Reference to a workbook

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,832
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
I am trying to refer to a workbook saved on my PC but I don't know why the following code doesn't work:

Code:
    Dim wb As Workbook
    Set wb = Workbooks("C:\Users\myname\Documents\myexcelfile.xlsm")

The error message is:

Code:
Run-time error '9'

Subscript out of range

When I recorded a macro to open the workbook, this code was generated:

Code:
Workbooks.Open Filename:="C:\Users\myname\Documents\myexcelfile.xlsm"

so I know my file and its location is correct.
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
Is the workbook open?
 
Upvote 0
In that case you need to use
VBA Code:
Set wb = Workbooks.Open("C:\Users\myname\Documents\myexcelfile.xlsm")
 
Upvote 0
In that case you need to use
VBA Code:
Set wb = Workbooks.Open("C:\Users\myname\Documents\myexcelfile.xlsm")
Thanks, your suggestion did work but (obviously) opens the workbook.

I recall sometime ago that I could reference a workbook without opening it or am I mistaken?

I tried experimenting by opening myexcelfile.xlsm manually, then running this code from another workbook:

Code:
    Dim wb As Workbook
    Set wb = Workbooks("C:\Users\myname\Documents\myexcelfile.xlsm")

but it still failed.

However, this worked:

Code:
    Dim wb As Workbook
    Set wb = Workbooks("myexcelfile.xlsm")
 
Upvote 0
You cannot set a variable to a workbook if it is not open.
 
Upvote 0

Forum statistics

Threads
1,214,911
Messages
6,122,198
Members
449,072
Latest member
DW Draft

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top