Excel vba sub workbooks

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.

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

“We are drowning in information but starved for knowledge.” – John Naisbitt

This post provides a complete guide to using the VBA Workbook.

If you want to use VBA to Open a Workbook then check out Open Workbook

If you want to use VBA to create a new workbook go to Create New Workbook

For all other VBA Workbook tasks, check out the quick guide below.

A Quick Guide to the VBA Workbook

The following table provides a quick how-to guide on the main VBA workbook tasks

Task How to
Access open workbook using name Workbooks(«Example.xlsx»)
Access open workbook (the one opened first) Workbooks(1)
Access open workbook (the one opened last) Workbooks(Workbooks.Count)
Access the active workbook ActiveWorkbook
Access workbook containing VBA code ThisWorkbook
Declare a workbook variable Dim wk As Workbook
Assign a workbook variable Set wk = Workbooks(«Example.xlsx»)
Set wk = ThisWorkbook
Set wk = Workbooks(1)
Activate workbook wk.Activate
Close workbook without saving wk.Close SaveChanges:=False
Close workbook and save wk.Close SaveChanges:=True
Create new workbook Set wk = Workbooks.Add
Open workbook Set wk =Workbooks.Open («C:DocsExample.xlsx»)
Open workbook as read only Set wk = Workbooks.Open («C:DocsExample.xlsx», ReadOnly:=True)
Check Workbook exists If Dir(«C:Docsbook1.xlsx») = «» Then
MsgBox «File does not exist.»
EndIf
Check Workbook is open See Check Workbook Open section below
List all open workbooks For Each wk In Application.Workbooks
    Debug.Print wk.FullName
Next wk
Open workbook with the File Dialog See File Dialog section below function below
Save workbook wk.Save
Save workbook copy wk.SaveCopyAs «C:Copy.xlsm»
Copy workbook if closed FileCopy «C:file1.xlsx»,«C:Copy.xlsx»
SaveAs workbook wk.SaveAs «Backup.xlsx»

VBA Workbook Webinar

If you are a member of the website, click on the image below to access the webinar.

(Note: Website members have access to the full webinar archive.)

vba workbook video

Getting Started with the VBA Workbook

We can access any open workbook using the code Workbooks(“Example.xlsm). Simply replace Example.xlsm with the name of the workbook you wish to use.

 
The following example shows you how to write to a cell on a worksheet. You will notice we had to specify the workbook, worksheet and range of cells.

' https://excelmacromastery.com/
Public Sub WriteToA1()

    ' Writes 100 to cell A1 of worksheet "Sheet1" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Sheet1").Range("A1") = 100

End Sub

 
This example may look a little be confusing to a new user but it is actually quite simple.

The first part up to the decimal point is the Workbook, the second part is the Worksheet and the third is the Range. Here are some more examples of writing to a cell

' https://excelmacromastery.com/
Public Sub WriteToMulti()

' Writes 100 to cell A1 of worksheet "Sheet1" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Sheet1").Range("A1") = 100

' Writes "John" to cell B1 of worksheet "Sheet1" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Sheet1").Range("B1") = "John"

' Writes 100 to cell A1 of worksheet "Accounts" in MyVBA.xlsm
Workbooks("MyVBA.xlsm").Worksheets("Accounts").Range("A1") = 100

' Writes the date to cell D3 of worksheet "Sheet2" in Book.xlsc
Workbooks("Book.xlsx").Worksheets("Sheet2").Range("D3") = "112016"

End Sub

 
You can see the simple pattern here. You can write to any cell in any worksheet from any workbook. It is just a matter of changing the workbook name, worksheet name and the range to suit your needs.

Take a look at the workbook part

Workbooks("Example.xlsx")

 
The Workbooks keyword refers to a collection of all open workbooks. Supplying the workbook name to the collection gives us access to that workbook. When we have the object we can use it to perform tasks with the workbook.

Troubleshooting the Workbooks Collection

When you use the Workbooks collection to access a workbook, you may get the error message:

Run-time Error 9: Subscript out of Range.

This means that VBA cannot find the workbook you passed as a parameter.

This can happen for the following reasons

  1. The workbook is currently closed.
  2. You spelled the name wrong.
  3. You created e new workbook (e.g. Book1) and tried to access it using Workbooks(“Book1.xlsx”). It’s name is not Book1.xlsx until it is saved for the first time.
  4. (Excel 2007/2010 only) If you are running two instances of Excel then Workbooks() only refers to to the workbooks open in the current Excel instance.
  5. You passed a number as Index and it is greater than the number of workbooks open e.g. you used Workbooks(3) and only two workbooks are open.

 
If you cannot resolve the error then use either of the functions in the section Finding all open Workbooks. These will print the names of all open workbooks to the Immediate Window(Ctrl + G).

Examples of Using the VBA Workbook

The following examples show what you can do with the workbook.

Note: To try this example create two open workbooks called Test1.xlsx and Test2.xlsx.

' https://excelmacromastery.com/
Public Sub WorkbookProperties()

    ' Prints the number of open workbooks
    Debug.Print Workbooks.Count

    ' Prints the full workbook name
    Debug.Print Workbooks("Test1.xlsx").FullName

    ' Displays the full workbook name in a message dialog
    MsgBox Workbooks("Test1.xlsx").FullName

    ' Prints the number of worksheets in Test2.xlsx
    Debug.Print Workbooks("Test2.xlsx").Worksheets.Count

    ' Prints the name of currently active sheet of Test2.xlsx
    Debug.Print Workbooks("Test2.xlsx").ActiveSheet.Name

    ' Closes workbook called Test1.xlsx
    Workbooks("Test1.xlsx").Close

    ' Closes workbook Test2.xlsx and saves changes
    Workbooks("Test2.xlsx").Close SaveChanges:=True

End Sub

 
 Note: In the code examples I use Debug.Print a lot. This function prints values to the Immediate  Window. To view this window select View->Immediate Window from the menu( Shortcut is Ctrl + G)

 
ImmediateWindow

 
ImmediateSampeText

Accessing the VBA Workbook by Index

You can also use an Index number with Workbooks(). The index refers to the order the Workbook was open or created.

 
Workbooks(1) refers to the workbook that was opened first. Workbooks(2) refers to the workbook that was opened second and so on.

' First workbook that was opened
Debug.Print Workbooks(1).Name

' Third workbook that was opened
Debug.Print Workbooks(3).Name

' The last workbook that was opened
Debug.Print Workbooks(Workbooks.Count).Name

 
In this example, we used Workbooks.Count. This is the number of workbooks that are currently in the Workbooks collection. That is, the number of workbooks currently open. So using it as the Index gives us the last workbook that was opened

Using the index is not really useful unless you really need to know the order. For this reason, you should avoid using it. You should use the workbook name with Workbooks() instead.

Finding all Open Workbooks

Sometimes you may want to access all the workbooks that are open. In other words, all the items in the Workbooks() collection.

You can do this using the For Each loop.

' https://excelmacromastery.com/
Public Sub PrintWrkFileName()

    ' Prints out the full filename of all open workbooks
    Dim wrk As Workbook
    For Each wrk In Workbooks
        Debug.Print wrk.FullName
    Next wrk

End Sub

 
You can also use the standard For loop to access all the open workbooks

' https://excelmacromastery.com/
Public Sub PrintWrkFileNameIdx()

    ' Prints out the full filename of all open workbooks
    Dim i As Long
    For i = 1 To Workbooks.Count
        Debug.Print Workbooks(i).FullName
    Next i

End Sub

 
For accessing workbooks, either of these Loops is fine. The standard For loop is useful if you want to use a different order or you need to use a counter.

Note: Both examples read in the order of the first opened to the last opened. If you want to read in reverse order(last to first) you can do this

' https://excelmacromastery.com/
Public Sub PrintWrkFileNameIdxRev()

    ' Prints out the full filename of all open workbooks
    ' in reverse order.
    Dim i As Long
    For i = Workbooks.Count To 1 Step -1
        Debug.Print Workbooks(i).FullName
    Next i

End Sub

Open Workbook

So far we have dealt with workbooks that are already open. Of course, having to manually open a workbook before running a Macro, defeats the purpose of automating tasks. The Open Workbook task should be performed by VBA.

The following VBA code opens the workbook “Book1.xlsm” in the “C:Docs” folder

' https://excelmacromastery.com/
Public Sub OpenWrk()

    ' Open the workbook and print the number of sheets it contains
    Workbooks.Open ("C:DocsBook1.xlsm")

    Debug.Print Workbooks("Book1.xlsm").Worksheets.Count

    ' Close the workbook without saving
    Workbooks("Book1.xlsm").Close saveChanges:=False

End Sub

 
It is a good idea to check a workbook actually exists before you try to open it. This will prevent you getting errors. The Dir function allows you to easily do this .

' https://excelmacromastery.com/
Public Sub OpenWrkDir()

    If Dir("C:DocsBook1.xlsm") = "" Then
        ' File does not exist - inform user
        MsgBox "Could not open the workbook. Please check it exists"
    Else
        ' open workbook and do something with it
        Workbooks.Open("C:DocsBook1.xlsm")
    End If

End Sub

Check For Open Workbook

If you are opening a workbook as Read-Only, it doesn’t matter if it is already open. However, if you’re going to update data in a workbook then it is a good idea to check if it is already open.

The function below can be used to check if the workbook is currently open. If not, then it will open the workbook. In either case you will end up with the workbook opened.

(The code below is taken from this StackOverFlow entry.)

' https://excelmacromastery.com/
Function GetWorkbook(ByVal sFullFilename As String) As Workbook
    
    Dim sFilename As String
    sFilename = Dir(sFullFilename)
    
    On Error Resume Next
    Dim wk As Workbook
    Set wk = Workbooks(sFilename)
    
    If wk Is Nothing Then
        Set wk = Workbooks.Open(sFullFilename)
    End If
    
    On Error Goto 0
    Set GetWorkbook = wk
    
End Function

You can use this function like this

' https://excelmacromastery.com/
Sub ExampleOpenWorkbook()

    Dim sFilename As String
    sFilename = "C:DocsBook2.xlsx"

    Dim wk As Workbook
    Set wk = GetWorkbook(sFilename)
    
End Sub

This code is fine is most situations. However, if the workbook could be currently open in read-only mode or could be currently opened by another user then you may want to use a slightly different approach.

An easy way to deal this with this scenario is to insist that the file must be closed for the application to run successfully. You can use the function below to simply check is the file already open and if so inform the user that it must be closed first.

(The code below is also taken from this StackOverFlow entry)

' https://excelmacromastery.com/
' Function to check if workbook is already open
Function IsWorkBookOpen(strBookName As String) As Boolean
    
    Dim oBk As Workbook
    
    On Error Resume Next
    Set oBk = Workbooks(strBookName)
    On Error GoTo 0
    
    If Not oBk Is Nothing Then
        IsWorkBookOpen = True
    End If
    
End Function

 
An example of using this function is shown below. In this case, if the workbook is already open then you inform the user that is must be closed for the macro to proceed.

