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")

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")

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)

icon

Try the Code VBA editor add-in