In this Excel VBA Tutorial, you learn how to activate workbooks with macros.
This Excel VBA Activate Workbook Tutorial is currently under development. Subscribe to the Power Spreadsheets Newsletter to get future updates to this Excel VBA Tutorial.
Use the following Table of Contents to navigate to the Section you’re interested in.
VBA Code to Activate This Workbook
To activate this workbook, use the following statement in the applicable procedure.
Process to Activate This Workbook with VBA
- Refer to this workbook (the workbook where the macro is stored).
- Activate the workbook.
Main VBA Constructs Used to Activate This Workbook
(1) Application.ThisWorkbook property.
Returns a Workbook object representing the workbook where the macro is stored (the workbook where the macro is running).
(2) Workbook object.
Represents an Excel workbook.
(3) Workbook.Activate method.
Activates the (first) window associated with a workbook.
Macro Example to Activate This Workbook
The macro below does the following:
- Activate this workbook (the workbook where the macro is stored).
- Maximize the active window.
Sub ActivateThisWorkbook() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'This procedure: '(1) Activates this workbook (the workbook where the macro is stored) '(2) Maximizes the active window 'Activate this workbook ThisWorkbook.Activate 'Maximize the active window ActiveWindow.WindowState = xlMaximized End Sub
Effects of Executing Macro Example to Activate This Workbook
The image below illustrates the effects of using the macro example. In this example:
- 2 workbooks (“Excel VBA Activate Workbook” and “Book1”) are open.
- The “Book1” workbook is the active workbook.
- The macro example is stored in the “Excel VBA Activate Workbook” workbook.
When the macro is executed, Excel:
- Activates this workbook (“Excel VBA Activate Workbook”; the workbook where the macro example is stored); and
- Maximizes the active window.
Excel VBA Activate Workbook by Filename
VBA Code to Activate Workbook by Filename
To activate a workbook by filename, use the following structure/template in the applicable statement.
Workbooks("Filename").Activate
Process to Activate Workbook by Filename with VBA
- Refer to the workbook to activate by filename.
- Activate the applicable workbook.
Main VBA Constructs Used to Activate Workbook by Filename
(1) Application.Workbooks property.
Returns a Workbooks collection representing all open workbooks.
(2) Workbooks object.
Represents all open workbooks.
(3) Workbooks.Item property.
Returns a specific Workbook object from the applicable Workbooks collection.
(4) Workbook object.
Represents an Excel workbook.
(5) Workbook.Activate method.
Activates the (first) window associated with a workbook.
Cues to Activate Workbook by Filename with VBA
- Consider whether you must wrap the workbook filename in double quotes and parentheses ((“Filename”)).
- As a general rule: Include the complete filename, including file extension (for ex., “Filename.xlsm”), of a previously saved workbook.
Macro Example to Activate Workbook by Filename
The macro below does the following:
- Activate the workbook with filename “Excel VBA Activate Workbook.xlsm”.
- Maximize the active window.
Sub ActivateWorkbookByFilename() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'This procedure: '(1) Activates the workbook with filename "Excel VBA Activate Workbook.xlsm" '(2) Maximizes the active window 'Activate the workbook with filename "Excel VBA Activate Workbook.xlsm" Workbooks("Excel VBA Activate Workbook.xlsm").Activate 'Maximize the active window ActiveWindow.WindowState = xlMaximized End Sub
Effects of Executing Macro Example to Activate Workbook by Filename
The image below illustrates the effects of using the macro example. In this example:
- 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
- The “Book1” workbook is the active workbook.
When the macro is executed, Excel:
- Activates the workbook with filename “Excel VBA Activate Workbook.xlsm”; and
- Maximizes the active window.
Excel VBA Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)
VBA Code to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)
To activate a workbook with partial filename (with the Left, Mid, or Right functions), use the following structure/template in the applicable procedure.
VariableDeclarationStatement iWorkbook As Workbook For Each iWorkbook In Application.Workbooks If VbaBuiltInTextFunction(TextFunctionArgumentsIncludingWorkbookName) = "PartialWorkbookFilename" Then iWorkbook.Activate End If Next iWorkbook
Process to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)
- Declare iteration object variable (usually of the Workbook object data type).
- Loop through all open workbooks.
- Test whether the applicable part (for example, the beginning or end) of the name of the workbook (the loop is currently iterating through) matches the (known) partial filename (of the workbook to activate).
- If the condition is met (the applicable part of the name of the applicable workbook matches the partial filename of the workbook to activate), activate the workbook (the loop is currently iterating through).
Main VBA Constructs Used to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)
(1) Variable declaration statement.
One of the following 4 statements:
- Dim: Declares variables and allocates storage space.
- Private:
- Used at the module level.
- Declares module-level variables and allocates storage space.
- Public:
- Used at the module level.
- Declares global variables and allocates storage space.
- Static: Declares static variables and allocates storage space.
(2) Workbook object.
Represents an Excel workbook.
(3) For Each… Next statement.
Repeats a set of statements for each element in an array or collection.
(4) Application.Workbooks property.
Returns a Workbooks collection representing all open workbooks.
(5) Workbooks object.
Represents all open workbooks.
(6) Object variable.
A named storage location containing data (a reference to an object) that can be modified during procedure execution.
(7) If… Then… Else statement.
Conditionally executes a set of statements, depending on the value returned by a logical expression.
(8) VBA built-in text function.
One (or more) of the following VBA built-in text functions:
- Left: Returns a string containing a specific number of characters from the start (left side) of a string.
- Mid: Returns a string containing a specific number of characters from the middle (starting at a specific position) of a string.
- Right: Returns a string containing a specific number of characters from the end (right side) of a string.
- InStr: Returns the position of the first occurrence of one string inside another string.
(9) String.
A sequence of contiguous characters.
(10) Workbook.Activate method.
Activates the (first) window associated with a workbook.
Cues to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions) with VBA
- Consider explicitly declaring:
- The iteration object variable.
- The data type (usually Workbook object) of the iteration object variable.
- As a general rule, declare the iteration object variable:
- Using the Dim statement; and
- As of the Workbook object data type.
- If the scope of the iteration object variable is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
- Depending on the case you deal with, you may need to work with different versions of the If… Then… Else statement. Consider the following 4 basic versions of the If… Then… Else statement:
- If… Then. This is the version I use in the structure/template above.
- If… Then… Else.
- If… Then… ElseIf.
- If… Then… ElseIf… Else.
- The appropriate VBA built-in text function you work with depends on the case you deal with (for example, the structure and position of the known partial filename).
- As a general rule:
- The (main) string you use as one of the arguments of the VBA built-in text function (the string from which you extract characters) is the name of the applicable workbook (the For Each… Next statement is currently iterating through).
- Work with the Workbook.Name property to obtain the name of the applicable workbook. The Workbook.Name property returns a workbook’s name.
- When specifying the (known) partial filename, consider whether you must wrap this partial filename in double quotes (“PartialWorkbookFilename”).
Macro Example to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)
The macro below does the following:
- Declare an object variable (iWorkbook) of the Workbook object data type.
- Loop through all open workbooks.
- Test whether the first/leftmost 9 letters of the name of the workbook (the loop is currently iterating through) spell “Excel VBA”.
- If the condition is met (the first/leftmost 9 letters of the name of the applicable workbook spell “Excel VBA”), activate the workbook (the loop is currently iterating through).
Sub ActivateWorkbookPartialFilenameLeftMidRight() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'Declare iteration object variable Dim iWorkbook As Workbook 'Loop through all open workbooks For Each iWorkbook In Application.Workbooks 'Do the following: '(1) Test whether the first/leftmost 9 letters of the name of the workbook (the loop is currently iterating through) spell "Excel VBA" '(2) If the condition is met, activate the workbook (the loop is currently iterating through) If Left(iWorkbook.Name, 9) = "Excel VBA" Then iWorkbook.Activate Next iWorkbook End Sub
Effects of Executing Macro Example to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)
The image below illustrates the effects of using the macro example. In this example:
- 10 workbooks (“Excel VBA Activate Workbook.xlsm”, and “Book1” through “Book9”) are open.
- The “Book1” workbook is the active workbook.
When the macro is executed, Excel activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) contains the (known) partial filename (Excel VBA).
Excel VBA Activate Workbook with Partial Filename (with InStr Function)
VBA Code to Activate Workbook with Partial Filename (with InStr Function)
To activate a workbook with partial filename (with the InStr function), use the following structure/template in the applicable procedure.
VariableDeclarationStatement iWorkbook As Workbook For Each iWorkbook In Application.Workbooks If InStr(1, iWorkbook.Name, "PartialWorkbookFilename", StringCompareMethodConstant) > 0 Then iWorkbook.Activate End If Next iWorkbook
Process to Activate Workbook with Partial Filename (with InStr Function)
- Declare iteration object variable (usually of the Workbook object data type).
- Loop through all open workbooks.
- Test whether the name of the workbook (the loop is currently iterating through) contains the (known) partial filename (of the workbook to activate).
- If the condition is met (the name of the applicable workbook contains the partial filename of the workbook to activate), activate the workbook (the loop is currently iterating through).
Main VBA Constructs Used to Activate Workbook with Partial Filename (with InStr Function)
(1) Variable declaration statement.
One of the following 4 statements:
- Dim: Declares variables and allocates storage space.
- Private:
- Used at the module level.
- Declares module-level variables and allocates storage space.
- Public:
- Used at the module level.
- Declares global variables and allocates storage space.
- Static: Declares static variables and allocates storage space.
(2) Workbook object.
Represents an Excel workbook.
(3) For Each… Next statement.
Repeats a set of statements for each element in an array or collection.
(4) Application.Workbooks property.
Returns a Workbooks collection representing all open workbooks.
(5) Workbooks object.
Represents all open workbooks.
(6) Object variable.
A named storage location containing data (a reference to an object) that can be modified during procedure execution.
(7) If… Then… Else statement.
Conditionally executes a set of statements, depending on the value returned by a logical expression.
(8) InStr function.
Returns the position of the first occurrence of one string inside another string.
Accepts the following 4 arguments:
- start:
- Optional argument.
- The starting position for the search.
- If omitted, the search begins at the first character.
- string1:
- Required argument.
- The string you search in.
- string2:
- Required argument.
- The string you search for.
- compare:
- Optional argument.
- The string comparison method.
- If omitted, the module’s Option Compare setting applies.
(9) Workbook.Name property.
Returns a workbook’s name.
(10) String.
A sequence of contiguous characters.
(11) Greater than operator (>).
Compares 2 expressions and returns True, False, or Null as follows:
- True: If Expression1 > Expression2.
- False: If Expression1 <= Expression2.
- Null: If (either) Expression1 or Expression2 are Null.
(12) Workbook.Activate method.
Activates the (first) window associated with a workbook.
Cues to Activate Workbook with Partial Filename (with InStr Function) with VBA
- Consider explicitly declaring:
- The iteration object variable.
- The data type (usually Workbook object) of the iteration object variable.
- As a general rule, declare the iteration object variable:
- Using the Dim statement; and
- As of the Workbook object data type.
- If the scope of the iteration object variable is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
- Depending on the case you deal with, you may need to work with different versions of the If… Then… Else statement. Consider the following 4 basic versions of the If… Then… Else statement:
- If… Then. This is the version I use in the structure/template above.
- If… Then… Else.
- If… Then… ElseIf.
- If… Then… ElseIf… Else.
- As a general rule, set the arguments of the InStr function as follows:
- start: 1.
- string1: The name of the workbook the loop is currently iterating through, as returned by the Workbook.Name property.
- string2: The (known) partial filename.
- compare: vbBinaryCompare. vbBinaryCompare (usually) results in a case sensitive comparison.
- When specifying the (known) partial filename (as string2 argument of the InStr function), consider whether you must wrap this partial filename in double quotes (“PartialWorkbookFilename”).
Macro Example to Activate Workbook with Partial Filename (with InStr Function)
The macro below does the following:
- Declare an object variable (iWorkbook) of the Workbook object data type.
- Loop through all open workbooks.
- Test whether the name of the workbook (the loop is currently iterating through) contains “Excel VBA”.
- If the condition is met (the name of the applicable workbook contains “Excel VBA”), activate the workbook (the loop is currently iterating through).
Sub ActivateWorkbookPartialFilenameInStr() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'Declare iteration object variable Dim iWorkbook As Workbook 'Loop through all open workbooks For Each iWorkbook In Application.Workbooks 'Do the following: '(1) Test whether the name of the workbook (the loop is currently iterating through) contains "Excel VBA" '(2) If the condition is met, activate the workbook (the loop is currently iterating through) If InStr(1, iWorkbook.Name, "Excel VBA", vbBinaryCompare) > 0 Then iWorkbook.Activate Next iWorkbook End Sub
Effects of Executing Macro Example to Activate Workbook with Partial Filename (with InStr Function)
The image below illustrates the effects of using the macro example. In this example:
- 10 workbooks (“Excel VBA Activate Workbook.xlsm”, and “Book1” through “Book9”) are open.
- The “Book1” workbook is the active workbook.
When the macro is executed, Excel activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) contains the (known) partial filename (Excel VBA).
Excel VBA Activate Workbook Using Wildcard
VBA Code to Activate Workbook Using Wildcard
To activate a workbook using a wildcard, use the following structure/template in the applicable procedure.
VariableDeclarationStatement Dim iWorkbook As Workbook For Each iWorkbook In Application.Workbooks If iWorkbook.Name Like "WorkbookNameUsingWildcard" Then iWorkbook.Activate End If Next iWorkbook
Process to Activate Workbook Using Wildcard
- Declare iteration object variable (usually of the Workbook object data type).
- Loop through all open workbooks.
- Test whether the name of the workbook (the loop is currently iterating through) is like the (known) filename (of the workbook to activate). Use wildcards (as necessary) to specify the filename of the workbook to activate.
- If the condition is met (the name of the applicable workbook is like the filename -including any wildcards- of the workbook to activate), activate the workbook (the loop is currently iterating through).
Main VBA Constructs Used to Activate Workbook Using Wildcard
(1) Variable declaration statement.
One of the following 4 statements:
- Dim: Declares variables and allocates storage space.
- Private:
- Used at the module level.
- Declares module-level variables and allocates storage space.
- Public:
- Used at the module level.
- Declares global variables and allocates storage space.
- Static: Declares static variables and allocates storage space.
(2) Workbook object.
Represents an Excel workbook.
(3) For Each… Next statement.
Repeats a set of statements for each element in an array or collection.
(4) Application.Workbooks property.
Returns a Workbooks collection representing all open workbooks.
(5) Workbooks object.
Represents all open workbooks.
(6) Object variable.
A named storage location containing data (a reference to an object) that can be modified during procedure execution.
(7) If… Then… Else statement.
Conditionally executes a set of statements, depending on the value returned by a logical expression.
(8) Workbook.Name property.
Returns a workbook’s name.
(9) Like operator.
Compares a string against a pattern and returns True, False, or Null as follows:
- True: If the string matches the pattern.
- False: If the string doesn’t match the pattern.
- Null: If (either) the string or the pattern are Null.
You can combine the following elements when specifying the pattern:
- Wildcard characters.
- Character lists.
- Character ranges.
(10) String.
A sequence of contiguous characters.
(11) Workbook.Activate method.
Activates the (first) window associated with a workbook.
Cues to Activate Workbook Using Wildcard with VBA
- Consider explicitly declaring:
- The iteration object variable.
- The data type (usually Workbook object) of the iteration object variable.
- As a general rule, declare the iteration object variable:
- Using the Dim statement; and
- As of the Workbook object data type.
- If the scope of the iteration object variable is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
- Depending on the case you deal with, you may need to work with different versions of the If… Then… Else statement. Consider the following 4 basic versions of the If… Then… Else statement:
- If… Then. This is the version I use in the structure/template above.
- If… Then… Else.
- If… Then… ElseIf.
- If… Then… ElseIf… Else.
- Use the Like operator to compare the string returned by the Workbook.Name property (the name of the workbook the loop is currently iterating through) against a string with the filename (including any wildcards) of the workbook to activate.
- Use the following wildcards when specifying the pattern the Like operator works with:
- ?: Represents any single character.
- *: Represents any sequence of 0 or more characters.
- When specifying the pattern the Like operator works with (the filename -including any wildcards- of the workbook to activate), consider whether you must wrap this partial filename in double quotes (“WorkbookNameUsingWildcard”).
Macro Example to Activate Workbook Using Wildcard
The macro below does the following:
- Declare an object variable (iWorkbook) of the Workbook object data type.
- Loop through all open workbooks.
- Test whether the name of the workbook (the loop is currently iterating through) has the following structure:
- Starts with “Excel VBA”;
- Followed by any sequence of characters; and
- Ends with the “.xlsm” file extension.
- If the condition is met (the name of the applicable workbook is like the specified filename, including the * wildcard), activate the workbook (the loop is currently iterating through).
Sub ActivateWorkbookUsingWildcard() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'Declare iteration object variable Dim iWorkbook As Workbook 'Loop through all open workbooks For Each iWorkbook In Application.Workbooks 'Do the following: '(1) Test whether the name of the workbook (the loop is currently iterating through) has the following structure: '(1) Starts with "Excel VBA" '(2) Followed by any sequence of characters '(3) Ends with the ".xlsm" file extension '(2) If the condition is met, activate the workbook (the loop is currently iterating through) If iWorkbook.Name Like "Excel VBA*.xlsm" Then iWorkbook.Activate Next iWorkbook End Sub
Effects of Executing Macro Example to Activate Workbook Using Wildcard
The image below illustrates the effects of using the macro example. In this example:
- 10 workbooks (“Excel VBA Activate Workbook.xlsm”, and “Book1” through “Book9”) are open.
- The “Book1” workbook is the active workbook.
When the macro is executed, Excel activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) has the following structure:
- Starts with “Excel VBA”;
- Followed by any sequence of characters; and
- Ends with the “.xlsm” file extension.
Excel VBA Activate Workbook and Worksheet
VBA Code to Activate Workbook and Worksheet
To activate a workbook and a worksheet, use the following structure/template in the applicable statement.
WorkbookObjectReference.WorksheetObjectReference.Activate
Process to Activate Workbook and Worksheet with VBA
- Refer to the workbook and worksheet to activate.
- Activate the applicable worksheet.
Main VBA Constructs Used to Activate Workbook and Worksheet
(1) Workbook object.
Represents an Excel workbook.
(2) Workbook.Worksheets property.
Returns a Sheets collection representing all worksheets in the applicable workbook.
(3) Worksheets object.
Represents all worksheets in the applicable workbook.
(4) Worksheets.Item property.
Returns a specific Worksheet object from the applicable Worksheets collection.
(5) Worksheet object.
Represents a worksheet.
(6) Worksheet.Activate method.
Activates the applicable worksheet.
Cues to Activate Workbook and Worksheet with VBA
- Work with (among others) one of the following VBA constructs (or groups of constructs) to return a Workbook object:
- Application.Workbooks property, Workbooks object, and Workbooks.Item property.
- Application.ThisWorkbook property.
- As a general rule, identify the applicable Worksheet object (inside the Worksheets collection) using one of the following:
- An index number. The index number:
- Represents the position of the Worksheet object in the Worksheets collection.
- Is:
- Wrapped in parentheses ((IndexNumber)).
- Included after the reference to the Worksheets collection (Worksheets(IndexNumber)).
- The Worksheet object’s name (Worksheet.Name property). The name is:
- Wrapped in:
- Double quotes (“WorksheetName”); and
- Parentheses ((“WorksheetName”)).
- Included after the reference to the Worksheets collection (Worksheets(“WorksheetName”)).
- Wrapped in:
- An index number. The index number:
- You can (also) use a Worksheet object’s CodeName property (Worksheet.CodeName property) to refer to the applicable worksheet.
Macro Example to Activate Workbook and Worksheet
The macro below does the following:
- Activate:
- The “Excel VBA Activate Workbook.xlsm” workbook; and
- The “Activate Workbook and Worksheet” worksheet.
- Maximize the active window.
Sub ActivateWorkbookAndWorksheet() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'This procedure: '(1) Activates the "Activate Workbook and Worksheet" worksheet in the "Excel VBA Activate Workbook.xlsm" workbook '(2) Maximizes the active window 'Activate the "Activate Workbook and Worksheet" worksheet in the "Excel VBA Activate Workbook.xlsm" workbook Workbooks("Excel VBA Activate Workbook.xlsm").Worksheets("Activate Workbook and Worksheet").Activate 'Maximize the active window ActiveWindow.WindowState = xlMaximized End Sub
Effects of Executing Macro Example to Activate Workbook and Worksheet
The image below illustrates the effects of using the macro example. In this example:
- 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
- The “Book1” workbook is the active workbook.
- The “Sheet1” worksheet is the active worksheet in both (“Excel VBA Activate Workbook.xlsm” and “Book1”) workbooks.
When the macro is executed, Excel:
- Activates:
- The “Excel VBA Activate Workbook.xlsm” workbook; and
- The “Activate Workbook and Worksheet” worksheet.
- Maximizes the active window.
Excel VBA Activate Workbook and Chart Sheet
VBA Code to Activate Workbook and Chart Sheet
To activate a workbook and a chart sheet, use the following structure/template in the applicable statement.
WorkbookObjectReference.ChartObjectReference.Activate
Process to Activate Workbook and Chart Sheet with VBA
- Refer to the workbook and chart sheet to activate.
- Activate the applicable chart sheet.
Main VBA Constructs Used to Activate Workbook and Chart Sheet
(1) Workbook object.
Represents an Excel workbook.
(2) Workbook.Charts property.
Returns a Sheets collection representing all chart sheets in the applicable workbook.
(3) Charts object.
Represents all chart sheets in the applicable workbook.
(4) Charts.Item property.
Returns a specific Chart object from the applicable Charts collection.
(5) Chart object.
Represents a chart in a workbook. The chart can be either of the following:
- A chart sheet.
- An embedded chart (not the subject of this Section).
(6) Chart.Activate method.
Activates the applicable chart.
Cues to Activate Workbook and Chart Sheet with VBA
- Work with (among others) one of the following VBA constructs (or groups of constructs) to return a Workbook object:
- Application.Workbooks property, Workbooks object, and Workbooks.Item property.
- Application.ThisWorkbook property.
- As a general rule, identify the applicable Chart object (inside the Charts collection) using one of the following:
- An index number. The index number:
- Represents the position of the Chart object in the Charts collection.
- Is:
- Wrapped in parentheses ((IndexNumber)).
- Included after the reference to the Charts collection (Charts(IndexNumber)).
- The Chart object’s name (Chart.Name property). The name is:
- Wrapped in:
- Double quotes (“ChartSheetName”); and
- Parentheses ((“ChartSheetName”)).
- Included after the reference to the Charts collection (Charts(“ChartSheetName”)).
- Wrapped in:
- An index number. The index number:
- You can (also) use a Chart object’s CodeName property (Chart.CodeName property) to refer to the applicable chart sheet.
Macro Example to Activate Workbook and Chart Sheet
The macro below does the following:
- Activate:
- The “Excel VBA Activate Workbook.xlsm” workbook; and
- The “Activate Workbook Chart Sheet” chart sheet.
- Maximize the active window.
Sub ActivateWorkbookAndChartSheet() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'This procedure: '(1) Activates the "Activate Workbook Chart Sheet" chart sheet in the "Excel VBA Activate Workbook.xlsm" workbook '(2) Maximizes the active window 'Activate the "Activate Workbook Chart Sheet" chart sheet in the "Excel VBA Activate Workbook.xlsm" workbook Workbooks("Excel VBA Activate Workbook.xlsm").Charts("Activate Workbook Chart Sheet").Activate 'Maximize the active window ActiveWindow.WindowState = xlMaximized End Sub
Effects of Executing Macro Example to Activate Workbook and Chart Sheet
The image below illustrates the effects of using the macro example. In this example:
- 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
- The “Book1” workbook is the active workbook.
- The “Sheet1” worksheet is the active sheet in both (“Excel VBA Activate Workbook.xlsm” and “Book1”) workbooks.
When the macro is executed, Excel:
- Activates:
- The “Excel VBA Activate Workbook.xlsm” workbook; and
- The “Activate Workbook Chart Sheet” chart sheet.
- Maximizes the active window.
Excel VBA Activate Workbook with Variable Name
VBA Code to Activate Workbook with Variable Name
To activate a workbook with variable name (where the workbook filename is held by a variable), use the following structure/template in the applicable procedure.
VariableDeclarationStatement WorkbookFilenameVariable As String WorkbookFilenameVariable = WorkbookFilenameString Workbooks(WorkbookFilenameVariable).Activate
Process to Activate Workbook with Variable Name
- Declare variable (usually of the String data type) to represent workbook filename.
- Assign workbook filename to variable.
- Refer to the workbook to activate by using the applicable variable name (representing the workbook filename).
- Activate the applicable workbook.
Main VBA Constructs Used to Activate Workbook with Variable Name
(1) Variable declaration statement.
One of the following 4 statements:
- Dim: Declares variables and allocates storage space.
- Private:
- Used at the module level.
- Declares module-level variables and allocates storage space.
- Public:
- Used at the module level.
- Declares global variables and allocates storage space.
- Static: Declares static variables and allocates storage space.
(2) String data type.
Holds textual data (a sequence of characters representing the characters themselves).
(3) Assignment operator (=).
Assigns a value to a variable or property.
(4) Application.Workbooks property.
Returns a Workbooks collection representing all open workbooks.
(5) Workbooks object.
Represents all open workbooks.
(6) Workbooks.Item property.
Returns a specific Workbook object from the applicable Workbooks collection.
(7) Workbook object.
Represents an Excel workbook.
(8) Variable.
A named storage location containing data that can be modified during procedure execution.
(9) Workbook.Activate method.
Activates the (first) window associated with a workbook.
Cues to Activate Workbook with Variable Name with VBA
- Consider explicitly declaring:
- The variable representing the workbook filename.
- The data type (usually String) of the variable representing the workbook filename.
- As a general rule, declare the variable representing the workbook filename:
- Using the Dim statement; and
- As of the String data type.
- If the scope of the variable representing the workbook filename is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
- When assigning the workbook filename to the variable representing the workbook filename:
- Consider whether you must wrap the workbook filename in double quotes and parentheses ((“Filename”)).
- As a general rule:
- Include the complete filename, including file extension (for ex., “Filename.xlsm”), of a previously saved workbook.
- Do not include the file path.
Macro Example to Activate Workbook with Variable Name
The macro below does the following:
- Declare a variable (WorkbookFilename) of the String data type.
- Assign a string (Excel VBA Activate Workbook.xlsm) to the WorkbookFilename variable.
- Activate the workbook whose filename is represented by the WorkbookFilename variable.
- Maximize the active window.
Sub ActivateWorkbookWithVariableName() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'This procedure: '(1) Declares a variable (WorkbookFilename) of the String data type '(2) Assigns a string (Excel VBA Activate Workbook.xlsm) to the WorkbookFilename variable '(3) Activates the workbook whose filename is represented by the WorkbookFilename variable '(4) Maximizes the active window 'Declare variable to represent workbook filename Dim WorkbookFilename As String 'Assign workbook filename to variable WorkbookFilename = "Excel VBA Activate Workbook.xlsm" 'Activate the workbook whose filename is represented by the WorkbookFilename variable Workbooks(WorkbookFilename).Activate 'Maximize the active window ActiveWindow.WindowState = xlMaximized End Sub
Effects of Executing Macro Example to Activate Workbook with Variable Name
The image below illustrates the effects of using the macro example. In this example:
- 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
- The “Book1” workbook is the active workbook.
When the macro is executed, Excel:
- Activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) is held by a variable (WorkbookFilename); and
- Maximizes the active window.
Excel VBA Activate Workbook with Object Variable Name
VBA Code to Activate Workbook with Object Variable Name
To activate a workbook with object variable name (where the Workbook object is represented by an object variable), use the following structure/template in the applicable procedure.
VariableDeclarationStatement WorkbookObjectVariable As Workbook Set WorkbookObjectVariable = WorkbookObjectReference WorkbookObjectVariable.Activate
Process to Activate Workbook with Object Variable Name
- Declare object variable (usually of the Workbook object data type) to represent workbook.
- Assign Workbook object reference to object variable.
- Refer to the workbook to activate by using the applicable object variable name (representing the workbook).
- Activate the applicable workbook.
Main VBA Constructs Used to Activate Workbook with Object Variable Name
(1) Variable declaration statement.
One of the following 4 statements:
- Dim: Declares variables and allocates storage space.
- Private:
- Used at the module level.
- Declares module-level variables and allocates storage space.
- Public:
- Used at the module level.
- Declares global variables and allocates storage space.
- Static: Declares static variables and allocates storage space.
(2) Workbook object.
Represents an Excel workbook.
(3) Set statement.
Assigns an object reference to a variable or property.
(4) Application.Workbooks property.
Returns a Workbooks collection representing all open workbooks.
(5) Workbooks object.
Represents all open workbooks.
(6) Workbooks.Item property.
Returns a specific Workbook object from the applicable Workbooks collection.
(7) Object Variable.
A named storage location containing data (a reference to an object) that can be modified during procedure execution.
(8) Workbook.Activate method.
Activates the (first) window associated with a workbook.
Cues to Activate Workbook with Object Variable Name with VBA
- Consider explicitly declaring:
- The object variable representing the workbook.
- The data type (usually Workbook object) of the object variable representing the workbook.
- As a general rule, declare the object variable representing the workbook:
- Using the Dim statement; and
- As of the Workbook object data type.
- If the scope of the object variable representing the workbook is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
Macro Example to Activate Workbook with Object Variable Name
The macro below does the following:
- Declare an object variable (WorkbookObjectVariable) of the Workbook object data type.
- Assign a Workbook object reference (Excel VBA Activate Workbook.xlsm) to the WorkbookObjectVariable object variable.
- Activate the workbook represented by the WorkbookObjectVariable object variable.
- Maximize the active window.
Sub ActivateWorkbookWithObjectVariableName() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'This procedure: '(1) Declares an object variable (WorkbookObjectVariable) of the Workbook object data type '(2) Assigns a Workbook object reference (to the "Excel VBA Activate Workbook.xlsm" workbook) to the WorkbookObjectVariable object variable '(3) Activates the workbook represented by the WorkbookObjectVariable object variable '(4) Maximizes the active window 'Declare object variable to represent workbook Dim WorkbookObjectVariable As Workbook 'Assign Workbook object reference to object variable Set WorkbookObjectVariable = Workbooks("Excel VBA Activate Workbook.xlsm") 'Activate workbook represented by the WorkbookObjectVariable object variable WorkbookObjectVariable.Activate 'Maximize the active window ActiveWindow.WindowState = xlMaximized End Sub
Effects of Executing Macro Example to Activate Workbook with Object Variable Name
The image below illustrates the effects of using the macro example. In this example:
- 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
- The “Book1” workbook is the active workbook.
When the macro is executed, Excel:
- Activates the workbook whose reference (Excel VBA Activate Workbook.xlsm) is held by an object variable (WorkbookObjectVariable); and
- Maximizes the active window.
Excel VBA Open and Activate Workbook
VBA Code to Open and Activate Workbook
To open and activate a workbook, use the following structure/template in the applicable statement.
Workbooks.Open Filename:="PathAndFilename"
Process to Open and Activate Workbook with VBA
- Open the workbook with the Workbooks.Open method.
Main VBA Constructs Used to Open and Activate Workbook
(1) Workbooks.Open method.
Opens a workbook.
(2) Filename parameter.
The:
- First parameter of the Workbooks.Open method.
- Filename of the workbook to open.
Cues to Open and Activate Workbook with VBA
- When you open a workbook with the Workbooks.Open method, the opened workbook becomes the active workbook.
- Consider whether you must wrap the workbook path and filename in double quotes (“PathAndFilename”).
- As a general rule:
- Include the full path and filename (including file extension).
- If the workbook is stored in the default file folder (where Excel currently saves files by default), you can exclude the workbook’s path (use only the filename, including file extension).
Macro Example to Open and Activate Workbook
The macro below opens (and activates) the workbook with filename “Excel VBA Open and Activate Workbook.xlsx” stored in the Desktop folder.
Sub OpenAndActivateWorkbook() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/ 'Open the workbook with filename "Excel VBA Open and Activate Workbook.xlsx" stored in the Desktop folder. The opened workbook becomes the active workbook Workbooks.Open Filename:="C:UsersPowerSpreadsheetsDesktopExcel VBA Open and Activate Workbook.xlsx" End Sub
Effects of Executing Macro Example to Open and Activate Workbook
The image below illustrates the effects of using the macro example.
In this example (only) 1 workbook (“Excel VBA Activate Workbook”) is open. This is (also) the active workbook.
When the macro is executed, Excel opens and activates the workbook with filename “Excel VBA Open and Activate Workbook.xlsx” stored in the Desktop folder.
Home / VBA / VBA Activate Workbook (Excel File)
When you are working with multiple workbooks at the same time, I mean, when you have more than one workbook open at the same time then you need to know the method that can help you activate a workbook that you want to work on.
To activate a workbook using VBA, you need to use the Workbook.Activate method. In this method, you need to specify the workbook name using the Workbook object. It also allows you to use the workbook number instead of the workbook name, but you can only refer to the open workbooks.
In this tutorial, we look at different ways to use this method.
Steps to Activate a Workbook
- Type “Workbooks” to use the workbook object.
- Specify the workbook name in the double quotation marks.
- Enter a dot (.) to get the list of properties and methods.
- Select the Activate method from the list or you can also type it.
- In the end, run the code to activate the workbook.
Sub vba_activate_workbook()
Workbooks("Book3").Activate
End Sub
Note: If you try to activate a workbook that is not open, VBA will show an error.
Related: Activate a Worksheet using VBA
Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook
Activate a Workbook by using the Number
When you have multiple workbooks open all those workbooks are part of the workbook collection and have a number that you can use to refer to and then you can use the activate method with it. Here’s the code:
Sub vba_activate_workbook()
Workbooks(2).Activate
End Sub
And if you are trying to activate a workbook using a number that doesn’t exist, VBA will show you an error Run-time error ‘9’ (Subscript out of Range).
Activate ThisWorkbook
You can refer to the workbook where you are writing code by using the ThisWorkbook property. Let’s say you have five workbooks open at the same time but you are working on the “Book1.xlsm”, so when you run the following code, it will activate the “Book1.xlsm”.
Sub vba_activate_workbook()
ThisWorkbook.Activate
End Sub
Check Before Activating a Workbook
As I said, when you try to activate a workbook that is not opened VBA will show you an error. To deal with this problem the best way is to check for the workbook name first (if it’s open or not) and then activate it.
Sub vba_activate_workbook()
Dim wb As Workbook
For Each wb In Workbooks
If wb.Name = "Book3.xlsx" Then
wb.Activate
MsgBox "Workbook found and activated"
Exit Sub
End If
Next wb
MsgBox "Not found"
End Sub
By using the above code, you can specify a workbook name and this will first check for that workbook in all the open workbooks, and if it finds the workbook, it will activate it.
Notes
- When you are using the name of the workbook make sure to use the correct file extension
- If you want to activate a workbook that is not yet saved, then you need to use only the name of that workbook without suffixing the file extension.
More on VBA Workbooks
VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)
- VBA Workbook
VBA Activate Workbook — ActiveWorkbook
VBA Workbook Activate method will help us to activate a specific Workbook. It is helpful when we have opened multiple workbooks and want to access a particular workbook to manipulate or read some data from the Active Workbook.
- Why we need to activate a Workbook using VBA?
- VBA Activate Workbook – Syntax
- VBA Activate Workbook – with Name: Example 1
- VBA Activate Workbook – with Number: Example 2
- VBA Activate Workbook – ThisWorkbook: Example 3
- VBA ActiveWorkbook Object
- Set ActiveWorkbook in Excel VBA
- VBA ThisWorkbook Object in Excel
- Set ThisWorkbook in Excel VBA
- VBA Activate Workbook – Best Approach
- VBA Activate Workbook – Instructions
Why we need to activate a Workbook using VBA?
When we deal with multiple workbooks and if you want to read or write to a specific workbook. You can easily activate a workbook using VBA. And do whatever tasks which you want to do.
VBA Activate Workbook – Syntax
Here is the example syntax to activate a Workbook using VBA. You can use either a Workbook name or Workbook number. When we specify the workbook number if it the order of the workbooks which you are opening.
Workbooks(“Your Workbook Name”).Activate
‘Or
Workbooks(
‘And you can use Thisworkbook.Activate method to activate the workbook with the current procedure/macro
ThisWorkbook.Activate
VBA Activate Workbook – with Name:Example 1
Please see the below VBA codes to activate a Workbook. In this example we are activating a workbook named “Project1”.
'Workbook Activate Sub sb_Activate_Workbook() Workbooks("Project1").Activate End Sub
VBA Activate Workbook – with Number:Example 2
Please see the below VBA codes to activate a Workbook using workbook number. In this example we are activating a workbook 2 in the currently opened workbooks collection.
'Workbook Activate Sub sb_Activate_Workbook_Number() Workbooks(2).Activate End Sub
VBA Activate Workbook – ThisWorkbook:Example 2
Please see the below VBA codes to activate a currently running macro workbook. This will be very useful while dealing with the multiple workbooks.
Let’s say you have your macros in “MyProjects1.xlsm” and you have opened multiple workbooks say Book2.xlsx, Book3.xlsx, Book4.xlsx, and you can deal with any workbook and come back to your original workbook with the currently running code by just referring to ThisWorkbook Object.
'Workbook Activate Sub sb_Activate_Workbook_ThisWorkbook() 'Lets say you have written this macro in "MyProjects1.xlsm 'And say you want to write to Book2 Workbooks("Book2").Activate Sheet1.Range("A1") = 1 'Now you want to write to Book3 Workbooks("Book3").Activate Sheet1.Range("A1") = 1 'You can come back to activate the currently macro running workbook ThisWorkbook.Activate 'This will activate "MyProjects1.xlsm End Sub
VBA ActiveWorkbook Object
We can refer the currently activated Excel Workbook using Excel VBA ActiveWorkbook object. ActiveWorkbook VBA object is very usefull while automating tasks and working on currently active Excel WorkBook in the active workbook window. If you ignore the ActiveWorkbook object while refering any other object like sheet, range or chart, VBA will treat the ActiveWorkbook as the current Workbook by default. For example: Following are the two macro statements both will refer the active ActiveWorkbook.
ActiveWorkbook.ActiveSheet.Range("A1")="Some Value" 'OR ActiveSheet.Range("A1")="Some Value" 'OR Range("A1")="Some Value"
both the above statements print some value at Range A1 of Activesheet.
Set ActiveWorkbook in Excel VBA
It is very useful to refer the Active Eorkbook in Excel VBA by setting into a Variable. We can assign and set ActiveWorkbook to an object and refer at any place of the procedure. Here is the syntax to Set ActiveWorkbook in VBA.
Sub sbSetActiveWorkbookVBA() Dim wb As Workbook Set wb = ActiveWorkbook Set ws = wb.ActiveSheet ws.Range("A1") = "Some Value" End Sub
This code will print the some value at Range A1 of ActiveWorkbook.
VBA ThisWorkbook Object in Excel VBA
While automating the Excel Tasks, we usually have all our macros in one Excel Workbook (say Book1.xlsm) and deal with with multiple workbboks and files. We activate different workbooks to access the file objects and do some activity. For example, we activate Book12.xlsx to enter some data, we may open and format some ranges. While accessing the different objects in different workbooks, we generally activate the Workbook and do perform some operation with Excel VBA Macros.
What if you need to wok on the same workbook(Book1.xlsm) where all your macros are written. You do not required to activate and use VBA ActiveWorokbook object. Instead, you can use VBA Thisworkbook object to deal with your macro file.
Here is the simple macro to insert some values in ThisWorkbook using VBA.
ThisWorkbook.Sheets(1).Range("A1") = "Some Value"
Set ThisWorkbook in Excel VBA
We can also set ThisWorkbook to a variable using VBA and access it whereever it is required. For example the following macro will do print the some value at A1 of Sheet 1 of ThisWorkbook.
Sub sbThisWorkbookVBA() Dim wb As Workbook Set wb = ThisWorkbook Set ws = wb.Sheets(1) ws.Range("A1") = "Some Value" End Sub
VBA Activate Workbook – Best Approach
Note: Always better to use the Workbook name, instead of workbook number. The best is to assign the workbook to an object and then do whatever task you want to do with that particular Workbook object.
When working with multiple workbooks, you should refer the workbook with exact workbook name to correctly update your data into target workbook. Create workbook object and refer the workbook with the object whenever you require.
Let us see the another example to understand the accessing the workbooks using objects. You do not need to activate workbook to deal with any workbook.
Sub sb_Activate_Workbook_Object() 'Declare the objects here Dim wbkMain, wbk_A, wbk_B, wbk_C 'Set the Workbooks to Objects Set wbMain = ThisWorkbook Set wbk_A = Workbooks("Book2") Set wbk_B = Workbooks("Book3") Set wbk_C = Workbooks("Book4") 'Now deal with your workbooks wbk_A.Sheets(1).Range("A1") = wbkMain.Sheet1.Range("A1") End Sub
VBA Activate Workbook – Instructions
Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:
- Open an Excel Workbook
- Press Alt+F11 to Open VBA Editor
- Insert a Module from Insert Menu
- Copy the above code for activating a range and Paste in the code window(VBA Editor)
- Save the file as macro enabled workbook
- Press ‘F5’ to run it or Keep Pressing ‘F8’ to debug the code line by line.
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
-
-
- In this topic:
-
- Why we need to activate a Workbook using VBA?
- VBA Activate Workbook – Syntax
- VBA Activate Workbook – with Name:Example 1
- VBA Activate Workbook – with Number:Example 2
- VBA Activate Workbook – ThisWorkbook:Example 2
- VBA ActiveWorkbook Object
- Set ActiveWorkbook in Excel VBA
- VBA ThisWorkbook Object in Excel VBA
- Set ThisWorkbook in Excel VBA
- VBA Activate Workbook – Best Approach
- VBA Activate Workbook – Instructions
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
3 Comments
-
Lisa
April 27, 2019 at 12:34 AM — ReplyHello,
How do you activate a workbook whose full name changes because it is downloaded from the internet and gets a number appended to each file? In this case, you would not always know the full name in order to activate it. How do you call this workbook? I am using
Workbooks(ActiveWorkbookName).Activate
but some users are getting a run-time error 1004 “Application-defined or Object-defined error”
-
Neha.Meghani
May 7, 2020 at 6:39 AM — ReplyHi,
Can you please help me with code how to consolidate different workbooks into one workbook.
-
M Jairam
August 13, 2020 at 10:14 AM — ReplyI used the coding to Activate workbooks Best Approach..using workbook objects . I created 4 work books.Myprojects,Books2,3,4 as per your recommendation.It did not work ..Run-time error Subscript out of range..
***** Can you help me in this….Thanks..
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
In this Article
- The Workbook Object
- Workbook Index Number
- Activate Workbook, ActiveWorkbook, and ThisWorkbook
- Activate Workbook
- ActiveWorkbook
- ThisWorkbook
- Open Workbook
- Open and Assign to Variable
- Open File Dialog
- Create New (Add) Workbook
- Add New Workbook to Variable
- Close Workbook
- Close & Save
- Close without Save
- Workbook Save As
- Other Workbook VBA Examples
- Workbook Name
- Protect Workbook
- Loop Through all Open Workbooks
- Workbook Activate Event
This guide will introduce you working with the Workbook Object in VBA.
The Workbook Object
First, in order to interact with workbooks in VBA, you must understand the Workbook Object.
With the workbook object, you can reference workbooks by their name like this:
Workbooks("Book2.xlsm").Activate
However, this code will only work if the workbook is open. If the workbook is closed, you will need to provide the full workbook path:
Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")
Instead of typing out the full path, if your desired workbook is in the same directory as the workbook where your code is stored, you could use this line code to open the workbook:
Workbooks.Open (ThisWorkbook.Path & "book2.xlsm")
This makes use of the ThisWorkbook object that we will discuss in the next section.
Workbook Index Number
Last, you can reference workbooks by their “Index Number”. The index number of a workbook corresponds to the order that the workbook was opened (technically its the workbook’s position in the Workbooks Collection).
Workbooks(1).Activate
This is useful if you want to do something like close the first (or last) opened workbook.
Activate Workbook, ActiveWorkbook, and ThisWorkbook
If a workbook is NOT ACTIVE, you can access the Workbook’s objects like this:
Workbooks("Book2.xlsm").Sheets("Sheet1").Range("A1").value = 1
However, if the workbook is Active, you can omit the workbook object:
Sheets("Sheet1").Range("A1").value = 1
And if you want to interact with the workbook’s active sheet, you can also ommit the sheets object:
Range("A1").value = 1
Activate Workbook
To activate a workbook, use the Activate Method.
Workbooks("Book2.xlsm").Activate
Now you can interact with Book2’s object’s without explicitly stating the workbook name.
ActiveWorkbook
The ActiveWorkbook object always refer to the active workbook. This is useful if you’d like to assign the ActiveWorkbook to a variable to use later.
Dim wb As Workbook
Set wb = ActiveWorkbook
ThisWorkbook
The ThisWorkbook object always refers to the workbook where the running code is stored. To activate ThisWorkbook, use this line of code:
ThisWorkbook.Activate
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Open Workbook
To open a workbook, use the Open Method:
Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")
The newly opened workbook will always become the ActiveWorkbook, allowing you to easily interact with it.
ActiveWorkbook.Save
The Open Method has several other arguments, allowing you to open read-only, open a password-protected workbook, and more. It’s covered here in our article about Opening / Closing Workbooks.
Open and Assign to Variable
You can also open a workbook and assign it to a variable at the same time:
Dim wb As Workbook
Set wb = Workbooks.Open("C:UsersStevePC2Downloadsbook2.xlsm")
Open File Dialog
You can also trigger the Open File Dialog Box like this:
Sub OpenWorkbook ()
Dim strFile As String
strFile = Application.GetOpenFilename()
Workbooks.Open (strFile)
End Sub
VBA Programming | Code Generator does work for you!
Create New (Add) Workbook
This line of code will create a new workbook:
Workbooks.Add
The new workbook now becomes the ActiveWorkbook, allowing you to interact with it (ex. save the new workbook).
Add New Workbook to Variable
You can also add a new workbook directly to a variable:
Dim wb As Workbook
Set wb = Workbooks.Add
Close Workbook
Close & Save
To close a workbook with saving, use the Close Method with SaveChanges set to TRUE:
ActiveWorkbook.Close SaveChanges:=True
Close without Save
To close without saving, set SaveChanges equal to FALSE:
ActiveWorkbook.Close SaveChanges:=False
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook Save As
The SaveAs Method is used to save a workbook as.
To save a workbook with a new name, in the same directory, you can imply use this:
ActiveWorkbook.SaveAs "new"
where “new” is the new file name.
To save a workbook in a new directory with a specific file extension, simply specify the new directory and file name:
ActiveWorkbook.SaveAs "C:UsersStevePC2Downloadsnew.xlsm"
Other Workbook VBA Examples
Workbook Name
To get the name of a workbook:
MsgBox ActiveWorkbook.Name
Protect Workbook
To protect the workbook structure from editing, you can use the Protect Method (password optional):
Workbooks("book1.xlsm").Protect "password"
To unprotect a workbook use the UnProtect Method:
Workbooks("book1.xlsm").Unprotect "password"
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Loop Through all Open Workbooks
To loop through all open workbooks:
Sub LoopThroughWBs()
Dim wb As Workbook
For Each wb In Workbooks
MsgBox wb.Name
Next wb
End Sub
Workbook Activate Event
You can run some code whenever a specific workbook is opened with the Workbook Open Event.
Place this procedure your workbook’s ThisWorkbook Module:
Private Sub Workbook_Open()
Sheets("sheet1").Activate
End Sub
This procedure will activate Sheet1 every time the workbook is opened.
In this tutorial, I will cover the how to work with workbooks in Excel using VBA.
In Excel, a ‘Workbook’ is an object that is a part of the ‘Workbooks’ collection. Within a workbook, you have different objects such as worksheets, chart sheets, cells and ranges, chart objects, shapes, etc.
With VBA, you can do a lot of stuff with a workbook object – such as open a specific workbook, save and close workbooks, create new workbooks, change the workbook properties, etc.
So let’s get started.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
Referencing a Workbook using VBA
There are different ways to refer to a Workbook object in VBA.
The method you choose would depend on what you want to get done.
In this section, I will cover the different ways to refer to a workbook along with some example codes.
Using Workbook Names
If you have the exact name of the workbook that you want to refer to, you can use the name in the code.
Let’s begin with a simple example.
If you have two workbooks open, and you want to activate the workbook with the name – Examples.xlsx, you can use the below code:
Sub ActivateWorkbook() Workbooks("Examples.xlsx").Activate End Sub
Note that you need to use the file name along with the extension if the file has been saved. If it hasn’t been saved, then you can use the name without the file extension.
If you’re not sure what name to use, take help from the Project Explorer.
If you want to activate a workbook and select a specific cell in a worksheet in that workbook, you need to give the entire address of the cell (including the Workbook and the Worksheet name).
Sub ActivateWorkbook() Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate Range("A1").Select End Sub
The above code first activates Sheet1 in the Examples.xlsx workbook and then selects cell A1 in the sheet.
You will often see a code where a reference to a worksheet or a cell/range is made without referring to the workbook. This happens when you’re referring to the worksheet/ranges in the same workbook that has the code in it and is also the active workbook. However, in some cases, you do need to specify the workbook to make sure the code works (more on this in the ThisWorkbook section).
Using Index Numbers
You can also refer to the workbooks based on their index number.
For example, if you have three workbooks open, the following code would show you the names of the three workbooks in a message box (one at a time).
Sub WorkbookName() MsgBox Workbooks(1).Name MsgBox Workbooks(2).Name MsgBox Workbooks(3).Name End Sub
The above code uses MsgBox – which is a function that shows a message box with the specified text/value (which is the workbook name in this case).
One of the troubles I often have with using index numbers with Workbooks is that you never know which one is the first workbook and which one is the second and so on. To be sure, you would have to run the code as shown above or something similar to loop through the open workbooks and know their index number.
Excel treats the workbook opened first to have the index number as 1, and the next one as 2 and so on.
Despite this drawback, using index numbers can come in handy.
For example, if you want to loop through all the open workbooks and save all, you can use the index numbers.
In this case, since you want this to happen to all the workbooks, you’re not concerned about their individual index numbers.
The below code would loop through all the open workbooks and close all except the workbook that has this VBA code.
Sub CloseWorkbooks() Dim WbCount As Integer WbCount = Workbooks.Count For i = WbCount To 1 Step -1 If Workbooks(i).Name <> ThisWorkbook.Name Then Workbooks(i).Close End If Next i End Sub
The above code counts the number of open workbooks and then goes through all the workbooks using the For Each loop.
It uses the IF condition to check if the name of the workbook is the same as that of the workbook where the code is being run.
If it’s not a match, it closes the workbook and moves to the next one.
Note that we have run the loop from WbCount to 1 with a Step of -1. This is done as with each loop, the number of open workbooks is decreasing.
ThisWorkbook is covered in detail in the later section.
Also read: How to Open Excel Files Using VBA (Examples)
Using ActiveWorkbook
ActiveWorkbook, as the name suggests, refers to the workbook that is active.
The below code would show you the name of the active workbook.
Sub ActiveWorkbookName() MsgBox ActiveWorkbook.Name End Sub
When you use VBA to activate another workbook, the ActiveWorkbook part in the VBA after that would start referring to the activated workbook.
Here is an example of this.
If you have a workbook active and you insert the following code into it and run it, it would first show the name of the workbook that has the code and then the name of Examples.xlsx (which gets activated by the code).
Sub ActiveWorkbookName() MsgBox ActiveWorkbook.Name Workbooks("Examples.xlsx").Activate MsgBox ActiveWorkbook.Name End Sub
Note that when you create a new workbook using VBA, that newly created workbook automatically becomes the active workbook.
Using ThisWorkbook
ThisWorkbook refers to the workbook where the code is being executed.
Every workbook would have a ThisWorkbook object as a part of it (visible in the Project Explorer).
‘ThisWorkbook’ can store regular macros (similar to the ones that we add-in modules) as well as event procedures. An event procedure is something that is triggered based on an event – such as double-clicking on a cell, or saving a workbook or activating a worksheet.
Any event procedure that you save in this ‘ThisWorkbook’ would be available in the entire workbook, as compared to the sheet level events which are restricted to the specific sheets only.
For example, if you double-click on the ThisWorkbook object in the Project Explorer and copy-paste the below code in it, it will show the cell address whenever you double-click on any of the cells in the entire workbook.
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) MsgBox Target.Address End Sub
While ThisWorkbook’s main role is to store event procedure, you can also use it to refer to the workbook where the code is being executed.
The below code would return the name of the workbook in which the code is being executed.
Sub ThisWorkbookName() MsgBox ThisWorkbook.Name End Sub
The benefit of using ThisWorkbook (over ActiveWorkbook) is that it would refer to the same workbook (the one that has the code in it) in all the cases. So if you use a VBA code to add a new workbook, the ActiveWorkbook would change, but ThisWorkbook would still refer to the one that has the code.
Creating a New Workbook Object
The following code will create a new workbook.
Sub CreateNewWorkbook() Workbooks.Add End Sub
When you add a new workbook, it becomes the active workbook.
The following code will add a new workbook and then show you the name of that workbook (which would be the default Book1 type name).
Sub CreateNewWorkbook() Workbooks.Add MsgBox ActiveWorkbook.Name End Sub
Open a Workbook using VBA
You can use VBA to open a specific workbook when you know the file path of the workbook.
The below code will open the workbook – Examples.xlsx which is in the Documents folder on my system.
Sub OpenWorkbook() Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx") End Sub
In case the file exists in the default folder, which is the folder where VBA saves new files by default, then you can just specify the workbook name – without the entire path.
Sub OpenWorkbook() Workbooks.Open ("Examples.xlsx") End Sub
In case the workbook that you’re trying to open doesn’t exist, you’ll see an error.
To avoid this error, you can add a few lines to your code to first check whether the file exists or not and if it exists then try to open it.
The below code would check the file location and if it doesn’t exist, it will show a custom message (not the error message):
Sub OpenWorkbook()
If Dir("C:UserssumitDocumentsExamples.xlsx") <> "" Then
Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx")
Else
MsgBox "The file doesn't exist"
End If
End Sub
You can also use the Open dialog box to select the file that you want to open.
Sub OpenWorkbook()
If Dir("C:UserssumitDocumentsExamples.xlsx") <> "" Then
Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx")
Else
MsgBox "The file doesn't exist"
End If
End Sub
The above code opens the Open dialog box. When you select a file that you want to open, it assigns the file path to the FilePath variable. Workbooks.Open then uses the file path to open the file.
In case the user doesn’t open a file and clicks on Cancel button, FilePath becomes False. To avoid getting an error in this case, we have used the ‘On Error Resume Next’ statement.
Saving a Workbook
To save the active workbook, use the code below:
Sub SaveWorkbook() ActiveWorkbook.Save End Sub
This code works for the workbooks that have already been saved earlier. Also, since the workbook contains the above macro, if it hasn’t been saved as a .xlsm (or .xls) file, you will lose the macro when you open it next.
If you’re saving the workbook for the first time, it will show you a prompt as shown below:
When saving for the first time, it’s better to use the ‘Saveas’ option.
The below code would save the active workbook as a .xlsm file in the default location (which is the document folder in my system).
Sub SaveWorkbook() ActiveWorkbook.SaveAs Filename:="Test.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
If you want the file to be saved in a specific location, you need to mention that in the Filename value. The below code saves the file on my desktop.
Sub SaveWorkbook() ActiveWorkbook.SaveAs Filename:="C:UserssumitDesktopTest.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
If you want the user to get the option to select the location to save the file, you can use call the Saveas dialog box. The below code shows the Saveas dialog box and allows the user to select the location where the file should be saved.
Sub SaveWorkbook() Dim FilePath As String FilePath = Application.GetSaveAsFilename ActiveWorkbook.SaveAs Filename:=FilePath & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
Note that instead of using FileFormat:=xlOpenXMLWorkbookMacroEnabled, you can also use FileFormat:=52, where 52 is the code xlOpenXMLWorkbookMacroEnabled.
Saving All Open Workbooks
If you have more than one workbook open and you want to save all the workbooks, you can use the code below:
Sub SaveAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks wb.Save Next wb End Sub
The above saves all the workbooks, including the ones that have never been saved. The workbooks that have not been saved previously would get saved in the default location.
If you only want to save those workbooks that have previously been saved, you can use the below code:
Sub SaveAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Path <> "" Then wb.Save End If Next wb End Sub
Saving and Closing All Workbooks
If you want to close all the workbooks, except the workbook that has the current code in it, you can use the code below:
Sub CloseandSaveWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Name <> ThisWorkbook.Name Then wb.Close SaveChanges:=True End If Next wb End Sub
The above code would close all the workbooks (except the workbook that has the code – ThisWorkbook). In case there are changes in these workbooks, the changes would be saved. In case there is a workbook that has never been saved, it will show the save as dialog box.
Save a Copy of the Workbook (with Timestamp)
When I am working with complex data and dashboard in Excel workbooks, I often create different versions of my workbooks. This is helpful in case something goes wrong with my current workbook. I would at least have a copy of it saved with a different name (and I would only lose the work I did after creating a copy).
Here is the VBA code that will create a copy of your workbook and save it in the specified location.
Sub CreateaCopyofWorkbook() ThisWorkbook.SaveCopyAs Filename:="C:UserssumitDesktopBackupCopy.xlsm" End Sub
The above code would save a copy of your workbook every time you run this macro.
While this works great, I would feel more comfortable if I had different copies saved whenever I run this code. The reason this is important is that if I make an inadvertent mistake and run this macro, it will save the work with the mistakes. And I wouldn’t have access to the work before I made the mistake.
To handle such situations, you can use the below code that saves a new copy of the work each time you save it. And it also adds a date and timestamp as a part of the workbook name. This can help you track any mistake you did as you never lose any of the previously created backups.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) ThisWorkbook.SaveCopyAs Filename:="C:UserssumitDesktopBackupCopy" & Format(Now(), "dd-mm-yy-hh-mm-ss-AMPM") & ".xlsm" End Sub
The above code would create a copy every time you run this macro and add a date/time stamp to the workbook name.
Create a New Workbook for Each Worksheet
In some cases, you may have a workbook that has multiple worksheets, and you want to create a workbook for each worksheet.
This could be the case when you have monthly/quarterly reports in a single workbook and you want to split these into one workbook for each worksheet.
Or, if you have department wise reports and you want to split these into individual workbooks so that you can send these individual workbooks to the department heads.
Here is the code that will create a workbook for each worksheet, give it the same name as that of the worksheet, and save it in the specified folder.
Sub CreateWorkbookforWorksheets() Dim ws As Worksheet Dim wb As Workbook For Each ws In ThisWorkbook.Worksheets Set wb = Workbooks.Add ws.Copy Before:=wb.Sheets(1) Application.DisplayAlerts = False wb.Sheets(2).Delete Application.DisplayAlerts = True wb.SaveAs "C:UserssumitDesktopTest" & ws.Name & ".xlsx" wb.Close Next ws End Sub
In the above code, we have used two variable ‘ws’ and ‘wb’.
The code goes through each worksheet (using the For Each Next loop) and creates a workbook for it. It also uses the copy method of the worksheet object to create a copy of the worksheet in the new workbook.
Note that I have used the SET statement to assign the ‘wb’ variable to any new workbook that is created by the code.
You can use this technique to assign a workbook object to a variable. This is covered in the next section.
Assign Workbook Object to a Variable
In VBA, you can assign an object to a variable, and then use the variable to refer to that object.
For example, in the below code, I use VBA to add a new workbook and then assign that workbook to the variable wb. To do this, I need to use the SET statement.
Once I have assigned the workbook to the variable, all the properties of the workbook are made available to the variable as well.
Sub AssigntoVariable() Dim wb As Workbook Set wb = Workbooks.Add wb.SaveAs Filename:="C:UserssumitDesktopExamples.xlsx" End Sub
Note that the first step in the code is to declare ‘wb’ as a workbook type variable. This tells VBA that this variable can hold the workbook object.
The next statement uses SET to assign the variable to the new workbook that we are adding. Once this assignment is done, we can use the wb variable to save the workbook (or do anything else with it).
Looping through Open Workbooks
We have already seen a few examples codes above that used looping in the code.
In this section, I will explain different ways to loop through open workbooks using VBA.
Suppose you want to save and close all the open workbooks, except the one with the code in it, then you can use the below code:
Sub CloseandSaveWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Name <> ThisWorkbook.Name Then wb.Close SaveChanges:=True End If Next wb End Sub
The above code uses the For Each loop to go through each workbook in the Workbooks collection. To do this, we first need to declare ‘wb’ as the workbook type variable.
In every loop cycle, each workbook name is analyzed and if it doesn’t match the name of the workbook that has the code, it’s closed after saving its content.
The same can also be achieved with a different loop as shown below:
Sub CloseWorkbooks() Dim WbCount As Integer WbCount = Workbooks.Count For i = WbCount To 1 Step -1 If Workbooks(i).Name <> ThisWorkbook.Name Then Workbooks(i).Close SaveChanges:=True End If Next i End Sub
The above code uses the For Next loop to close all the workbooks except the one that has the code in it. In this case, we don’t need to declare a workbook variable, but instead, we need to count the total number of open workbooks. When we have the count, we use the For Next loop to go through each workbook. Also, we use the index number to refer to the workbooks in this case.
Note that in the above code, we are looping from WbCount to 1 with Step -1. This is needed as with each loop, the workbook gets closed and the number of workbooks gets decreased by 1.
Error while Working with the Workbook Object (Run-time error ‘9’)
One of the most common error you may encounter when working with workbooks is – Run-time Error ‘9’ – Subscript out of range.
Generally, VBA errors are not very informative and often leave it to you to figure out what went wrong.
Here are some of the possible reasons that may lead to this error:
- The workbook that you’re trying to access does not exist. For example, if I am trying to access the fifth workbook using Workbooks(5), and there are only 4 workbooks open, then I will get this error.
- If you’re using a wrong name to refer to the workbook. For example, if your workbook name is Examples.xlsx and you use Example.xlsx. then it will show you this error.
- If you haven’t saved a workbook, and you use the extension, then you get this error. For example, if your workbook name is Book1, and you use the name Book1.xlsx without saving it, you will get this error.
- The workbook you’re trying to access is closed.
Get a List of All Open Workbooks
If you want to get a list of all the open workbooks in the current workbook (the workbook where you’re running the code), you can use the below code:
Sub GetWorkbookNames() Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range("A1").Activate For i = 1 To wbcount Range("A1").Offset(i - 1, 0).Value = Workbooks(i).Name Next i End Sub
The above code adds a new worksheet and then lists the name of all the open workbooks.
If you want to get their file path as well, you can use the below code:
Sub GetWorkbookNames() Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range("A1").Activate For i = 1 To wbcount Range("A1").Offset(i - 1, 0).Value = Workbooks(i).Path & "" & Workbooks(i).Name Next i End Sub
Open the Specified Workbook by Double-clicking on the Cell
If you have a list of file paths for Excel workbooks, you can use the below code to simply double-click on the cell with the file path and it will open that workbook.
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Workbooks.Open Target.Value End Sub
This code would be placed in the ThisWorkbook code window.
To do this:
- Double click on the ThisWorkbook object in the project explorer. Note that the ThisWorkbook object should be in the workbook where you want this functionality.
- Copy and paste the above code.
Now, if you have the exact path of the files that you want to open, you can do that by simply double-clicking on the file path and VBA would instantly open that workbook.
Where to Put the VBA Code
Wondering where the VBA code goes in your Excel workbook?
Excel has a VBA backend called the VBA editor. You need to copy and paste the code into the VB Editor module code window.
Here are the steps to do this:
- Go to the Developer tab.
- Click on the Visual Basic option. This will open the VB editor in the backend.
- In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
You May Also Like the Following Excel VBA Tutorials:
- How to Record a Macro in Excel.
- Creating a User Defined Function in Excel.
- How to Create and Use Add-in in Excel.
- How to Resue Macros by placing it in the Personal Macro Workbook.
- Get the List of File Names from a Folder in Excel (with and without VBA).
- How to Use Excel VBA InStr Function (with practical EXAMPLES).
- How to Sort Data in Excel using VBA (A Step-by-Step Guide).