' https://excelmacromastery.com/
Sub ExampleUse()

    Dim sFilename As String
    sFilename = "C:tempwritedata.xlsx"

    If IsWorkBookOpen(Dir(sFilename)) = True Then
        MsgBox "File is already open. Please close file and run macro again."
        Exit Sub
    End If
    
    ' Write to workbook here
    
End Sub

 
If you need to check if the workbook is open in another instance of Excel you can use the ReadOnly attribute of the workbook. It will be set to true if it is open in another instance.

Close Workbook

To Close a Workbook in Excel VBA is very simple. You simply call the Close method of the workbook.

wk.Close

 
Normally when you close a workbook in VBA, you don’t want to see messages from Excel asking if you want to save the file.

You can specify whether to save the workbook or not and then the Excel messages will not appear.

' Don't save changes
wk.Close SaveChanges:= False

' Do save changes
wk.Close SaveChanges:= True

 
Obviously, you cannot save changes to a workbook that is currently open as read-only.

Save Workbook

We have just seen that you can save a workbook when you close it. If you want to save it any other stage you can simply use the Save method

wk.Save

 
You can also use the SaveAs method

wk.SaveAs "C:Backupsaccounts.xlsx"

 
The Workbook SaveAs method comes with twelve parameters which allow you to add a password, set the file as read-only and so on. You can see the details here.

 
You can also use VBA to save the workbook as a copy using SaveCopyAs

wk.SaveCopyAs "C:DocsCopy.xlsm"

Copy Workbook

If the workbook is open you can use the two methods in the above section to create a copy i.e. SaveAs and SaveCopyAs.

 
 
If you want to copy a workbook without opening it then you can use FileCopy as the following example demonstrates

Public Sub CopyWorkbook()
    FileCopy "C:DocsDocs.xlsm", "C:DocsExample_Copy.xlsm"
End Sub

Using the File Dialog To Open a Workbook

The previous section shows you how to open a workbook with a given name. Sometimes you may want the user to select the workbook. You can easily use the Windows File Dialog shown here.

FileDialog VBA Workbook

The Windows File Dialog

 
 
The FileDialog is configurable and you can use it to

  1. Select a file.
  2. Select a folder.
  3. Open a file.
  4. “Save As” a file.

 
If you just want the user to select the file you can use the GetOpenFilename function.

 
The following function opens a workbook using the File Dialog. The function returns the full file name if a file was selected. If the user cancels it displays a message and returns an empty string.

' https://excelmacromastery.com/
Public Function UserSelectWorkbook() As String

    On Error Goto ErrorHandler

    Dim sWorkbookName As String

    Dim FD As FileDialog
    Set FD = Application.FileDialog(msoFileDialogFilePicker)

    ' Open the file dialog
    With FD
        ' Set Dialog Title
        .Title = "Please Select File"

        ' Add filter
        .Filters.Add "Excel Files", "*.xls;*.xlsx;*.xlsm"

        ' Allow selection of one file only
        .AllowMultiSelect = False

        ' Display dialog
        .Show

        If .SelectedItems.Count > 0 Then
            UserSelectWorkbook = .SelectedItems(1)
        Else
            MsgBox "Selecting a file has been cancelled. "
            UserSelectWorkbook = ""
        End If
    End With

    ' Clean up
    Set FD = Nothing
Done:
    Exit Function
ErrorHandler:
    MsgBox "Error: " + Err.Description
End Function

 
When you call this function you have to check for the user cancelling the dialog. The following example shows you how to easily call the UserSelectWorkbook function and handle the case of the user cancelling

' https://excelmacromastery.com/
Public Sub TestUserSelect()

    Dim userBook As Workbook, sFilename As String

    ' Call the UserSelectworkbook function
    sFilename = UserSelectWorkbook()

    ' If the filename returns is blank the user cancelled
    If sFilename <> "" Then
        ' Open workbook and do something with it
        Set userBook = Workbooks.Open(sFilename)
    End If

End Sub

 
You can customise the dialog by changing the Title, Filters and AllowMultiSelect in the UserSelectWorkbook function.

Using ThisWorkbook

There is an easier way to access the current workbook than using Workbooks(). You can use the keyword ThisWorkbook. It refers to the current workbook i.e. the workbook that contains the VBA code.

If our code is in a workbook call MyVBA.xlsm then ThisWorkbook and Workbooks(“MyVBA.xlsm”) refer to the same workbook.

 
Using ThisWorkbook is more useful than using Workbooks(). With ThisWorkbook we do not need to worry about the name of the file. This gives us two advantages:

  1. Changing the file name will not affect the code
  2. Copying the code to another workbook will not require a code change

 
These may seem like very small advantages. The reality is your filenames will change all the time. Using ThisWorkbook  means your code will still work fine.

 
The following example shows two lines of code. One using ThisWorkbook  and one using Workbooks(). The one using Workbooks will no longer work if the name of MyVBA.xlsm changes.

' https://excelmacromastery.com/
Public Sub WriteToCellUsingThis()

    ' Both lines do the same thing.
    Debug.Print ThisWorkbook.FullName
    Debug.Print Workbooks("MyVBA.xlsm").FullName

End Sub

Using the ActiveWorkbook

ActiveWorkbook refers to the workbook that is currently active. This is the one that the user last clicked on.

This can seem useful at first. The problem is that any workbook can become active by a simple mouse click. This means you could easily write data to the wrong workbook.

Using ActiveWorkbook also makes the code hard to read. It may not be obvious from the code which workbook should be the active one.

I hope I made it clear that you should avoid using ActiveWorkbook unless you really have to. If you must then be very careful.

Examples of the Accessing the Workbook

We’ve looked at all the ways of accessing a workbook. The following code shows examples of these ways

' https://excelmacromastery.com/
Public Sub WorkbooksUse()

    ' This is a workbook that is already open and called MyVBA.xlsm
    Debug.Print Workbooks("MyVBA.xlsm").FullName

    ' The workbook that contains this code
    Debug.Print ThisWorkbook.FullName

    ' The open workbook that was opened first
    Debug.Print Workbooks(1).FullName

    ' The open workbook that was opened last
    Debug.Print Workbooks(Workbooks.Count).FullName

    ' The workbook that is the currently active one
    Debug.Print ActiveWorkbook.FullName

    ' No workbook mentioned - the active one will be used
    Debug.Print Worksheets("Sheet1").Name

    ' A closed workbook called Book1.xlsm in folder C:Docs
    Workbooks.Open ("C:DocsBook1.xlsm")
    Debug.Print Workbooks("Book1.xlsm").FullName
    Workbooks("Book1.xlsm").Close

End Sub

Declaring a VBA Workbook variable

The reason for declaring a workbook variable is to make your code easier to read and understand. It is easier to see the advantage of using an example

' https://excelmacromastery.com/
Public Sub OpenWrkObjects()

    Dim wrk As Workbook
    Set wrk = Workbooks.Open("C:DocsBook1.xlsm")

    ' Print number of sheets in each book
    Debug.Print wrk.Worksheets.Count
    Debug.Print wrk.Name

    wrk.Close

End Sub

 
You can set a workbook variable with any of the access methods we have seen.

The following shows you the same code without a workbook variable

' https://excelmacromastery.com/
Public Sub OpenWrkNoObjects()

   Workbooks.Open ("C:DocsBook1.xlsm")

   Debug.Print Workbooks("Book2.xlsm").Worksheets.Count
   Debug.Print Workbooks("Book2.xlsm").Name

    Workbooks("Book2.xlsm").Close

End Sub

 
In these examples the difference is not major. However, when you have a lot of code, using a variable is useful particularly for worksheet and ranges where the names tend to be long e.g. thisWorkbook.Worksheets(“Sheet1”).Range(“A1”).

You can name the workbook variable to be something like wrkRead or wrkWrite. Then at a glance you can see what this workbook is being used for.

Create New Workbook

To create a new workbook you use the Workbooks Add function. This function creates a new blank workbook. It is the same as selecting New Workbook from the Excel File menu.

 
When you create a new workbook you will generally want to save it. The following code shows you how to do this.

' https://excelmacromastery.com/
Public Sub AddWordbook()

    Dim wrk As Workbook
    Set wrk = Workbooks.Add

    ' Save as xlsx. This is the default.
    wrk.SaveAs "C:TempExample.xlsx"

    ' Save as a Macro enabled workbook
    wrk.SaveAs "C:TempExample.xlsm", xlOpenXMLWorkbookMacroEnabled

End Sub

 
When you create a new workbook it normally contains three sheets. This is determined by the property Application.SheetsInNewWorkbook.

 
If you want to have a different number of sheets in a new workbook then you change this property before you create the new workbook. The following example shows you how to create a new workbook with seven sheets.

' https://excelmacromastery.com/
Public Sub AddWordbookMultiSheets()

    ' Store SheetsInNewWorkbook value so we can reset it later
    Dim sheetCnt As Long
    sheetCnt = Application.SheetsInNewWorkbook

    ' Set sheets in a new workbook to be 7
    Application.SheetsInNewWorkbook = 7

    ' Workbook will be created with 7 sheets
    Dim wrk As Workbook
    Set wrk = Workbooks.Add

    ' Display sheet count
    Debug.Print "number of sheets: " & CStr(wrk.Worksheets.Count)

    ' Reset to original value
    Application.SheetsInNewWorkbook = sheetCnt

End Sub

The With keyword and the Workbook

The With keyword makes reading and writing VBA code easier. Using With means you only need to mention the item once. With  is used with Objects. These are items such as Workbooks, Worksheets and Ranges.

 
The following example has two Subs. The first is similar to code we have seen so far. The second uses the With keyword. You can see the code is much clearer in the second Sub. The keywords End With mark the finish of a section code using With.

' https://excelmacromastery.com/
' Not using the With keyword
Public Sub NoUsingWith()

   Debug.Print Workbooks("Book2.xlsm").Worksheets.Count
   Debug.Print Workbooks("Book2.xlsm").Name
   Debug.Print Workbooks("Book2.xlsm").Worksheets(1).Range("A1")
   Workbooks("Book2.xlsm").Close

End Sub

' Using With makes the code easier to read
Public Sub UsingWith()

    With Workbooks("Book2.xlsm")
        Debug.Print .Worksheets.Count
        Debug.Print .Name
        Debug.Print .Worksheets(1).Range("A1")
        .Close
    End With

End Sub

Summary

The following is a brief summary of the main points of this post

  1. To get the workbook containing the code use ThisWorkbook.
  2. To get any open workbook use Workbooks(“Example.xlsx”).
  3. To open a workbook use Set Wrk = Workbooks.Open(“C:FolderExample.xlsx”).
  4. Allow the user to select a file using the UserSelectWorkbook function provided above.
  5. To create a copy of an open workbook use the SaveAs property with a filename.
  6. To create a copy of a workbook without opening use the FileCopy function.
  7. To make your code easier to read and write use the With keyword.
  8. Another way to make your code clear is to use a Workbook variables
  9. To run through all open Workbooks use For Each wk in Workbooks where wk is a workbook variable.
  10. Try to avoid using ActiveWorkbook and Workbooks(Index) as their reference to a workbook is temporary.

