Workbook object in excel vba

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.

Worksheets Object in Excel VBA - file name in 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).

Workbook Object in VBA - ThisWorkbook

‘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:

Workbook Object in VBA - Warning when saving Workbook for the first time

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.

Workbook Object in VBA - Runtime 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:

  1. Go to the Developer tab.Using Workbooks in Excel VBA - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. 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.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.Using Workbooks in Excel VBA - inserting module
  5. Copy and paste the code in the module window.Using Workbooks in Excel VBA - inserting module

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

In Excel, a workbook is one of the most important of all the Excel Objects, and it is also essential to understand how to use and refer to workbooks while writing VBA codes.

In this tutorial, we will explore all the things that you need to know. But, the first thing you need to understand are objects that are involved in using workbooks in VBA.

Objects you need to know:

  • Workbooks Object
  • Workbook Object

Both of these objects sound the same, but there’s a core difference between both of them.

Workbooks Object

In VBA, the workbooks object represents the collection of the workbooks that are open in Microsoft Excel. Imagine you have ten workbooks open at the same time. And you want to refer to the one workbook out of them. In that case, you need to use the workbook object to refer to that one workbook using its name.

Workbook Object

In VBA, the workbook object represents one single workbook from the entire collection of workbooks open at present in Microsoft Excel. The best way to understand this is to think about declaring a variable as a workbook that you want to use to refer to a particular workbook in the code.

Useful Links: Add Developer Tab | Visual Basic Editor | Run a Macro | Personal Macro Workbook

To work with workbooks in VBA, the first thing that you need to know is how to refer to a workbook in a macro. Here’s the happy thing: there are multiple ways to refer to a workbook. And ahead, we will explore each one of them.

1. By Name

The easiest way to refer to a workbook is to use its name. Let’s say you want to activate the workbook Book1.xlsx, in that case, the code that you need to use should be like the following:

Referring to a workbook with its name is quite simple, you need to specify the name, and that’s it. But here’s one thing that you need to take care of: if a workbook is not saved, then you need to use only the name. And if saved, then you need to use the name along with the extension.

2. By Number

When you open a workbook, Excel gives an index number to that workbook, and you can use that number to refer to a workbook. The workbook that you have opened at first will have the index number “1” and the second will have “2” and so on.

This method might seem less real to you as it’s hard to know which workbook is on which index number. But there’s one situation where this method is quite useful to use, and that’s looping through all the open workbooks.

3. By ThisWorkbook

This workbook is a property that helps you to refer to the workbook where you are writing the code. Let’s say you are writing the code in “Book1” and use the ThisWorkbook to save the workbook. Now even when you change the name of the workbook, you won’t need to change the code.

The above code counts the number of sheets in the workbook where this code is written and shows a message box with the result.

4. By ActiveWorkbook

If you want to refer to a workbook that is active, then you need to use the “ActiveWorkbook” property. The best use of this property is when you are sure which workbook is activated now. Or you have already activated the workbook that you want to work.

The above code activates the workbook “Book1” first and then uses the active workbook property to save and close the active workbook.

Access all the Methods and Properties

In VBA, whenever you refer to an object, VBA allows you to access the properties and methods that come with that object. In the same way, the workbook object comes with properties and methods. To access them, you need to define the workbook first and then enter a dot.

The moment you type a dot (.), it shows the list of properties and methods. Now, you must have a question in your mind about how to identify which one is a property and which one is a method.

Here’s the trick. If you look closely, you can identify a moving green brick and grey hand before each name on the list. So, all the properties have that grey hand before the name and methods have a moving green brick.

For example to use a Method with Workbook

Imagine you want to close a workbook (which is a method), you need to type or select “Close” from the list.

After that, you need to enter starting parentheses to get the IntelliSense to know the arguments you need to define.

With the close method, there are three arguments that you need to define, and as you can see, all these arguments are optional, and you can skip them if you want. But some methods don’t have arguments (for example: activate)

