将范围读入数组并将值复制到两个单独的工作表

时间:2017-01-30 15:03:30

标签: vba excel-vba excel

我想将两个不同变量变量读取的两个范围的值复制到两个不同的工作表中。如果其中一个目标工作表处于活动状态,则代码仅复制值,并且根本不复制两个范围的值。我希望代码能够在没有这两个工作表处于活动状态的情况下成功运行。

此外,如果我在代码中没有包含 On Error Resume Next 位,那么它偶尔会抛出运行时错误1004 。我不明白为什么它变化无常。

请您告诉我您对如何按需运行的想法?

    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

1 个答案:

答案 0 :(得分:1)

代替:

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

Cells是一个变量,表示Worksheets个对象,因此该对象也应该被引用。否则,它会占用activesheet对象并且可能发生错误 - 例如RangeCell可以被视为拥有不同的父母。

来自这里的信息: https://msdn.microsoft.com/en-us/library/office/ff194567.aspx