我正在尝试将一个动态范围从一个workbook1 sheet1复制到workbook2 sheet2。该代码有效,但是仅当我激活workbook1 sheet1时,如果我激活workbook1 sheet2,代码就会失败。
我的代码是:
Sub CopyOrders()
Dim wB1 As Worksheet
Set wB1 = Workbooks("Master.xlsx").Worksheets("Data")
Dim RngCe1 As Range
Set RngCe1 = wB1.Cells(Rows.Count, "B").End(xlUp).Offset(0, 11)
Dim RngCe2 As Range
Set RngCe2 = wB1.Range("A1:A7000").FIND("Grand Total", LookAt:=xlPart).Offset(-1, 23)
Dim NewRng As Range
Set NewRng = Range(RngCe1.Address & ":" & RngCe2.Address)
Dim wB2 As Worksheet
Set wB2 = Workbooks("Report.xlsx").Worksheets("Orders")
Dim DesRng As Range
Set DesRng = wB2.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Resize(, 12)
NewRng.Copy
DesRng.PasteSpecial xlPasteValues
End Sub
答案 0 :(得分:0)
问题出在这里:
Set DesRng = wB2.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Resize(, 12)
您需要在此处指定工作表,而不是Rows.Count
,否则将使用活动工作表。因此wB2.Rows.Count
可以解决问题。
并且仍然:您正在定义工作工作表变量,并使用w B 2对其进行命名。为清楚起见,请考虑将其重命名为w S 2。