You can see a quick guide to the topic at the top of this post

Conclusion

This was an in-depth post about a very important element of VBA – the Workbook.  I hope you found it beneficial. Excel is great at providing many ways to perform similar actions but the downside is it can lead to confusion at times.

To get the most benefit from this post I recommend you try out the examples. Create some workbooks and play around with the code. Make changes to the code and see how the changes affect the outcome. Practice is the best way to learn VBA.

If you found this post useful then feel free to share it with others using the bar at the side.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Excel VBA Workbooks — Reference, Open, Add, Name, Save, Activate, Copy & Close Workbooks; SendMail Method


Related Links:

Working with Objects in Excel VBA

Excel VBA Application Object, the Default Object in Excel

Microsoft Excel VBA — Worksheets

Excel VBA Range Object, Referencing Cells and Ranges

Excel VBA Custom Classes and Objects


—————————————————————————————

Contents:

The Workbook Object

Reference a Workbook object ie. a single workbook

Open, Add, Copy & Close Workbooks

Saving Workbooks

Some often used Methods & Properties of the Workbook Object

—————————————————————————————

The Workbook Object appears next below the Application Object in Excel VBA object hierarchy, and represents a single workbook within the Excel application. The Workbooks Object refers to a collection of all currently open Workbooks (ie. all currently open Workbook Objects) in Excel.

Note that while working with Workbooks, you will use Properties & Methods of the Workbook Object as well as Properties & Methods of the Workbooks Object.

Reference a Workbook object ie. a single workbook.

To reference or return a Workbook object (single workbook), the following properties can be used.

Workbooks.Item Property

The Item Property of the Workbooks object (ie. Workbooks.Item property) refers to a single workbook in a collection. Syntax: WorkbooksObject.Item(Index), where Index is the workbook name or index number. You can also omit using the ‘item’ word — use syntax as WorkbooksObject(WorkbookName) or WorkbooksObject(IndexNumber). The index number starts at 1 for the first workbook opened or created and increments accordingly for each subsequent workbook (hidden workbooks are also included), the last workbook being returned by Workbooks(Workbooks.Count). The Count property of the Workbooks object — WorkbooksObject.Count Property — returns the number of workbooks in the collection. Refer below examples of using this property.

Close the workbook named «ExcelVBA1.xlsm»:

Workbooks.Item(«ExcelVBA1.xlsm»).Close

Workbooks(«ExcelVBA1.xlsm»).Close

Close the workbook opened last, after saving it:

Workbooks(Workbooks.Count).Close SaveChanges:=True

Return the name of workbook with index number 2 ie. the second workbook which is opened / created:

MsgBox Workbooks(2).Name

Print preview of workbook with index number 2:

Workbooks(2).PrintPreview

Return the name of the last workbook opened or created:

MsgBox Workbooks(Workbooks.Count).Name

Example 1 — return names of all open workbooks:

Sub workbookNames()
‘return name of each open workbook

Dim i As Integer
For i = 1 To Workbooks.Count

msgbox Workbooks(i).Name

Next i

End Sub

Example 2 — set variable to a workbook:

Sub workbookVariable()
‘set variable to a workbook

Dim wb As Workbook
Dim i As Integer
‘set the wb variable to the specified workbook:
Set wb = Workbooks(«Excel2007Workbook — Copy.xlsx»)

‘refer total number of worksheets in the specified workbook using the Worksheets.Count property:

For i = 1 To wb.Worksheets.Count

‘return the name of each worksheet using the Name property of the Worksheet object:

MsgBox wb.Worksheets(i).Name

Next i

End Sub

ActiveWorkbook Property of the Application object. This property returns the active workbook (ie. the workbook in the active window). Syntax: ApplicationObject.ActiveWorkbook. It is optional to specify the ApplicationObject.

MsgBox «Active Workbook’s name is » & ActiveWorkbook.Name

ThisWorkbook Property of the Application object. This property is used only from within the Excel Application and returns the workbook in which the code is running currently. Syntax: ApplicationObject.ThisWorkbook. It is optional to specify the ApplicationObject.

MsgBox «This Workbook’s name is » & ThisWorkbook.Name

Note that though most times the ActiveWorkbook is the same as ThisWorkbook, but it might not always be so. The active workbook can be different than the workbook in which the code is running, as shown by the following code example. The Active Object has been illustrated in detail in the section «Excel VBA Objects, Properties & Methods.».

Example 3 — ActiveWorkbook and ThisWorkbook:

Sub ActiveWorkbook_ThisWorkbook()
‘Open two Excel workbook files («Book1.xlsm» and «Book2.xlsm») in a single instance (this will enable all workbooks to access macros).
‘Enter this code in the workbook «Book1.xlsm», which is also the active/selected workbook.

‘returns «Book1.xlsm»:
MsgBox «Active Workbook’s name is » & ActiveWorkbook.Name

‘returns «Book1.xlsm»:

MsgBox «This Workbook’s name is » & ThisWorkbook.Name

‘activate «Book2.xlsm»:

Workbooks(«Book2.xlsm»).Activate
‘returns «Book2.xlsm», while ThisWorkbook remains «Book1.xlsm»:
MsgBox «Active Workbook’s name is » & ActiveWorkbook.Name

‘returns «Book1.xlsm»:

MsgBox «This Workbook’s name is » & ThisWorkbook.Name

‘activate «Book1.xlsm»:
Workbooks(«Book1.xlsm»).Activate
‘returns «Book1.xlsm»:
MsgBox «Active Workbook’s name is » & ActiveWorkbook.Name
‘returns «Book1.xlsm»:

MsgBox «This Workbook’s name is » & ThisWorkbook.Name

End Sub

Open, Add, Copy & Close Workbooks

Workbooks.Open Method

Use the Workbooks.Open Method (Open Method of the Workbooks object) to open a workbook. Syntax: WorkbooksObject.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad). The FileName argument is required while all other arguments are optional to specify. We detail only some arguments here. The FileName argument is a String value specifying the workbook name which is to be opened. The file name (including extension) with its path should be specified, else omitting the path will look-up the file name in the current directory. Setting the UpdateLinks argument to 0 will not update external links or references when the workbook is opened, while specifying the value 3 will update the external links or references. Set the ReadOnly argument to True to open the workbook in read-only mode. The Password argument is a string value specifying the password required to open workbook which is password-protected, and omitting this argument will prompt the user for a password. The WriteResPassword argument is a string value specifying the password required to open a write-reserved workbook (ie. opening this file without the password will make it read-only), and omitting this argument will prompt the user for a password. Note that when a workbook is opened programmatically, macros are enabled by default.

Workbooks.Add Method

Use the Workbooks.Add Method (Add Method of the Workbooks object) to create a new workbook, which also becomes the active workbook. Syntax: WorkbooksObject.Add(Template). Using this method returns a workbook object. It is optional to specify the Template argument. This argument can be a string value specifying the name (and path) of an existing Excel file, and in this case the specified file acts as the template for the new workbook which is created (meaning that the new workbook will have the same content, formatting, macros & customization as the existing file which is specified). You can also define a constant (XlWBATemplate Enumeration) for this argument, and in this case the newly created workbook will contain a single sheet of the type which is specified viz. specifying the constant xlWBATChart (value -4109) will create one Chart sheet; xlWBATExcel4MacroSheet (value 3) — creates one Excel version 4 macro sheet; xlWBATExcel4IntlMacroSheet (4) — creates one Excel version 4 international macro sheet; xlWBATWorksheet (-4167) — creates one Worksheet. Omitting the Template argument will create a new workbook with the Excel default of three blank sheets, wherein the default number of sheets can be changed / set by using the Application.SheetsInNewWorkbook Property.

Default name of the new workbook(s): Creating new workbooks using the Add method — when the Template argument is omitted — the workbooks are named BookN, the first workbook created being Book1, followed by Book2, and so on; when the Template argument is the xlWBATWorksheet constant, the workbooks are named SheetN, the first workbook created being Sheet1, followed by Sheet2, and so on; using the constants xlWBATExcel4MacroSheet or xlWBATExcel4IntlMacroSheet, the workbooks are named MacroN, the first workbook created being Macro1, followed by Macro2, and so on; using the constant xlWBATChart, the workbooks are named ChartN;

Example 4: Use the Add method to create new workbook(s).

Sub WorkbooksAdd()
‘use the Add method to create new workbook(s).

Dim i As Integer
Dim n As Integer
‘entering 4 in the input box, will create four new workbooks with default names Book1, Book2, Book3 & Book4.
i = InputBox(«Enter number of workbooks to create»)

For n = 1 To i

Workbooks.Add

Next n

End Sub

Close Method

Use the Close Method of the Workbooks object to close all open workbooks. Syntax: WorkbooksObject.Close. This method accepts no arguments, and using this will prompt you for saving changes, if any changes have been made in the open workbook. You can set the DisplayAlerts property to False to not display any prompts or alerts. To close all open workbooks, use the code line Workbooks.Close. While dealing with multiple excel workbooks, remember that all files should have been opened in a single instance of Excel.

Use the Close Method of the Workbook object to close a single workbook. Syntax: WorkbookObject.Close(SaveChanges, Filename, RouteWorkbook). All arguments are optional to specify. Omitting the SaveChanges argument will prompt the user to save changes, in case any change has been made to the workbook after being saved last. Setting SaveChanges argument to True will save any changes made to the workbook, and if set to False, the workbook will close without saving any changes made and in both settings the workbook closes without displaying a prompt to save changes. The Filename argument should be used to specify a file name to close a workbook which does not yet have an associated file name (viz. a new workbook), else omitting this argument will ask the user to specify a file name before closing it. The Filename argument can be used optionally if you want to save an existing workbook (ie. which already has an associated name), with a new file name. Set the RouteWorkbook argument to True if the workbook is to be routed or sent to the next recipient, where a routing slip is present. Examples of using this method: for closing the active workbook after saving changes — ActiveWorkbook.Close SaveChanges:=True; to close the workbook named «Book1.xlsx», after saving changes — Workbooks(«Book1.xlsx»).Close SaveChanges:=True.

Example 5 — Open workbook, Close workbook(s)

Sub WorkbookOpenClose()
‘open workbook, close workbooks

Application.ScreenUpdating = False

 Dim wb As Workbook
Dim strPath As String, strName As String
Dim i As Integer, count As Integer

‘open the workbook by assigning the path & file name to variables:
strPath = «C:UsersUser NameDocuments»

strName = «Book1.xlsx»
‘open the workbook in read-only mode:
Workbooks.Open (strPath & «» & strName), ReadOnly:=True

‘omitting the path will look-up the file name in the current directory:
‘change the current directory using the ChDir Statement — this sets the the new default directory or folder:
ChDir «C:UsersUser NameDocumentsFolder1»
‘open workbook (omitting the path) without updating external links or references:
Workbooks.Open «Book2.xlsx», UpdateLinks:=0

