Select workbook using VBA
This page shows how you can assign an open workbook to a Workbook
variable using a Set
statement.
This is the preferred way of programming as against using the ActiveWorkbook
(using Select
).
Select workbook by name
The Item
property of the Workbooks
collection is used to returns a single Workbook
object from the collection. It is called like this:
Dim wb As Workbook
Set wb = Application.Workbooks.Item(Index:="Demo.xlsx")
Workbook
to select is already open in Excel.
The Workbooks
collection here is obtained from the Application.Workbooks
procedure.
The Item
procedure returns an object of type Workbook
which is optionally assigned to a variable wb
.
Normally in the Index
you will use the filename to identify, though strictly speaking you could use the position number in the collection.
... or shorter:
Dim wb As Workbook
Set wb = Workbooks("Demo.xlsx")
- Because the
Application.Workbooks
method is globalApplication
may be left out from the statement. - A common practice with collection items is to use a shorthand: Instead of the full
collection.Item(...)
the shortercollection(...)
is used. - As it does not make things clearer we also leave out the
Item
parameter name(Index:=...)
Select workbook with variable name
More often than not you will want to apply you procedures on variable file names.
For this you will use a String
variable that will be assigned a value in some way, e.g. by using a file selection dialog.
Dim strWorkbook As String: strWorkbook =
Dim wb As Workbook
Set wb = Workbooks(strWorkbook)