我正在尝试编写一些简单的代码,以从一个工作簿(源)提取范围并将其粘贴到另一工作簿(合并)中。我希望在运行“合并”工作簿中的宏时指定“源”工作簿。
当我使用“ Workbooks.Open(....)”时,以下代码可以正常工作,但是当我删除“ .Open”时(例如,Workbooks(## filename ##)),我得到下标超出范围的错误。
我正在使用Excel 2013,但似乎两个工作簿都在同一实例中(我可以在VBA项目列表中看到它们)。文件名是正确的,并且包含扩展名(同样,当我“打开”它时,下面的代码可以完美地工作,但是我希望能够多次运行该代码,并且我不想一直打开文件再来一次。
该代码也可以与ActiveWorkbook一起使用,但是需要我先导航到“源”工作簿,然后运行也不是首选的宏。
Sub CopyData()
Dim wbk_data as Workbook 'source book
Dim wbk_cons as Workbook 'consolidate book
Dim wbk_data_s as Worksheet 'source sheet
Dim wbk_cons_s as Worksheet 'consolidate sheet
Dim target As String
target = [wbk_name].Value2 'filename is included as a named cell in the worksheet
Set wbk_data = Workbooks(target) 'this is the line that doesn't work.
'Set wbk_data = Workbooks.Open(target) does work in this place
Set wbk_cons = ThisWorkbook
Set wbk_data_s = wbk_data.Worksheets("ExampleSrcSheet")
Set wbk_cons_s = wbk_cons.Worksheets("ExampleConsSheet")
感谢任何建议。
答案 0 :(得分:0)
检查它是否已经打开,如果没有打开,则将其打开:
Dim target As String
target = [wbk_name].Value2
'see if it's already open
On Error Resume Next 'ignore any error on the next line
Set wbk_data = Workbooks(target)
On Error Goto 0 'stop ignoring errors
'if not already open, open it
If wbk_data Is Nothing Then
Set wbk_data = Workbooks.Open(target)
End If