‘specifying the password required to open workbook which is password-protected:
Workbooks.Open fileName:=«C:UsersUser NameDocumentsFolder2Book3.xlsx», Password:=«123»

‘specifying the password required to open a write-reserved workbook (ie. opening this file without the password will make it read-only):
Workbooks.Open fileName:=«C:UsersUser NameDocumentsFolder3Book4.xlsx», WriteResPassword:=«abc123»

‘define the path to the same directory as this workbook (containing the code), to look-up the file name:
strPath = ThisWorkbook.Path
Workbooks.Open (strPath & «» & «Book5.xls»)

‘close all open workbooks, except the workbook with this code:

‘For Each wb In Application.Workbooks

‘If Not wb.Name = ThisWorkbook.Name Then wb.Close SaveChanges:=True

‘alternately:

‘If wb.Name <> ThisWorkbook.Name Then wb.Close SaveChanges:=True

‘Next

‘Alternate — close all open workbooks, except the workbook with this code:

count = Workbooks.count

For i = count To 1 Step -1

If Workbooks(i).Name <> ThisWorkbook.Name Then Workbooks(i).Close SaveChanges:=True

Next i

Application.ScreenUpdating = True

End Sub

Example 6 — Create new workbook(s) using the Add method, then save and close.

For live code of this example, click to download excel file.

Sub WorkbookAdd()
‘create new workbook(s) using the Add method, then save and close.

‘set DisplayAlerts property to False to not display any prompts or alerts:
Application.DisplayAlerts = False
‘change the current directory to ThisWorkbook directory, using the ChDir Statement — this sets the the new default directory or folder:

ChDir ThisWorkbook.Path

‘————-

‘specifying the name of an existing file (in the same folder as ThisWorkbook) which is used as the template for the new workbook created using the Add method:
Workbooks.Add «Book1.xlsx»
MsgBox «New Workbook name and number of sheets: » & ActiveWorkbook.Name & «; » & ActiveWorkbook.Sheets.count

‘save as .xls file, the Excel 97 — Excel 2003 file format, using the FileFormat Enumeration xlExcel8 (value 56):
ActiveWorkbook.SaveAs fileName:=ActiveWorkbook.Name, FileFormat:=xlExcel8
‘enter «xlsFile» in cell (1,1) in active sheet of the new workbook:
ActiveWorkbook.ActiveSheet.Range(«A1») = «xlsFile»
‘close workbook after saving changes:

ActiveWorkbook.Close SaveChanges:=True

‘————-

‘creates a new workbook with three worksheets (this is the Excel 2007 default for number of worksheets), unless the default has been changed using the Application.SheetsInNewWorkbook property:
Workbooks.Add
MsgBox «New Workbook name and number of sheets: » & ActiveWorkbook.Name & «; » & ActiveWorkbook.Sheets.count

‘save as .xlsx file, the default Excel 2007 file format, using the FileFormat Enumeration xlOpenXMLWorkbook (value 51):
ActiveWorkbook.SaveAs fileName:=ActiveWorkbook.Name, FileFormat:=xlOpenXMLWorkbook
‘enter «xlsxFile» in cell (1,1) in active sheet of the new workbook:
ActiveWorkbook.ActiveSheet.Range(«A1») = «xlsxFile»
‘close workbook after saving changes:

ActiveWorkbook.Close SaveChanges:=True

‘————-

‘change the default number of worksheets to 5:
Application.SheetsInNewWorkbook = 5
‘creates a new workbook with five worksheets
Workbooks.Add
MsgBox «New Workbook name and number of sheets: » & ActiveWorkbook.Name & «; » & ActiveWorkbook.Sheets.count

‘save the new workbook as a .xlsm file, the Excel 2007 macro-enabled file format, using the FileFormat Enumeration xlOpenXMLWorkbookMacroEnabled (value 52) :
ActiveWorkbook.SaveAs fileName:=«NewWorkbookSaved.xlsm», FileFormat:=xlOpenXMLWorkbookMacroEnabled
‘enter «xlsmFile» in cell (1,1) in active sheet of the new workbook:
ActiveWorkbook.ActiveSheet.Range(«A1») = «xlsmFile»
‘close workbook after saving changes:

ActiveWorkbook.Close SaveChanges:=True

‘————-

‘create a new workbook containing one worksheet:
Workbooks.Add (xlWBATWorksheet)
MsgBox «New Workbook name and number of sheets: » & ActiveWorkbook.Name & «; » & ActiveWorkbook.Sheets.count

‘save the new workbook, omitting the file format, this will save in the default file format of your current Excel version when you are saving a new file:
ActiveWorkbook.SaveAs fileName:=ActiveWorkbook.Name
‘enter «DefaultFileFormat» in cell (1,1) in active sheet of the new workbook:
ActiveWorkbook.ActiveSheet.Range(«A1») = «DefaultFileFormat«
‘close workbook after saving changes:

ActiveWorkbook.Close SaveChanges:=True

‘————-

‘create a new workbook containing one Chart sheet:
Workbooks.Add (xlWBATChart)
MsgBox «New Workbook name and number of sheets: » & ActiveWorkbook.Name & «; » & ActiveWorkbook.Sheets.count

‘save as .xlsx file, the default Excel 2007 file format, using the FileFormat Enumeration xlOpenXMLWorkbook (value 51):
ActiveWorkbook.SaveAs fileName:=ActiveWorkbook.Name, FileFormat:=xlOpenXMLWorkbook
‘close workbook:
ActiveWorkbook.Close

‘restore DisplayAlerts property to True to display prompts or alerts:
Application.DisplayAlerts = True

‘You might want to revert to the Excel 2007 default of three blank sheets, because the value set by using the SheetsInNewWorkbook property will be retained in the application after this session.

Application.SheetsInNewWorkbook = 3

End Sub

Workbooks.OpenDatabase Method

Use the Workbooks.OpenDatabase Method to get data from a database, stored in a table or a query, into an excel file. Syntax: WorkbooksObject.OpenDatabase(Filename, CommandText, CommandType, BackgroundQuery, ImportDataAs). This method returns a workbook object ie. a new workbook is opened, representing the database. All arguments except Filename are optional to specify. Use the Filename argument to specify the name of the database file from which you want to retreive data. Use the CommandText argument to specify the query string (SQL statement, table name, …), to get the data. The CommandType argument specifies the command type of the query. You can specify one of the five constants: xlCmdTable (a table name); xlCmdSql (a SQL statement);  xlCmdDefault (command text that the OLE DB provider understands); xlCmdList (pointer to list data); xlCmdCube (cube name for an OLAP data source). Setting the BackgroundQuery to True will perform the query in the background (asynchronously), whereas the default value is False. Use the ImportDataAs argument to specify the format in which data is retreived from a database — specifying argument value as xlPivotTableReport returns the data as a PivotTable and specifying value as xlQueryTable (default value) returns data as Query Table.

Using the Workbooks.OpenDatabase Method when only the Filename argument is specified and not the optional arguments, a dialog box is displayed listing all the tables and queries in the database from which the user has to make a selection, after which a new workbook opens containing data from the selected table or query.

Example 7 — Use the Workbooks.OpenDatabase Method to import data into an Excel file as a query table.

Sub OpenDatabase_QueryTableFormat()
‘get data from a database table, into an excel file, using the Workbooks.OpenDatabase Method.
‘refer Image 1a which shows the «SalesManager» table in Access file «SalesReport.accdb; refer Image 1b which shows the excel file «OpenDatabase_QueryTable» into which data is imported.

‘change the current directory to ThisWorkbook directory, in which the new workbook will be saved:
ChDir ThisWorkbook.Path

      ‘use the Workbooks.OpenDatabase Method to import data into an Excel file as a query table, from the «SalesManager» table in Access file «SalesReport.accdb:
Workbooks.OpenDatabase fileName:=«SalesReport.accdb», CommandText:=«SalesManager», CommandType:=xlCmdTable, BackgroundQuery:=False, ImportDataAs:=xlQueryTable

‘save as .xlsx file, the default Excel 2007 file format:
ActiveWorkbook.SaveAs fileName:=«OpenDatabase_QueryTable», FileFormat:=xlOpenXMLWorkbook

‘close workbook:

ActiveWorkbook.Close

End Sub

Example 8 — Use the Workbooks.OpenDatabase Method to import data into an Excel file as a pivot table.


Sub OpenDatabase_PivotTableFormat()
‘get data from a database table, into an excel file, using the Workbooks.OpenDatabase Method.
‘refer Image 1c which shows the «Performance» table in Access file «SalesReport.accdb;
‘refer Image 1d which shows the excel file «OpenDatabase_PivotTable» into which data is imported;
‘refer Image 1e which shows the excel file «OpenDatabase_PivotTable» wherein the fields displayed in the pivot report have been selected manually.

‘change the current directory to ThisWorkbook directory, in which the new workbook will be saved:
ChDir ThisWorkbook.Path

      ‘use the Workbooks.OpenDatabase Method to import data into an Excel file as a pivot table from Access file «SalesReport.accdb, using an SQL statement:
Workbooks.OpenDatabase fileName:=«SalesReport.accdb», CommandText:=«SELECT * FROM Performance WHERE EmployeeId >= 21″, CommandType:=xlCmdSql, BackgroundQuery:=True, ImportDataAs:=xlPivotTableReport

‘save as .xlsx file, the default Excel 2007 file format:
ActiveWorkbook.SaveAs fileName:=«OpenDatabase_PivotTable», FileFormat:=xlOpenXMLWorkbook

‘close workbook:
ActiveWorkbook.Close

End Sub

Workbook.SaveCopyAs Method

Use the Workbook.SaveCopyAs Method to save a copy of the workbook. The method doesn’t modify the open workbook in memory. Syntax: WorkbookObject.SaveCopyAs(Filename). The Filename argument is optional to specify, and is used to specify the file name with which the workbook copy is saved. Note that the Workbook.SaveCopyAs Method allows saving with the same File Format only (ie. the workbook and its copy being saved should be of same file format), else while opening the saved copy you will get a prompt — «The file you are trying to open is in a different format than specified by the file extension …» — and the file may or may not open. Whereas the Workbook.SaveAs Method allows you to specify the File Format for saving the file.

Example 9: Use the Workbook.SaveCopyAs Method to save a copy of Active Workbook which your are working in.

Sub WorkbookSaveCopyAs1()
‘use the Workbook.SaveCopyAs Method to save a copy of Active Workbook which your are working in:

Dim lLastRow As Long

‘determine last row with Data in a column (column «A»):
lLastRow = ActiveWorkbook.ActiveSheet.Range(«A» & Rows.count).End(xlUp).Row

‘save a copy of the workbook if data in a column of active sheet is over a specific number of rows:

If lLastRow >= 100 Then

‘save a copy of Active Workbook which your are working in, specifying a file name (of same file format as the active workbook) — use this method to save your existing work, while your current workbook remains the active workbook:

ActiveWorkbook.SaveCopyAs «C:MyDocuments

Folder1WorkbookCopy.xlsm»

End If

‘your current workbook remains the active workbook, the saved copy remains closed:

MsgBox ActiveWorkbook.Name

End Sub

Example 10: Use the Workbook.SaveCopyAs Method to save a copy of ThisWorkbook which your are working in, with a unique name everytime.

Sub WorkbookSaveCopyAs2()
‘use the Workbook.SaveCopyAs Method to save a copy of ThisWorkbook which your are working in, with a unique name everytime:

Dim strName As String, strExtn As String, MyStr As String
Dim i As Integer, iLastDot As Integer

‘change the current directory to the ThisWorkbook directory:
ChDir ThisWorkbook.Path

‘find position of last dot, to distinguish file extension:

For i = 1 To Len(ThisWorkbook.Name)

If Mid(ThisWorkbook.Name, i, 1) = «.» Then

iLastDot = i

End If

Next i

‘extract file extension and dot before extension:
strExtn = Right(ThisWorkbook.Name, Len(ThisWorkbook.Name) — iLastDot + 1)
‘extract workbook name excluding its name extension and dot before extension:
MyStr = Left(ThisWorkbook.Name, iLastDot — 1)

‘specify name for the copy — the time part in the file name will help in indentifying the last backup, besides making the name unique:
strName = MyStr & «_» & Format(Now(), «yyyy-mm-dd hh-mm-ss AMPM») & strExtn

‘save a copy of ThisWorkbook which your are working in, specifying a file name — use this method to save your existing work, while your current workbook remains the active workbook:
ThisWorkbook.SaveCopyAs strName

‘your current workbook remains the active workbook, the saved copy remains closed:

MsgBox ActiveWorkbook.Name

End Sub

Example 11: Use the Workbook.SaveCopyAs Method to save a copy of a specified workbook.

Sub WorkbookSaveCopyAs3()
‘use the Workbook.SaveCopyAs Method to save a copy of a specified workbook:

‘open a specified workbook in the current directory:
Workbooks.Open «C:MyDocumentsFolder2ExcelFile.xlsx»

‘the opened workbook becomes the active workbook:
MsgBox ActiveWorkbook.Name

‘save a copy of the opened workbook, specifying a file name (the workbook and its copy being saved should be of same file format).
ActiveWorkbook.SaveCopyAs «C:MyDocumentsFolder2Copy of ExcelFile.xlsx»

‘the opened workbook remains the active workbook, the saved copy remains closed:
MsgBox ActiveWorkbook.Name

‘close the opened workbook — note that neither the opened workbook or the saved copy will be open after this command:

ActiveWorkbook.Close

End Sub

Saving Workbooks

Use the Workbook.Save Method (Save Method of the Workbook object) to save a specified workbook. Syntax: WorkbookObject.Save.

Save the workbook named «ExcelVBA1.xlsm»:

Workbooks(«ExcelVBA1.xlsm»).Save

Use the SaveChanges argument in the Close Method of the Workbook object, to save the workbook before closing (refer to Close Method for details).

Close the workbook opened last, after saving it:

Workbooks(Workbooks.Count).Close SaveChanges:=True

Use the Workbook.SaveAs Method (SaveAs Method of the Workbook object) to save workbook changes in a separate file. Syntax: WorkbookObject.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local). All arguments are optional to specify. We detail only some arguments here. FileName is a string value, specifying the name and full path of the file to be saved and omitting the path will save the file in the current folder. FileFormat specifies the format of the file to be saved, as per the XlFileFormat enumeration list. The default file format is your current Excel version when you are saving a new file, whereas for an existing file the default is the file format which was last specified. Remember that in Excel 2007-2010 while using SaveAs, it is necessary to specify the FileFormat parameter to save a FileName with a .xlsm extension if the workbook being saved is not a .xlsm file viz. FileFormat:=xlOpenXMLWorkbookMacroEnabled or FileFormat:=52. You can specify a case-sensitive password upto 15 characters for file opening, using the Password argument. You can specify a password to open a file wherein opening the file without entering the password will open it as read-only — use the WriteResPassword argument to specify this password.

XlFileFormat Enumeration, some options are being mentioned here in the order of Constants, Value (Description): For Excel 2007-2013:- xlExcel12, 50 («.xlsb», Excel12, Excel Binary Workbook with macros or without in Excel 2007-13, Excel 2007 is version 12); xlOpenXMLWorkbook, 51 («.xlsx», Open XML Workbook, Workbook without macros in Excel 2007-13); xlOpenXMLWorkbookMacroEnabled, 52 («.xlsm», Open XML Workbook Macro Enabled, Macro-enabled workbook in Excel 2007-13); xlExcel8, 56 («.xls», Excel8, 97-2003 format in Excel 2007-13, Excel 97 is version 8); For Excel 97-2003:- xlWorkbookNormal, -4143 («.xls», Workbook Normal);

Example 12 — save an existing workbook with a new name & file format:

Sub workbookSaveAs1()
‘save the workbook with index number 2 with a new name & file format.
‘while dealing with multiple excel workbooks, remember that all files should have been opened in a single instance of Excel.

‘Remember that in Excel 2007-2010 while using SaveAs, it is necessary to specify the FileFormat parameter to save a FileName with a .xlsm extension if the workbook being saved is not a .xlsm file viz. FileFormat:=xlOpenXMLWorkbookMacroEnabled or FileFormat:=52.

‘to save .xlsm file as a .xlsm file, in Excel 2007:
Workbooks(2).SaveAs «WorkbookNameChanged.xlsm»

‘to save non .xlsm file as a .xlsm file, in Excel 2007:
‘Workbooks(2).SaveAs «WorkbookNameChanged.xlsm», FileFormat:=xlOpenXMLWorkbookMacroEnabled

End Sub

Example 13 — saving a new workbook:

Sub workbookSaveAs2()
‘saving a new workbook.
‘while dealing with multiple excel workbooks, remember that all files should have been opened in a single instance of Excel.

‘Remember that in Excel 2007-2010 while using SaveAs, it is necessary to specify the FileFormat parameter to save a FileName with a .xlsm extension if the workbook being saved is not a .xlsm file viz. FileFormat:=xlOpenXMLWorkbookMacroEnabled or FileFormat:=52.

‘add a new workbook:
Workbooks.Add

‘save the new workbook, which becomes the active workbook, as password protected:
ActiveWorkbook.SaveAs fileName:=«NewWorkbookSaved.xlsx», Password:=«abcXYZ123»

‘save the new workbook as a .xlsm file with password protection:
ActiveWorkbook.SaveAs fileName:=«NewWorkbookSaved.xlsm», FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:=«abcXYZ123»

‘save the new workbook as a .xlsm file with password protection, but can be opened as read-only without supplying the password:

ActiveWorkbook.SaveAs fileName:=«NewWorkbookSaved.xlsm», FileFormat:=xlOpenXMLWorkbookMacroEnabled, WriteResPassword:=«abcXYZ123»

End Sub

Use the Workbook.Saved Property to determine whether any changes have been made to the workbook after saving it last. Syntax: WorkbookObject .Saved. This property returns a Boolean value — True indicates that the workbook was not modified after it was last saved. Setting this property to True before closing a workbook wherein changes have been made will not prompt to save the workbook and will also not save the changes.

Example 14 — Set the Workbook.Saved Property to TRUE to close the workbook with NO prompt to save changes:

Sub workbookSaved()
‘Workbook.Saved Property — close the workbook with NO prompt to save changes:

‘open a workbook named «ExcelFile.xlsx»
Workbooks.Open «C:MyDocumentsExcelFile.xlsx»

‘Workbook.Saved Property will return True indicating no changes have been made to the workbook after it was last saved:
MsgBox Workbooks(«ExcelFile.xlsx»).Saved

‘make changes to the workbook:
Workbooks(«ExcelFile.xlsx»).ActiveSheet.

Range(«A1») = «hello»

‘Workbook.Saved Property will return False indicating that changes have been made to the workbook after it was last saved:
MsgBox Workbooks(«ExcelFile.xlsx»).Saved

‘set Workbook.Saved Property to True:
Workbooks(«ExcelFile.xlsx»).Saved = True

‘close the workbook with NO prompt to save changes and this will also NOT save any changes — if the Saved property was not set to True as above you will get a prompt to save changes while closing the workbook:

Workbooks(«ExcelFile.xlsx»).Close

End Sub

Some often used Methods & Properties of the Workbook Object

Workbook.Activate Method

Use the Workbook.Activate Method to activate a workbook. If the workbook has multiple windows, the method activates the first window. Syntax: WorkbookObject.Activate. To activate the workbook named «Workbook2.xlsx», use the code Workbooks(«Workbook2.xlsx»).Activate.

Workbook.PrintPreview Method

Use the Workbook.PrintPreview Method to view a preview of how the printed workbook will look. Syntax: WorkbookObject.PrintPreview(EnableChanges). It is optional to specify the EnableChanges argument, which accepts a Boolean value (default value is True), to allow or disallow the user to change the page setup options (ex. page orientation, scaling, margins, etc) available in print preview.

Example 15 — PrintPreview

Sub PrintPreview()

‘print preview of active sheet of workbook named «ExcelFile.xlsx, disallowing the user to change the page setup options available in print preview.
Workbooks(«ExcelFile.xlsx»).PrintPreview EnableChanges:=False

‘print preview of «Sheet3» of workbook «ExcelFile.xlsx, allowing the user to change the page setup options available in print preview.

Workbooks(«ExcelFile.xlsx»).Worksheets(«Sheet3»).

PrintPreview EnableChanges:=True

End Sub

Workbook.SendMail Method

Users often use Outlook to email from Excel. One option is to automate Outlook from within Excel, allowing you more functionality to send emails, by working with Outlook objects using VBA in Excel. Automation is a process by which one application communicates with or controls another application. Refer our section «Automate Outlook using vba: Sending Email from Excel using Outlook» for details. Another option to send mails from Excel is using the Workbook.SendMail Method, which is a simple way to email a workbook. However, this method has some limitations — you can only specify recipient(s), subject & option of a return receipt. You do not have options to specify CC or BCC, include text in the body of your mail or send other files as attachment.

With the Workbook.SendMail Method, you use the installed mail system to send or email a workbook. Syntax: WorkbookObject.SendMail(Recipients, Subject, ReturnReceipt). The Recipients argument is necessary wherein you can specify a single recipient or multiple recipients as text or an array of text strings respectively. The Subject argument is optional, and is used to specify the subject of the mail. Omitting this argument will default the workbook name as the subject. The ReturnReceipt argument is also optional, wherein specifying True or False will request or not request a return receipt respectively, default value being False.

If you wish to add text to the mail of the body, use «» for the Recipient argument which displays the mail viz. ActiveWorkbook.SendMail Recipients:=«»

Example 16 — Email workbook with sendmail method, specifying the recipient name or email.

Sub SendMail_1()
’email workbook with sendmail method, specifying the recipient name or email

Workbooks.Open («C:MyDocumentsFolder1Book1.xlsx»)

‘specifies the recipient name as text:
ActiveWorkbook.SendMail Recipients:=«David Kelly», Subject:=«Hi», ReturnReceipt:=True

‘specifies the recipient email:

ActiveWorkbook.SendMail Recipients:=«This email address is being protected from spambots. You need JavaScript enabled to view it.«, Subject:=«Hi», ReturnReceipt:=True

End Sub

Example 17 — Email workbook with sendmail method, specifying multiple recipients as array.

Sub SendMail_2()
’email workbook with sendmail method, specifying multiple recipients as array

‘specifies multiple recipients’ names as array:
ThisWorkbook.SendMail Array(«David Kelly», «Tracy Murray»)

‘specifies multiple recipients’ emails as array:

ThisWorkbook.SendMail Array(«This email address is being protected from spambots. You need JavaScript enabled to view it.«, «This email address is being protected from spambots. You need JavaScript enabled to view it.«)

End Sub

Example 18 — Email a Single Worksheet using the Sendmail method.

For live code of this example, click to download excel file.

Sub SendMail_3()
’email a specified worksheet(s) using the Sendmail method

Dim strName1 As String, strName2 As String
Dim wb As Workbook

‘change the current directory to ThisWorkbook directory, using the ChDir Statement — this sets the new default directory or folder:
ChDir ThisWorkbook.Path

‘creates a new workbook with a single sheet as copied from ThisWorkbook:
ThisWorkbook.Worksheets(«Sheet1»).Copy
‘set variable to the new workbook, which becomes the active workbook:
Set wb = ActiveWorkbook
‘rename the sheet in the new workbook:
wb.Sheets(«Sheet1»).Name = «NewSheet»
‘save new workbook with a file name, in the default folder:
wb.SaveAs fileName:=«NewBook.xlsx»

‘assign variables for recipients’ names:
strName1 = «David Kelly»
strName2 = «Tracy Murray»

‘specifies multiple recipients’ names as array; pick subject text from workbook range:
wb.SendMail Array(strName1, strName2), Subject:=ThisWorkbook.Worksheets(«Sheet1»).

Range(«A1»), ReturnReceipt:=False

‘close the new workbook:

wb.Close

End Sub

Example 19 — Email workbook with sendmail method, specifying recipient from worksheet cell, with a date stamp in the subject.

Sub SendMail_4()
’email workbook with sendmail method, specifying recipient from worksheet cell, with a date stamp in the subject

Dim strRec As String

‘Range(«A14») contains: This email address is being protected from spambots. You need JavaScript enabled to view it.
strRec = ThisWorkbook.Sheets(«Sheet1»).Range(«A14»).Value

‘subject will display as «Please Check 12/18/2013 10:43:06 AM»

ActiveWorkbook.SendMail Recipients:=strRec, Subject:=«Please Check » & Format(Now, «mm/dd/yyyy hh:mm:ss AMPM»)

End Sub

Example 20 — Email workbook with sendmail method, specifying multiple recipients from worksheet range.

Sub SendMail_5()
’email workbook with sendmail method, specifying multiple recipients from worksheet range

Dim MyArr As Variant

‘Range(«A14»)=This email address is being protected from spambots. You need JavaScript enabled to view it., Range(«A15»)=This email address is being protected from spambots. You need JavaScript enabled to view it.
ActiveWorkbook.SendMail Recipients:=ThisWorkbook.Sheets(«Sheet1»).

Range(«A14:A15»).Value

‘MyArr = ThisWorkbook.Sheets(«Sheet1»).Range(«A14:A15»)
ActiveWorkbook.SendMail Recipients:=MyArr

‘Range(«A10»)=David Kelly, Range(«A11»)=Tracy Murray; Range(«A14»)=This email address is being protected from spambots. You need JavaScript enabled to view it., Range(«A15»)=This email address is being protected from spambots. You need JavaScript enabled to view it.
‘named ranges: «NameList»=Range(«A10:A11»), «EmailList»=Range(«A14:A15»)
MyArr = ThisWorkbook.Sheets(«Sheet1»).Range(«NameList»)
MyArr = ThisWorkbook.Sheets(«Sheet1»).Range(«EmailList»)

ActiveWorkbook.SendMail Recipients:=MyArr

End Sub

Workbook.ActiveSheet Property

This property returns the currently Active Sheet in a workbook or window. Syntax: WorkbookObject.ActiveSheet. For a workbook appearing in multiple windows, the ActiveSheet might be different for each window. If there is no active sheet, this property returns Nothing. Use the Activate method of the Worksheet object to activate a sheet viz. ActiveWorkbook.Sheets(«Sheet3»).Activate will activate the sheet named «Sheet3» in the active workbook, which name will be displayed by MsgBox ActiveWorkbook.ActiveSheet.Name.

Workbook.ActiveChart Property

This property returns the currently Active Chart, which can be a chart sheet or an embedded chart. Syntax: WorkbookObject.ActiveChart. If there is no active chart, this property returns Nothing. Use the Activate method of the ‘Chart object’ or ‘ChartObject object’ to activate a chart sheet or embedded chart respectively. A chart sheet is active if selected by user or activated using the Activate method. An embedded chart is active if selected by the user or the ChartObject object is activated using the Activate method. See below example.

Example 21 — Illustrate ActiveChart property & Activate method.

Sub ActiveChart()
‘illustrate ActiveChart property

‘activate chart sheet named «Chart1»:
ActiveWorkbook.Sheets(«Chart1»).activate

‘alternatively, to activate chart sheet one:
‘ActiveWorkbook.Charts(1).activate

‘returns active chart — «Chart1»
MsgBox ActiveWorkbook.ActiveChart.Name

‘activate embedded chart named «Chart 13» in «Sheet2», using the Activate method of the ‘ChartObject object’:
ActiveWorkbook.Sheets(«Sheet2»).

ChartObjects(«Chart 13»).activate

‘alternatively, to activate ChartObject one in «Sheet2»:
‘ActiveWorkbook.Sheets(«Sheet2»).

ChartObjects(1).activate

‘returns active chart — «Sheet2 Chart 13»
MsgBox ActiveWorkbook.ActiveChart.Name

‘add a title to the active chart (embedded chart named «Chart 13» in «Sheet2»):

With ActiveWorkbook.ActiveChart

.HasTitle = True

.ChartTitle.Text = «EmbChart1»

End With

‘returns title text of active chart — «EmbChart1»

MsgBox ActiveWorkbook.ActiveChart.ChartTitle.Text

End Sub

Workbook.FileFormat Property

This property returns the file format (value as per XlFileFormat enumeration list) of the workbook. Syntax: WorkbookObject.FileFormat. This property is read-only, and you can specify or set the file format while saving an existing or new workbook using the Workbook.SaveAs Method (discussed above).

Workbook.Name Property

This property returns the name of a workbook (string value). Syntax: WorkbookObject.Name. This property is read-only and you cannot change a workbook name. You can however use the Workbook.SaveAs Method to: (i) save an existing workbook (in a separate file) with a new name; or (ii) save a new workbook with a name; as discussed above.

Sub WorkbookName()
‘return the names of all open workbooks

Dim i As Integer, count As Integer
‘returns the number of workbooks in the collection:
count = Workbooks.count

‘return names of all workbooks:

For i = 1 To count

MsgBox Workbooks(i).Name

Next i

End Sub

Workbook.Password Property

Use this property to set or return a password for opening a workbook. It is a read/write property. Syntax: WorkbookObject.Password. See below example which shows how to set password to open a workbook and change & delete an existing password.

Example 22 — Set workbook Password to open; Change existing workbook Password; Delete existing workbook Password.

Sub WorkbookPswd()
‘set workbook password to open; change existing workbook password; delete existing workbook password

‘this will not display the «replace file» prompt while using the SaveAs method:
Application.DisplayAlerts = False
Dim strPath As String, strName As String, strPswd As String, strNewPswd As String

‘specify full name (ie. path & name) of existing file to open:
strPath = «C:MyDocumentsFolder1»
strName = «NewBook.xlsx»

‘specify password(s) to open workbook:
strPswd = «123»
strNewPswd = «abc»

‘———————
‘open workbook without password:
Workbooks.Open fileName:=(strPath & «» & strName)
‘set the first workbook password:
ActiveWorkbook.Password = strPswd

‘close workbook after saving changes (ie. password):
ActiveWorkbook.Close SaveChanges:=True

‘———————
‘open workbook with password, updating external links or references:
Workbooks.Open fileName:=(strPath & «» & strName), UpdateLinks:=3, Password:=strPswd

‘will replace the existing file in the folder (file name is the same using SaveAs method) without displaying a prompt (Application.DisplayAlerts = False)
ActiveWorkbook.SaveAs fileName:=(strPath & «» & strName), Password:=strNewPswd
‘close workbook after saving changes (ie. new password):
ActiveWorkbook.Close SaveChanges:=True

‘———————
‘open workbook with password, updating external links or references:
Workbooks.Open fileName:=(strPath & «» & strName), UpdateLinks:=3, Password:=strNewPswd

‘will replace the existing file in the folder (file name is the same using SaveAs method) without displaying a prompt (Application.DisplayAlerts = False):
ActiveWorkbook.SaveAs fileName:=(strPath & «» & strName), Password:=«»
‘close workbook after saving changes (ie. removing password):
ActiveWorkbook.Close SaveChanges:=True

‘———————
Application.DisplayAlerts = True

End Sub

Workbook.Path Property

Use this property to return the full workbook path (string value). Syntax: WorkbookObject.Path. Refer example 22 wherein it is used.

Содержание

  • Ссылка на книгу с помощью VBA
  • Создание нового объекта книги
  • Откройте книгу с помощью VBA
  • Сохранение книги
  • Сохранение всех открытых книг
  • Сохранение и закрытие всех книг
  • Сохранить копию книги (с отметкой времени)
  • Создайте новую книгу для каждого рабочего листа
  • Назначьте объект книги переменной
  • Цикл через открытые книги
  • Ошибка при работе с объектом книги (ошибка времени выполнения «9»)
  • Получить список всех открытых книг
  • Откройте указанную книгу, дважды щелкнув ячейку
  • Куда поместить код VBA

В этом руководстве я расскажу, как работать с книгами в Excel с помощью VBA.

В Excel «Рабочая книга» — это объект, который является частью коллекции «Рабочие книги». В книге у вас есть различные объекты, такие как рабочие листы, листы диаграмм, ячейки и диапазоны, объекты диаграмм, фигуры и т. Д.

С помощью VBA вы можете выполнять множество операций с объектом книги, например открывать конкретную книгу, сохранять и закрывать книги, создавать новые книги, изменять свойства книги и т. Д.

Итак, приступим.

Все коды, которые я упоминаю в этом руководстве, необходимо поместить в редактор Visual Basic. Перейдите в раздел «Где разместить код VBA», чтобы узнать, как это работает.

Если вы заинтересованы в изучении VBA простым способом, ознакомьтесь с моими Онлайн-обучение по Excel VBA.

Есть разные способы ссылаться на объект Workbook в VBA. Выбранный вами метод будет зависеть от того, что вы хотите сделать. В этом разделе я расскажу о различных способах обращения к книге вместе с некоторыми примерами кодов.