For example to use a Property with Workbook

Imagine you want to count the sheets from the workbook “book1” in that case, you need to use the “Sheets” property and then the further count property of it.

In the above code, as I said, you have book1 defined, and then the sheet property refers to all the sheets, and then the count property to count them. And when you run this code, it shows you a message box with the result.

Using “WITH” Statement with Workbook

In VBA, there’s a “With” statement that can help you work with a workbook while writing a macro efficiently. Let’s see the below example where you have three different code lines with the same workbook, i.e., ActiveWorkbook.

With the “WITH statement”, you can refer to the active workbook a single time, and use all the properties and methods that you have in the code.

  • First of all, you need to start with the starting statement “With ActiveWorkbook” and end the statement with “End With”.
  • After that, you need to write the code between this statement that you have in the above example.

As you can see in the above code we have referred to the ActiveWorkbook one using the WITH statement, and then all the properties and methods need to be used.

Sub vba_activeworkbook_with_statement()
With ActiveWorkbook
    .Sheets.Add Count:=5
    .Charts.Visible = False
    .SaveAs ("C:UsersDellDesktopmyFolderbook2.xlsx")
End With
End Sub

Let me tell you a simple real-life example to make you understand everything. Imagine you ask me to go to room 215 to get the water bottle, and when I come back, you again send me to room 215 to get a pen, and then again send me back to get a laptop. Now here’s the thing: All the things that you told me to get are in room 215. So better if you sent me to room 215 and told me to get all three things at once.

Read: With – End With

Declaring a Variable as a Workbook

Sometimes you need to declare a variable as a workbook to use it further in the code. Well, this doesn’t require anything special for you to do.

  1. Use the DIM Statement (Declare).
  2. Write the name of the Variable.
  3. Define the type of the variable as Workbook.

Dealing with Errors

When you work with a workbook(s) object in VBA, there are chances that you need to deal with errors as well. Take an example of the “Run-time Error 9: Subscript out of Range” error. This error can occur for various reasons.

  • The workbook that you are trying to refer to is not opened.
  • Might be you have misspelled the name.
  • The workbook you are referring to is not yet saved and you are using the extension along with the name.
  • If you are using the index number to refer to a workbook and the number you have used is greater than the total number of workbooks open.

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!

automacro

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 open close file

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.

Workbook Object in MS Excel VBA. Workbook is an object in Microsoft Excel represents a member of the Workbooks collection. Workbooks collection contains list of all workbook objects. Again each workbook consists of different objects like Worksheets, Ranges, cells, Charts, shapes, chart sheets, etc.

Let us see a complete guide on VBA Workbook object. So let’s start learning about complete VBA Workbook object explained with examples in this tutorial.

Task Description Action performed (Sample Example)
Workbook Reference
  1. ActiveWorkbook Reference
  2. ThisWorkbook Reference
  3. Reference Workbook by Index
  4. Reference Workbook by Object
  5. Workbooks in Workbooks Collection Reference
  6. Reference Workbook Explicitly(By Name)
Declare Assign Workbook variable ‘Variable Declaration
Dim oWorkbook As Workbook

‘Define Object Variable
Set oWorkbook = Workbooks(“VBA Tutorial.xlsm”)

Create new Workbook Workbooks.Add
Create new Workbook with Name ActiveWorkbbok.SaveAs Filename:=”VBA Tutorial.xlsm”
Open Workbook Workbooks.Open (“D:VBA Tutorial.xlsm”)
Open Workbook as Read Only Workbooks.Open Filename:=”D:VBA Tutorial.xlsm”, ReadOnly:=True
Activate Workbook Workbooks(“VBA Tutorial.xlsm”).Activate
Rename Workbook Name “D:VBAF1Old_File.xlsx” As “D:VBAF1New_File.xlsx”
Copy Workbook ‘Variable declaration
Dim oFSO As FileSystemObject
Dim sFilePath As String
Dim dFilePath As String

