简体   繁体   中英

VBA Excel Workbooks Object Variable

I am trying to set two workbook variables - here are the first four lines of my code:

Dim wb1 As Workbook
Dim wb2 As Workbook

Set wb1 = Workbooks("C:\Users\ShaneM\Documents\File1.xlsx")
Set wb2 = Workbooks("C:\Users\ShaneM\Documents\Computer Languages\VBA\File2.xlsm")

The error I am getting on line 3 is:

Runtime error 9 - Subscript Out Of Range

The files definitely exist in these locations. Obviously much learning to be done. What am I doing wrong, please?

Thank you.

The .Workbooks() is a collection of workbook objects opened in the current Application object (which you don't write in your code, but it's called by default).

The collection .Workbooks() goes out of range because the workbook is not currently open in your Application ; if you want to use your workbook, in fact, what you need to do is opening it into the current Excel Application instance:

Set wb1 = Workbooks.Open("C:\...")

This will though cause the workbook to show up, because you're opening in your current application, and unfortunately is not possible to open it in Visible=False mode. However, you might want to use a new Excel instance set to Visible = False , so you will be able to read the content without actually displaying it. Which means, in code:

Set excObj = CreateObject("Excel.Application")
excObj.Visible = False
Set wb1 = excObj.Workbooks.Open("C:\...")

Please note that I'm specifying to open the workbook with excObj , which is not the current Application but another object of the same type that is intentionally set to Visible = False .

According to https://msdn.microsoft.com/en-us/library/office/ff841074.aspx , the Workbooks collection contains only the currently opened workbooks. The error simply tells you, that the requested workbook is not opened at the moment.

You have to use the method Workbooks.Open :

Set wb1 = Workbooks.Open("C:\Users\ShaneM\Documents\File1.xlsx")

When the Workbook is already opened, you can then use the property Workbooks.Item to get the object (note that you can omit .Item , as it is the default property of the Workbooks collection).

Set wb1 = Workbooks("File1.xlsx")

Also note that the names of opened workbooks must be unique within the same application. Ie the following will not work:

Set wb1 = Workbooks.Open("C:\Folder1\File.xlsx")
Set wb2 = Workbooks.Open("C:\Folder2\File.xlsx")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM