Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ref workbook by path and name - VBA

Sub Quack()

Dim LookupWB As Workbook
Set LookupWB = Application.Workbooks("C:\Users\user1\Desktop\Book1.xlsx")

End Sub

This code gives an error:

Subscript out of range I think it's because of the "Set" line. How do you correctly reference a workbook by path?

If I write: Set LookupWB = Application.Workbooks("Book1.xlsx") (without full path) it work perfectly. Thanks a lot!

like image 537
Sam Avatar asked Dec 06 '12 20:12

Sam


People also ask

What is the difference between ThisWorkbook and ActiveWorkbook in VBA?

ThisWorkbook refers to the workbook in which Excel VBA code is being executed. ActiveWorkbook on the other hand refers to the Excel Workbook that current has focus, meaning is the front facing Excel Window. Often Excel VBA Developers mix these two common types of Workbooks in VBA.

What does ActiveWorkbook mean in VBA?

The ActiveWorkbook is the workbook that you (or the user) has selected before running the macro. The ActiveSheet is the worksheet tab that is currently selected before running the macro. If multiple sheets are selected, the ActiveSheet is the sheet that is currently being viewed.


1 Answers

I think you need to use the Open function first:

Workbooks.Open Filename:="C:\Users\user1\Desktop\Book1.xlsx"
Set LookupWB = Application.Workbooks("Book1.xlsx")
like image 151
thornomad Avatar answered Oct 07 '22 05:10

thornomad