‘Source & Destination File Path
sFilePath = “D:VBAF1VBA Functionsa.xlsm”
dFilePath = “D:BlogVBA Functionsa.xlsm”

‘Reference Workbook by Object named oWorkbook
Set oFSO = CreateObject(“Scripting.FileSystemObject”)

‘Copy Workbook
oFSO.CopyFile sFilePath, dFilePath, True

Save Workbook Workbooks(“VBA Tutorial.xlsm”).Save
SaveAs Workbook ActiveWorkbook.SaveAs Filename:=”D:VBAF1New_File.xlsx”
List all open Workbooks ‘VBA List Open Workbooks in Excel
Sub VBA_List_All_Open_Workbooks()

‘Variable declaration
Dim xWorkbook As Workbook
Dim sWorkbookName As String
Dim iCount As Integer

‘Intialise value to a variable
iCount = 2

Sheets(“WB_Names”).Range(“A1”) = “Names of Available Workbooks”

‘Loop through all workbooks
For Each xWorkbook In Application.Workbooks
Sheets(“WB_Names”).Range(“A” & iCount) = xWorkbook.Name & vbCrLf

‘Increase value
iCount = iCount + 1
Next

End Sub

List Open Unsaved Workbooks ‘Variable declaration
Dim xWorkbook As Workbook

‘Loop through all workbooks
For Each xWorkbook In Application.Workbooks

‘Check Workbook is current Workbook or not
If xWorkbook.Name <> ThisWorkbook.Name Then
‘Check if the file names has an extension

If InStr(Right(xWorkbook.Name, 5), “.xl”) > 0 Then
‘Save and Close Workbook
xWorkbook.Close SaveChanges:=True
Else
Debug.Print xWorkbook.Name
End If
End If
Next

Check Workbook Exists ‘Variable declaration
Dim sFilePath As String

‘Value assigned to a variable
sFilePath = “D:FolderNameSample.xlsx”

‘Check Workbook exists or not
If Dir(sFilePath) = “” Then
‘Workbook is not available
MsgBox “File doesn’t exist.”, vbCritical, “File is not available”
Else
‘Workbook is available
MsgBox “File exists.”, vbInformation, “File available”
End If

Active & Current Workbook Name ActiveWorkbook.Name
ThisWorkbook.Name
Check for Open Workbook ‘Variable declaration
Dim oWorkbook As Workbook

For Each oWorkbook In Workbooks
If oWorkbook.Name = “Test_Workbook.xls” Then
MsgBox “Specified Workbook is open.”, vbInformation, “VBAF1 : Automation Made Easy”
Else
MsgBox “Specified Workbook is not open.”, vbCritical, “VBAF1 : Automation Made Easy”
End If
Next

Difference Between ActiveWorkbook and ThisWorkbook ActiveWorkbook represents the Workbook in active window which has focus on the screen.
ThisWorkbook represents the current Workbook in which the current VBA code is running or executing.
Get Workbook Path & Location ActiveWorkbook.Path
ActiveWorkbook.FullName
Protect Workbook ActiveWorkbook.Protect Structure:=True, Windows:=False, Password:=”12345″
UnProtect Workbook ActiveWorkbook.Unprotect Password:=”12345″
RunAutoMacros Workbook With ActiveWorkbook
.RunAutoMacros xlAutoOpen
.Open
End With
Access Workbook by Index Workbooks (1)
Create backup of current workbook ActiveWorkbook.SaveCopyAs “D:VBAF1New_File.xlsx”
Close Workbook and Save ActiveWorkbook.Close SaveChanges:=True
Close Workbook without Save ActiveWorkbook.Close SaveChanges:=False
Delete Workbook Kill “D:VBAF1Old_File.xlsx”
Close All Workbooks without prompt ‘Variable Declaration
Dim oWorkbook As Workbook

Application.ScreenUpdating = False
For Each oWorkbook In Application.Workbooks
If oWorkbook.Name <> ThisWorkbook.Name Then
oWorkbook.Close
End If
Next
Application.ScreenUpdating = True