Использование имен книг

Если у вас есть точное имя книги, к которой вы хотите обратиться, вы можете использовать это имя в коде.

Начнем с простого примера.

Если у вас открыты две книги и вы хотите активировать книгу с именем — Examples.xlsx, вы можете использовать следующий код:

Sub ActivateWorkbook () Workbooks ("Examples.xlsx"). Активировать End Sub

Обратите внимание, что вам нужно использовать имя файла вместе с расширением, если файл был сохранен. Если оно не было сохранено, вы можете использовать имя без расширения файла.

Если вы не знаете, какое имя использовать, обратитесь за помощью в Project Explorer.

Если вы хотите активировать книгу и выбрать определенную ячейку на листе в этой книге, вам необходимо указать полный адрес ячейки (включая книгу и имя рабочего листа).

Sub ActivateWorkbook () Рабочие книги ("Examples.xlsx"). Рабочие листы ("Sheet1"). Активировать диапазон ("A1"). Выберите End Sub

Приведенный выше код сначала активирует Sheet1 в книге Examples.xlsx, а затем выбирает ячейку A1 на листе.

Вы часто будете видеть код, в котором ссылка на рабочий лист или ячейку / диапазон делается без ссылки на книгу. Это происходит, когда вы ссылаетесь на лист / диапазоны в той же книге, в которой есть код и которая также является активной книгой. Однако в некоторых случаях вам необходимо указать книгу, чтобы убедиться, что код работает (подробнее об этом в разделе ThisWorkbook).

Использование порядковых номеров

Вы также можете ссылаться на книги по их порядковому номеру.

Например, если у вас открыто три книги, следующий код покажет вам имена трех книг в окне сообщения (по одному).

Sub WorkbookName () MsgBox Workbooks (1) .Name MsgBox Workbooks (2) .Name MsgBox Workbooks (3) .Name End Sub

В приведенном выше коде используется MsgBox — функция, отображающая окно сообщения с указанным текстом / значением (в данном случае это имя книги).

Одна из проблем, с которыми я часто сталкиваюсь при использовании порядковых номеров с рабочими книгами, заключается в том, что вы никогда не знаете, какая из них первая книга, а какая вторая и так далее. Конечно, вам нужно будет запустить код, как показано выше, или что-то подобное, чтобы просмотреть открытые книги и узнать их порядковый номер.

Excel обрабатывает книгу, открытую первой, так, чтобы она имела номер индекса как 1, а следующая — как 2 и так далее.

Несмотря на этот недостаток, использование индексных номеров может оказаться полезным. Например, если вы хотите перебрать все открытые книги и сохранить все, вы можете использовать номера индексов. В этом случае, поскольку вы хотите, чтобы это произошло со всеми книгами, вас не беспокоят их индивидуальные порядковые номера.

Приведенный ниже код будет перебирать все открытые книги и закрывать все, кроме книги с этим кодом VBA.

Sub CloseWorkbooks () Dim WbCount как целое число WbCount = Workbooks.Count For i = WbCount To 1 Step -1 Если Workbooks (i) .Name ThisWorkbook.Name Then Workbooks (i) .Close End If Next i End Sub

Приведенный выше код подсчитывает количество открытых книг, а затем просматривает все книги, используя цикл For Each.

Он использует условие IF, чтобы проверить, совпадает ли имя книги с именем книги, в которой выполняется код.

Если совпадений нет, рабочая книга закрывается и переходит к следующей.

Обратите внимание, что мы выполнили цикл от WbCount до 1 с шагом -1. Это делается по мере того, как с каждым циклом количество открытых книг уменьшается.

ThisWorkbook подробно рассматривается в следующем разделе.

Использование ActiveWorkbook

ActiveWorkbook, как следует из названия, относится к активной книге.

Приведенный ниже код покажет вам имя активной книги.

Sub ActiveWorkbookName () MsgBox ActiveWorkbook.Name End Sub

Когда вы используете VBA для активации другой книги, часть ActiveWorkbook в VBA после этого начнет ссылаться на активированную книгу.

Вот пример этого.

Если у вас есть активная книга, и вы вставляете в нее следующий код и запускаете ее, сначала будет показано имя книги с кодом, а затем имя Examples.xlsx (которое активируется кодом).

Sub ActiveWorkbookName () MsgBox ActiveWorkbook.Name Workbooks («Examples.xlsx»). Активировать MsgBox ActiveWorkbook.Name End Sub

Обратите внимание, что когда вы создаете новую книгу с помощью VBA, эта вновь созданная книга автоматически становится активной.

Использование ThisWorkbook

ThisWorkbook относится к книге, в которой выполняется код.

Каждая книга будет иметь объект ThisWorkbook как часть (видимый в Project Explorer).

ThisWorkbook может хранить обычные макросы (аналогичные тем, которые мы добавляем в модули), а также процедуры обработки событий. Процедура события — это то, что запускается на основе события, например двойного щелчка по ячейке, сохранения книги или активации листа.

Любая процедура события, которую вы сохраняете в этой «ThisWorkbook», будет доступна во всей книге по сравнению с событиями уровня листа, которые ограничены только определенными листами.

Например, если вы дважды щелкните объект ThisWorkbook в проводнике проекта и скопируйте и вставьте в него приведенный ниже код, он будет отображать адрес ячейки всякий раз, когда вы дважды щелкаете любую из ячеек во всей книге.

Private Sub Workbook_SheetBeforeDoubleClick (ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) MsgBox Target.Address End Sub

Хотя основная роль ThisWorkbook заключается в хранении процедуры события, вы также можете использовать ее для ссылки на книгу, в которой выполняется код.

Приведенный ниже код вернет имя книги, в которой выполняется код.

Sub ThisWorkbookName () MsgBox ThisWorkbook.Name End Sub

Преимущество использования ThisWorkbook (над ActiveWorkbook) заключается в том, что он будет ссылаться на одну и ту же книгу (ту, в которой есть код) во всех случаях. Поэтому, если вы используете код VBA для добавления новой книги, ActiveWorkbook изменится, но ThisWorkbook по-прежнему будет относиться к той, которая имеет код.

Создание нового объекта книги

Следующий код создаст новую книгу.

Sub CreateNewWorkbook () Workbooks.Add End Sub

Когда вы добавляете новую книгу, она становится активной.

Следующий код добавит новую книгу, а затем покажет вам имя этой книги (которое будет именем типа Book1 по умолчанию).

Sub CreateNewWorkbook () Workbooks.Add MsgBox ActiveWorkbook.Name End Sub

Откройте книгу с помощью VBA

Вы можете использовать VBA для открытия определенной книги, если знаете путь к файлу книги.

Приведенный ниже код откроет книгу — Examples.xlsx, которая находится в папке Documents в моей системе.

Sub OpenWorkbook () Workbooks.Open ("C:  Users  sumit  Documents  Examples.xlsx") End Sub

Если файл существует в папке по умолчанию, которая является папкой, в которой VBA сохраняет новые файлы по умолчанию, вы можете просто указать имя книги — без полного пути.

Sub OpenWorkbook () Workbooks.Open ("Examples.xlsx") End Sub

Если книга, которую вы пытаетесь открыть, не существует, вы увидите сообщение об ошибке.

Чтобы избежать этой ошибки, вы можете добавить несколько строк в свой код, чтобы сначала проверить, существует ли файл или нет, и, если он существует, попробуйте его открыть.

Приведенный ниже код проверит местоположение файла и, если он не существует, отобразит настраиваемое сообщение (не сообщение об ошибке):

Sub OpenWorkbook () If Dir ("C:  Users  sumit  Documents  Examples.xlsx") "" Then Workbooks.Open ("C:  Users  sumit  Documents  Examples.xlsx") Else MsgBox "Файл не "не существует" Конец Если Конец Подп.

Вы также можете использовать диалоговое окно «Открыть», чтобы выбрать файл, который хотите открыть.

Sub OpenWorkbook () При ошибке Возобновить следующий Dim FilePath As String FilePath = Application.GetOpenFilename Workbooks.Open (FilePath) End Sub

Приведенный выше код открывает диалоговое окно Открыть. Когда вы выбираете файл, который хотите открыть, он назначает путь к файлу переменной FilePath. Workbooks.Open затем использует путь к файлу для открытия файла.

Если пользователь не открывает файл и нажимает кнопку «Отмена», FilePath принимает значение False. Чтобы избежать появления ошибки в этом случае, мы использовали оператор «On Error Resume Next».

Связанный: Узнать все об обработке ошибок в Excel VBA

Сохранение книги

Чтобы сохранить активную книгу, используйте приведенный ниже код:

Подложка SaveWorkbook () ActiveWorkbook.Save End Sub

Этот код работает с книгами, которые уже были сохранены ранее. Кроме того, поскольку книга содержит указанный выше макрос, если он не был сохранен как файл .xlsm (или .xls), вы потеряете макрос, когда откроете его в следующий раз.

Если вы сохраняете книгу в первый раз, она покажет вам подсказку, как показано ниже:

При первом сохранении лучше использовать опцию «Сохранить».

Приведенный ниже код сохранит активную книгу как файл .xlsm в расположении по умолчанию (которое является папкой документов в моей системе).

Sub SaveWorkbook () ActiveWorkbook.SaveAs Имя файла: = "Test.xlsm", FileFormat: = xlOpenXMLWorkbookMacroEnabled End Sub

Если вы хотите, чтобы файл был сохранен в определенном месте, вам необходимо указать это в значении Filename. Приведенный ниже код сохраняет файл на моем рабочем столе.

Sub SaveWorkbook () ActiveWorkbook.SaveAs Имя файла: = "C:  Users  sumit  Desktop  Test.xlsm", FileFormat: = xlOpenXMLWorkbookMacroEnabled End Sub

Если вы хотите, чтобы пользователь мог выбрать место для сохранения файла, вы можете использовать диалоговое окно «Сохранить как». Приведенный ниже код показывает диалоговое окно «Сохранить как» и позволяет пользователю выбрать место для сохранения файла.

Sub SaveWorkbook () Dim FilePath As String FilePath = Application.GetSaveAsFilename ActiveWorkbook.SaveAs Filename: = FilePath & ".xlsm", FileFormat: = xlOpenXMLWorkbookMacroEnabled End Sub

Обратите внимание, что вместо использования FileFormat: = xlOpenXMLWorkbookMacroEnabled можно также использовать FileFormat: = 52, где 52 — это код xlOpenXMLWorkbookMacroEnabled.

Сохранение всех открытых книг

Если у вас открыто несколько книг и вы хотите сохранить все книги, вы можете использовать приведенный ниже код:

Sub SaveAllWorkbooks () Dim wb As Workbook for each wb In Workbooks wb.Save Next wb End Sub

Приведенное выше сохраняет все книги, включая те, которые никогда не сохранялись. Книги, которые не были сохранены ранее, будут сохранены в расположении по умолчанию.

Если вы хотите сохранить только те книги, которые были ранее сохранены, вы можете использовать следующий код:

