我正在尝试将对象从已关闭的工作簿复制到当前打开的工作簿,我正在尝试的代码是:
Sub test()
Dim WB1 As Workbook
Dim WBDest As Workbook
Set WBDest = Workbooks(ActiveWorkbook.Path & "\" & ActiveWorkbook.Name)
'Open up your first workbook, copy data
Set WB1 = Workbooks.Open("path to the folder\testbook.xlsx")
WB1.Sheets("Sheet1").Range("A1:F12").Copy
'paste in second workbook
WBDest.Sheets("Sheet1").Range("A1").PasteSpecial
'Close first workbook
WB1.Close savechanges:=False
End Sub
我不断得到一个"下标超出范围"如果我删除了WBDest信息并使用了activeworkbook,它会复制该对象并将其粘贴到与当时的activeworkbook相同的工作簿中。
有人可以指导我,并帮我弄清楚我做错了什么。
感谢。
答案 0 :(得分:1)
如AndyG所述,它应该是WBDest = Workbooks.Open(..)。然后更换:
Sub test()
Dim WB1 As Workbook
Dim WBDest As Workbook
Set WBDest = Workbooks.Open(ActiveWorkbook.Path & "\" & ActiveWorkbook.Name)
'Open up your first workbook, copy data
Set WB1 = Workbooks.Open("path to the folder\testbook.xlsx")
WB1.Sheets("Sheet1").Range("A1:A7").Copy
'paste in second workbook
WBDest.Sheets("Sheet1").Range("A1:A7").PasteSpecial
'Close first workbook
WB1.Close savechanges:=False
End Sub
请注意,如果工作簿已按您的建议打开,那么在第5行您可以轻松编写WBDest = ActiveWorkbook
。