Delete All Workbooks in a folder On Error Resume Next
Kill “D:VBAF1*.xl*”

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Excel VBA is an object-oriented programming language, which means in excel every component is an object. The superset of all the objects of excel is the excel application itself. The Excel Application Object is the root of all the other objects in excel. It contains Workbook Object. The Workbook Object contains another object such as Worksheet Object which includes all the worksheets present in a particular workbook. The Worksheet Object contains Cells Object. To perform any task or operation in excel we need to follow this excel object hierarchy.

Excel-Object-Hierarchy

Workbooks Object

In excel VBA, the workbooks object represents the collection of the workbook which are open in the excel application at the same time. This is the reason we write it as plural- Workbooks Object, which means it contains more than one workbook. In order to access a single workbook from the workbooks object, we can use the following VBA to access it from its name.

command-to-access-workbook

How to Refer a Workbook in VBA?

To refer a workbook in excel VBA, we can use the following different methods:

By Name

We can easily refer to a workbook using its name. We need to define a procedure in VBA and declare our excel workbook name. Make sure that the user name is only if the workbook is not saved otherwise we need to define the name along with its extension.

Referring-to-a-workbook

By Number

The excel application maintains an index order for all the workbooks we open. It gives numbers 1 to the first workbook, 2 to the second workbook, and so on. We can also use these numbers to refer to the workbook.

Note: It became really difficult to remember which workbook we have opened in which order. So, it is quite less used.

referring-by-number

By ActiveWorkbook Property

We can refer to a workbook using the ActiveWorkbook property. Using ActiveWorkbook we can refer to the workbook which is in an active state, which means the workbook is open in excel.

using-activeworkbook

Access Methods and Properties of a Workbook

Like any other object-oriented programming language, In VBA whenever we refer to an object it gives us access to all the methods and properties of that object. Similarly, when we access the Workbook Object, we get access to all its properties and methods.

Accessing Methods of Workbooks Object

In order to access the methods of the workbook object we will use the dot(.) operator. Once, we use our workbooks object as soon as we will use the dot(.) operator, it will display the list of methods associated with that particular object.

Access-methods-of-Workbooks-object

Accessing Properties of Workbooks Object

Similar to methods, we can use the dot(.) operator to access the properties of the workbook object.

Accessing-properties

As we can see, we have 3 different sheets currently open in our excel, if we run our procedure it will display the count as 3 in a message box.

Output

Worksheets Object

In excel VBA, the worksheets object represents the collection of the worksheets which are open in the excel workbook. This is the reason we write it as plural- Worksheets Object, which means it contains more than one worksheet.

How to Refer a Worksheet in VBA?

By Name

In excel, we can refer to a sheet using its name. By default, Excel creates sheets in natural number ordering. For example, Sheet1, Sheet2, etc. We can also give our own name to these sheets.

referring-by-name

By Number

We can also use sheet numbers to refer to a sheet in excel. The two operations to refer to a sheet, Sheets() and Worksheets() work in different ways while accessing the sheets by number.

Operation

Working

Sheets(n)

This is used to refer to the nth sheet starting from the first sheet

Worksheets(n)

This is used to refer to the nth sheet itself.

referring-by-number

By ActiveSheet Property

In excel VBA, we can also refer to a sheet using the ActiveSheet property.

referring-by-activesheet-property

As above, we can see we have the GFGCourse sheet active. When we run our procedure, it will pop up a message box with the active sheet name is.

Output

Access Method and Properties of a Worksheet

Similar to the Workbook object, Worksheet Object also comes up with different methods and properties. In excel VBA, we can access methods and properties of excel worksheet objects using the dot(.) operator.

Methods-and-properties-of-worksheet

Like this post? Please share to your friends:
  • Workbook not found excel
  • Workbook names from excel
  • Workbook file name excel
  • Workbook excel как открыть
  • Workbook event excel vba