Vba 将范围读入数组并将值复制到两个单独的工作表上
我想将读取到两个不同变量中的两个范围的值复制到两个不同的工作表上。仅当其中一个目标工作表处于活动状态且根本不复制两个范围的值时,代码才会复制值。我希望代码能够在这两个工作表都不处于活动状态的情况下成功运行 此外,如果我没有在代码中包含错误恢复下一位,那么它会偶尔抛出运行时错误1004。我不明白为什么它变化无常 你能告诉我你对如何让它按预期运行的想法吗Vba 将范围读入数组并将值复制到两个单独的工作表上,vba,excel,Vba,Excel,我想将读取到两个不同变量中的两个范围的值复制到两个不同的工作表上。仅当其中一个目标工作表处于活动状态且根本不复制两个范围的值时,代码才会复制值。我希望代码能够在这两个工作表都不处于活动状态的情况下成功运行 此外,如果我没有在代码中包含错误恢复下一位,那么它会偶尔抛出运行时错误1004。我不明白为什么它变化无常 你能告诉我你对如何让它按预期运行的想法吗 Sub historical() With Application .ScreenUpdating = False:
Sub historical()
With Application
.ScreenUpdating = False: .DisplayAlerts = False: .DisplayStatusBar = False: .EnableEvents = False: .Calculation = xlCalculationAutomatic: .AskToUpdateLinks = False
End With
Dim wb As Workbook: Set wb = Workbooks("Tardiness")
Dim wk1 As Worksheet: Set wk1 = wb.Worksheets("loginlogout") 'Source worksheet 1
Dim wk2 As Worksheet: Set wk2 = wb.Worksheets("auxcodes") 'Source worksheet 2
Dim wk4 As Worksheet: Set wk4 = wb.Worksheets("loginlogouth") 'Destination worksheet 1
Dim wk5 As Worksheet: Set wk5 = wb.Worksheets("auxcodesh") 'Destination worksheet 1
Dim lastrow4 As Long
Dim lastrow5 As Long
lastrow1 = wk1.Range("A" & Rows.Count).End(xlUp).Row
lastrow2 = wk2.Range("A" & Rows.Count).End(xlUp).Row
Debug.Print lastrow4, lastrow2
On Error Resume Next
lastrow5 = wk5.Range("A" & Rows.Count).End(xlUp).Row
Dim aux() As Variant
aux = wk2.Range("A5:AR" & lastrow2).Value
wk5.Range(Cells(lastrow5 + 1, 1), Cells(lastrow5 + UBound(aux), UBound(aux, 2))).Value = aux
Erase aux
Dim loginout() As Variant
loginout = wk1.Range("A2:K" & lastrow1).Value
lastrow4 = wk4.Range("A" & Rows.Count).End(xlUp).Row
wk4.Range(Cells(lastrow4 + 1, 1), Cells(lastrow4 + UBound(loginout), UBound(loginout, 2))).Value = loginout
lastrow4 = wk4.Range("A" & Rows.Count).End(xlUp).Row
Debug.Print lastrow4
With wk4.Range("C2:F" & lastrow4)
.NumberFormat = "hh:mm:ss"
End With
With wk4.Range("I2:K" & lastrow4)
.NumberFormat = "hh:mm:ss"
End With
Erase loginout
With Application
.ScreenUpdating = False: .DisplayAlerts = False: .DisplayStatusBar = False: .EnableEvents = False: .Calculation = xlCalculationAutomatic: .AskToUpdateLinks = False
End With
End Sub
代替:
wk5.Range(Cells(lastrow5 + 1, 1), Cells(lastrow5 + UBound(aux), UBound(aux, 2))).Value = aux
尝试:
With wks5
.Range(.Cells(lastrow5 + 1, 1), .Cells(lastrow5 + UBound(aux), UBound(aux, 2))).Value = aux
end with
单元格是一个变量,表示工作表对象,因此也应引用该对象。否则,它将接受activesheet对象,并且可能会发生错误-例如,范围和单元格可以被视为具有不同的父对象
此处提供的信息:
当您收到运行时错误时,它会抛出到哪一行?您可以尝试以下操作:wk5.Rangewk5.cellsastraw5+1,1,wk5.cellsastraw5+UBoundaux,UBoundaux,2。值=aux@Vityata答案是,您需要使用正确的父级来限定所有范围对象。另一种方法是Resize:wk5.cellsasratrow5+1,1.ResizeUBoundaux,1,UBoundaux,2.Value=AuxSide注意,与您所面临的问题并不相关:应用程序中底部的值应全部设置为True,顶部使用xlCalculationAutomatic,如果您可能打算使用xlCalculationManual,并且确实必须在代码的下一步插入错误恢复,那么您应该记住在错误恢复结束之前添加错误恢复0。理想情况下,您应该处理这个问题,而不是盲目地忽略它。另外,你的wk4.Range语句是无用的。只需使用wk4.RangeC2:F&lastrow4.NumberFormat=hh:mm:ssinstead@ScottCraner,Vityata,Victor Moraes谢谢你的建议。现在代码运行顺利,因为我已经纠正了您建议的问题。