Sub SaveAllWorkbooks () Dim wb As Workbook For each wb In Workbooks If wb.Path "" Then wb.Save End If Next wb End Sub

Сохранение и закрытие всех книг

Если вы хотите закрыть все книги, кроме книги, в которой есть текущий код, вы можете использовать приведенный ниже код:

Sub CloseandSaveWorkbooks () Dim wb As Workbook для каждого wb в рабочих книгах Если wb.Name ThisWorkbook.Name Then wb.Close SaveChanges: = True End If Next wb End Sub

Приведенный выше код закроет все книги (кроме книги с кодом — ThisWorkbook). Если в этих книгах есть изменения, они будут сохранены. Если есть книга, которая никогда не сохранялась, отобразится диалоговое окно «Сохранить как».

Сохранить копию книги (с отметкой времени)

Когда я работаю со сложными данными и панелью мониторинга в книгах Excel, я часто создаю разные версии своих книг. Это полезно на случай, если с моей текущей книгой что-то пойдет не так. По крайней мере, у меня была бы его копия, сохраненная под другим именем (и я потеряю только ту работу, которую проделал после создания копии).

Вот код VBA, который создаст копию вашей книги и сохранит ее в указанном месте.

Sub CreateaCopyofWorkbook () ThisWorkbook.SaveCopyAs Имя файла: = "C:  Users  sumit  Desktop  BackupCopy.xlsm" End Sub

Приведенный выше код будет сохранять копию вашей книги каждый раз, когда вы запускаете этот макрос.

Хотя это отлично работает, мне было бы удобнее, если бы я сохранял разные копии при каждом запуске этого кода. Причина, по которой это важно, заключается в том, что если я сделаю непреднамеренную ошибку и запущу этот макрос, он сохранит работу с ошибками. И у меня не будет доступа к работе, пока я не совершу ошибку.

Чтобы справиться с такими ситуациями, вы можете использовать приведенный ниже код, который сохраняет новую копию работы каждый раз, когда вы ее сохраняете. И он также добавляет дату и метку времени как часть имени книги. Это может помочь вам отследить любую допущенную вами ошибку, поскольку вы никогда не потеряете ни одну из ранее созданных резервных копий.

Private Sub Workbook_BeforeSave (ByVal SaveAsUI As Boolean, Cancel As Boolean) ThisWorkbook.SaveCopyAs Имя файла: = "C:  Users  sumit  Desktop  BackupCopy" & Format (Now (), "dd-mm-yy-hh-mm-ss -AMPM ") &" .xlsm "End Sub

Приведенный выше код будет создавать копию при каждом запуске этого макроса и добавлять метку даты / времени к имени книги.

Создайте новую книгу для каждого рабочего листа

В некоторых случаях у вас может быть книга с несколькими листами, и вы хотите создать книгу для каждого листа.

Это может быть в том случае, если у вас есть ежемесячные / ежеквартальные отчеты в одной книге, и вы хотите разделить их на одну книгу для каждого листа.

Или, если у вас есть отчеты по отделам, и вы хотите разделить их на отдельные книги, чтобы можно было отправлять эти отдельные книги руководителям отделов.

Вот код, который создаст книгу для каждого рабочего листа, присвоит ему то же имя, что и рабочий лист, и сохранит его в указанной папке.

Sub CreateWorkbookforWorksheets () Dim ws As Worksheet Dim wb As Workbook For each ws In ThisWorkbook.Worksheets Установить wb = Workbooks.Add ws.Copy Before: = wb.Sheets (1) Application.DisplayAlerts = False wb.Sheets (2) .Delete Application.DisplayAlerts = True wb.SaveAs "C:  Users  sumit  Desktop  Test " & ws.Name & ".xlsx" wb.Close Next ws End Sub

В приведенном выше коде мы использовали две переменные «ws» и «wb».

Код просматривает каждый рабочий лист (используя цикл For Each Next) и создает для него книгу. Он также использует метод копирования объекта рабочего листа для создания копии рабочего листа в новой книге.

Обратите внимание, что я использовал оператор SET для присвоения переменной «wb» любой новой книге, созданной с помощью кода.

Вы можете использовать этот метод, чтобы назначить объект книги переменной. Это рассматривается в следующем разделе.

Назначьте объект книги переменной

В VBA вы можете назначить объект переменной, а затем использовать переменную для ссылки на этот объект.

Например, в приведенном ниже коде я использую VBA для добавления новой книги, а затем назначаю эту книгу переменной wb. Для этого мне нужно использовать инструкцию SET.

После того, как я назначил книгу переменной, все свойства книги также становятся доступными для переменной.

Sub AssigntoVariable () Dim wb As Workbook Set wb = Workbooks.Add wb.SaveAs Filename: = "C:  Users  sumit  Desktop  Examples.xlsx" End Sub

Обратите внимание, что первый шаг в коде — объявить «wb» как переменную типа книги. Это сообщает VBA, что эта переменная может содержать объект книги.

Следующий оператор использует SET для присвоения переменной новой книги, которую мы добавляем. Как только это назначение будет выполнено, мы можем использовать переменную wb для сохранения книги (или сделать с ней что-нибудь еще).

Цикл через открытые книги

Мы уже видели несколько примеров кода выше, в которых использовался цикл в коде.

В этом разделе я объясню различные способы перебора открытых книг с помощью VBA.

Предположим, вы хотите сохранить и закрыть все открытые книги, кроме той, в которой есть код, тогда вы можете использовать следующий код:

Sub CloseandSaveWorkbooks () Dim wb As Workbook для каждого wb в рабочих книгах Если wb.Name ThisWorkbook.Name Then wb.Close SaveChanges: = True End If Next wb End Sub

В приведенном выше коде цикл For Each используется для просмотра каждой книги в коллекции Workbooks. Для этого нам сначала нужно объявить «wb» в качестве переменной типа книги.

В каждом цикле цикла каждое имя книги анализируется, и если оно не соответствует имени книги с кодом, она закрывается после сохранения своего содержимого.

То же самое может быть достигнуто с помощью другого цикла, как показано ниже:

Sub CloseWorkbooks () Dim WbCount As Integer WbCount = Workbooks.Count For i = WbCount To 1 Step -1 Если Workbooks (i) .Name ThisWorkbook.Name Then Workbooks (i) .Close SaveChanges: = True End If Next i End Sub

В приведенном выше коде цикл For Next используется для закрытия всех книг, кроме той, в которой есть код. В этом случае нам не нужно объявлять переменную книги, но вместо этого нам нужно подсчитать общее количество открытых книг. Когда у нас есть счетчик, мы используем цикл For Next для просмотра каждой книги. Кроме того, в этом случае мы используем порядковый номер для ссылки на книги.

Обратите внимание, что в приведенном выше коде мы переходим от WbCount к 1 с шагом -1. Это необходимо, поскольку с каждым циклом книга закрывается, а количество книг уменьшается на 1.

Ошибка при работе с объектом книги (ошибка времени выполнения «9»)

Одна из наиболее частых ошибок, с которыми вы можете столкнуться при работе с книгами, — это ошибка времени выполнения «9» — индекс вне допустимого диапазона.

Как правило, ошибки VBA не очень информативны и часто оставляют вам задачу выяснить, что пошло не так.

Вот некоторые из возможных причин, которые могут привести к этой ошибке:

  • Книга, к которой вы пытаетесь получить доступ, не существует. Например, если я пытаюсь получить доступ к пятой книге с помощью Workbooks (5), а открыты только 4 книги, я получу эту ошибку.
  • Если вы используете неправильное имя для ссылки на книгу. Например, если имя вашей книги — Examples.xlsx, и вы используете Example.xlsx. тогда он покажет вам эту ошибку.
  • Если вы не сохранили книгу и используете расширение, вы получите эту ошибку. Например, если имя вашей книги — Book1, и вы используете имя Book1.xlsx, не сохраняя его, вы получите эту ошибку.
  • Книга, к которой вы пытаетесь получить доступ, закрыта.

Получить список всех открытых книг

Если вы хотите получить список всех открытых книг в текущей книге (книге, в которой вы запускаете код), вы можете использовать следующий код:

Sub GetWorkbookNames () Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range ("A1"). Активировать для i = 1 В диапазон wbcount ("A1"). Смещение (i - 1, 0). Значение = Workbooks (i). Name Next i End Sub

Приведенный выше код добавляет новый лист, а затем перечисляет имена всех открытых книг.

Если вы также хотите получить путь к их файлу, вы можете использовать приведенный ниже код:

Sub GetWorkbookNames () Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range ("A1"). Активировать для i = 1 В диапазон wbcount ("A1"). Смещение (i - 1, 0). Значение = Workbooks (i) .Path & "" & Workbooks (i) .Name Next i End Sub

Откройте указанную книгу, дважды щелкнув ячейку

Если у вас есть список путей к файлам для книг Excel, вы можете использовать приведенный ниже код, чтобы просто дважды щелкнуть ячейку с путем к файлу, и эта книга откроется.

Private Sub Workbook_SheetBeforeDoubleClick (ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Workbooks.Open Target.Value End Sub

Этот код будет помещен в окно кода ThisWorkbook.

Сделать это:

  • Дважды щелкните объект ThisWorkbook в проводнике проекта. Обратите внимание, что объект ThisWorkbook должен находиться в книге, где вам нужна эта функция.
  • Скопируйте и вставьте приведенный выше код.

Теперь, если у вас есть точный путь к файлам, которые вы хотите открыть, вы можете сделать это, просто дважды щелкнув путь к файлу, и VBA мгновенно откроет эту книгу.

Куда поместить код VBA

Хотите знать, где находится код VBA в вашей книге Excel?

В Excel есть серверная часть VBA, называемая редактором VBA. Вам необходимо скопировать и вставить код в окно кода модуля VB Editor.

Вот как это сделать:

  1. Перейдите на вкладку Разработчик.
  2. Выберите вариант Visual Basic. Это откроет редактор VB в бэкэнде.
  3. На панели Project Explorer в редакторе VB щелкните правой кнопкой мыши любой объект книги, в которую вы хотите вставить код. Если вы не видите Project Explorer, перейдите на вкладку View и нажмите Project Explorer.
  4. Перейдите во вкладку «Вставить» и нажмите «Модуль». Это вставит объект модуля для вашей книги.
  5. Скопируйте и вставьте код в окно модуля.

Вам также могут понравиться следующие руководства по Excel VBA:

  • Как записать макрос в Excel.
  • Создание пользовательской функции в Excel.
  • Как создать и использовать надстройку в Excel.
  • Как возобновить макрос, поместив его в личную книгу макросов.
  • Получите список имен файлов из папки в Excel (с VBA и без).
  • Как использовать функцию Excel VBA InStr (с практическими примерами).
  • Как отсортировать данные в Excel с помощью VBA (пошаговое руководство).

Понравилась статья? Поделить с друзьями:
  • Excel vba sub return
  • Excel vba sub range
  • Excel vba string to number one
  • Excel vba string to long
  • Excel vba string not in array