Copying from one workbook to open workbook

浪子不回头ぞ 提交于 2019-12-20 07:25:14

问题


I am trying to copy an object from a closed workbook to the currently open workbook, the code I have bee experimenting with is:

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

I keep getting a "subscript out of range" error with this, if I remove the WBDest info and used activeworkbook instead, it copies the object and pastes it in the same workbook as it is the activeworkbook at the time.

Could someone please guide me on this and help me figure out what I am doing wrong.

Thanks.


回答1:


As mentioned by AndyG, it should be WBDest = Workbooks.Open(..). The replacement is then:

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

Note that on the 5th line you could as easily write WBDest = ActiveWorkbook if the workbook is already open as you suggest.



来源:https://stackoverflow.com/questions/23891847/copying-from-one-workbook-to-open-workbook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!