In this Article
- The Workbook Object
- Workbook Index Number
- Activate Workbook, ActiveWorkbook, and ThisWorkbook
- Activate Workbook
- ActiveWorkbook
- ThisWorkbook
- Open Workbook
- Open and Assign to Variable
- Open File Dialog
- Create New (Add) Workbook
- Add New Workbook to Variable
- Close Workbook
- Close & Save
- Close without Save
- Workbook Save As
- Other Workbook VBA Examples
- Workbook Name
- Protect Workbook
- Loop Through all Open Workbooks
- Workbook Activate Event
This guide will introduce you working with the Workbook Object in VBA.
The Workbook Object
First, in order to interact with workbooks in VBA, you must understand the Workbook Object.
With the workbook object, you can reference workbooks by their name like this:
Workbooks("Book2.xlsm").Activate
However, this code will only work if the workbook is open. If the workbook is closed, you will need to provide the full workbook path:
Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")
Instead of typing out the full path, if your desired workbook is in the same directory as the workbook where your code is stored, you could use this line code to open the workbook:
Workbooks.Open (ThisWorkbook.Path & "book2.xlsm")
This makes use of the ThisWorkbook object that we will discuss in the next section.
Workbook Index Number
Last, you can reference workbooks by their “Index Number”. The index number of a workbook corresponds to the order that the workbook was opened (technically its the workbook’s position in the Workbooks Collection).
Workbooks(1).Activate
This is useful if you want to do something like close the first (or last) opened workbook.
Activate Workbook, ActiveWorkbook, and ThisWorkbook
If a workbook is NOT ACTIVE, you can access the Workbook’s objects like this:
Workbooks("Book2.xlsm").Sheets("Sheet1").Range("A1").value = 1
However, if the workbook is Active, you can omit the workbook object:
Sheets("Sheet1").Range("A1").value = 1
And if you want to interact with the workbook’s active sheet, you can also ommit the sheets object:
Range("A1").value = 1
Activate Workbook
To activate a workbook, use the Activate Method.
Workbooks("Book2.xlsm").Activate
Now you can interact with Book2’s object’s without explicitly stating the workbook name.
ActiveWorkbook
The ActiveWorkbook object always refer to the active workbook. This is useful if you’d like to assign the ActiveWorkbook to a variable to use later.
Dim wb As Workbook
Set wb = ActiveWorkbook
ThisWorkbook
The ThisWorkbook object always refers to the workbook where the running code is stored. To activate ThisWorkbook, use this line of code:
ThisWorkbook.Activate
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Open Workbook
To open a workbook, use the Open Method:
Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")
The newly opened workbook will always become the ActiveWorkbook, allowing you to easily interact with it.
ActiveWorkbook.Save
The Open Method has several other arguments, allowing you to open read-only, open a password-protected workbook, and more. It’s covered here in our article about Opening / Closing Workbooks.
Open and Assign to Variable
You can also open a workbook and assign it to a variable at the same time:
Dim wb As Workbook
Set wb = Workbooks.Open("C:UsersStevePC2Downloadsbook2.xlsm")
Open File Dialog
You can also trigger the Open File Dialog Box like this:
Sub OpenWorkbook ()
Dim strFile As String
strFile = Application.GetOpenFilename()
Workbooks.Open (strFile)
End Sub
VBA Programming | Code Generator does work for you!
Create New (Add) Workbook
This line of code will create a new workbook:
Workbooks.Add
The new workbook now becomes the ActiveWorkbook, allowing you to interact with it (ex. save the new workbook).
Add New Workbook to Variable
You can also add a new workbook directly to a variable:
Dim wb As Workbook
Set wb = Workbooks.Add
Close Workbook
Close & Save
To close a workbook with saving, use the Close Method with SaveChanges set to TRUE:
ActiveWorkbook.Close SaveChanges:=True
Close without Save
To close without saving, set SaveChanges equal to FALSE:
ActiveWorkbook.Close SaveChanges:=False
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook Save As
The SaveAs Method is used to save a workbook as.
To save a workbook with a new name, in the same directory, you can imply use this:
ActiveWorkbook.SaveAs "new"
where “new” is the new file name.
To save a workbook in a new directory with a specific file extension, simply specify the new directory and file name:
ActiveWorkbook.SaveAs "C:UsersStevePC2Downloadsnew.xlsm"
Other Workbook VBA Examples
Workbook Name
To get the name of a workbook:
MsgBox ActiveWorkbook.Name
Protect Workbook
To protect the workbook structure from editing, you can use the Protect Method (password optional):
Workbooks("book1.xlsm").Protect "password"
To unprotect a workbook use the UnProtect Method:
Workbooks("book1.xlsm").Unprotect "password"
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Loop Through all Open Workbooks
To loop through all open workbooks:
Sub LoopThroughWBs()
Dim wb As Workbook
For Each wb In Workbooks
MsgBox wb.Name
Next wb
End Sub
Workbook Activate Event
You can run some code whenever a specific workbook is opened with the Workbook Open Event.
Place this procedure your workbook’s ThisWorkbook Module:
Private Sub Workbook_Open()
Sheets("sheet1").Activate
End Sub
This procedure will activate Sheet1 every time the workbook is opened.
In Excel, a workbook is one of the most important of all the Excel Objects, and it is also essential to understand how to use and refer to workbooks while writing VBA codes.
In this tutorial, we will explore all the things that you need to know. But, the first thing you need to understand are objects that are involved in using workbooks in VBA.
Objects you need to know:
- Workbooks Object
- Workbook Object
Both of these objects sound the same, but there’s a core difference between both of them.
Workbooks Object
In VBA, the workbooks object represents the collection of the workbooks that are open in Microsoft Excel. Imagine you have ten workbooks open at the same time. And you want to refer to the one workbook out of them. In that case, you need to use the workbook object to refer to that one workbook using its name.
Workbook Object
In VBA, the workbook object represents one single workbook from the entire collection of workbooks open at present in Microsoft Excel. The best way to understand this is to think about declaring a variable as a workbook that you want to use to refer to a particular workbook in the code.
Useful Links: Add Developer Tab | Visual Basic Editor | Run a Macro | Personal Macro Workbook
To work with workbooks in VBA, the first thing that you need to know is how to refer to a workbook in a macro. Here’s the happy thing: there are multiple ways to refer to a workbook. And ahead, we will explore each one of them.
1. By Name
The easiest way to refer to a workbook is to use its name. Let’s say you want to activate the workbook Book1.xlsx, in that case, the code that you need to use should be like the following:
Referring to a workbook with its name is quite simple, you need to specify the name, and that’s it. But here’s one thing that you need to take care of: if a workbook is not saved, then you need to use only the name. And if saved, then you need to use the name along with the extension.
2. By Number
When you open a workbook, Excel gives an index number to that workbook, and you can use that number to refer to a workbook. The workbook that you have opened at first will have the index number “1” and the second will have “2” and so on.
This method might seem less real to you as it’s hard to know which workbook is on which index number. But there’s one situation where this method is quite useful to use, and that’s looping through all the open workbooks.
3. By ThisWorkbook
This workbook is a property that helps you to refer to the workbook where you are writing the code. Let’s say you are writing the code in “Book1” and use the ThisWorkbook to save the workbook. Now even when you change the name of the workbook, you won’t need to change the code.
The above code counts the number of sheets in the workbook where this code is written and shows a message box with the result.
4. By ActiveWorkbook
If you want to refer to a workbook that is active, then you need to use the “ActiveWorkbook” property. The best use of this property is when you are sure which workbook is activated now. Or you have already activated the workbook that you want to work.
The above code activates the workbook “Book1” first and then uses the active workbook property to save and close the active workbook.
Access all the Methods and Properties
In VBA, whenever you refer to an object, VBA allows you to access the properties and methods that come with that object. In the same way, the workbook object comes with properties and methods. To access them, you need to define the workbook first and then enter a dot.
The moment you type a dot (.), it shows the list of properties and methods. Now, you must have a question in your mind about how to identify which one is a property and which one is a method.
Here’s the trick. If you look closely, you can identify a moving green brick and grey hand before each name on the list. So, all the properties have that grey hand before the name and methods have a moving green brick.
For example to use a Method with Workbook
Imagine you want to close a workbook (which is a method), you need to type or select “Close” from the list.
After that, you need to enter starting parentheses to get the IntelliSense to know the arguments you need to define.
With the close method, there are three arguments that you need to define, and as you can see, all these arguments are optional, and you can skip them if you want. But some methods don’t have arguments (for example: activate)
For example to use a Property with Workbook
Imagine you want to count the sheets from the workbook “book1” in that case, you need to use the “Sheets” property and then the further count property of it.
In the above code, as I said, you have book1 defined, and then the sheet property refers to all the sheets, and then the count property to count them. And when you run this code, it shows you a message box with the result.
Using “WITH” Statement with Workbook
In VBA, there’s a “With” statement that can help you work with a workbook while writing a macro efficiently. Let’s see the below example where you have three different code lines with the same workbook, i.e., ActiveWorkbook.
With the “WITH statement”, you can refer to the active workbook a single time, and use all the properties and methods that you have in the code.
- First of all, you need to start with the starting statement “With ActiveWorkbook” and end the statement with “End With”.
- After that, you need to write the code between this statement that you have in the above example.
As you can see in the above code we have referred to the ActiveWorkbook one using the WITH statement, and then all the properties and methods need to be used.
Sub vba_activeworkbook_with_statement()
With ActiveWorkbook
.Sheets.Add Count:=5
.Charts.Visible = False
.SaveAs ("C:UsersDellDesktopmyFolderbook2.xlsx")
End With
End Sub
Let me tell you a simple real-life example to make you understand everything. Imagine you ask me to go to room 215 to get the water bottle, and when I come back, you again send me to room 215 to get a pen, and then again send me back to get a laptop. Now here’s the thing: All the things that you told me to get are in room 215. So better if you sent me to room 215 and told me to get all three things at once.
Read: With – End With
Declaring a Variable as a Workbook
Sometimes you need to declare a variable as a workbook to use it further in the code. Well, this doesn’t require anything special for you to do.
- Use the DIM Statement (Declare).
- Write the name of the Variable.
- Define the type of the variable as Workbook.
Dealing with Errors
When you work with a workbook(s) object in VBA, there are chances that you need to deal with errors as well. Take an example of the “Run-time Error 9: Subscript out of Range” error. This error can occur for various reasons.
- The workbook that you are trying to refer to is not opened.
- Might be you have misspelled the name.
- The workbook you are referring to is not yet saved and you are using the extension along with the name.
- If you are using the index number to refer to a workbook and the number you have used is greater than the total number of workbooks open.
“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.)
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
- The workbook is currently closed.
- You spelled the name wrong.
- 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.
- (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.
- 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)
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.
The Windows File Dialog
The FileDialog is configurable and you can use it to
- Select a file.
- Select a folder.
- Open a file.
- “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:
- Changing the file name will not affect the code
- 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
- To get the workbook containing the code use ThisWorkbook.
- To get any open workbook use Workbooks(“Example.xlsx”).
- To open a workbook use Set Wrk = Workbooks.Open(“C:FolderExample.xlsx”).
- Allow the user to select a file using the UserSelectWorkbook function provided above.
- To create a copy of an open workbook use the SaveAs property with a filename.
- To create a copy of a workbook without opening use the FileCopy function.
- To make your code easier to read and write use the With keyword.
- Another way to make your code clear is to use a Workbook variables
- To run through all open Workbooks use For Each wk in Workbooks where wk is a workbook variable.
- 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.)
VBA Workbook Methods
Workbook methods helps us to perform different actions to deal with Excel Applications. For example, we can Activate a Workbook or Close a Workbook or save a Workbook etc. And also we can Protect and UnProtect Workbooks. Explore the various methods and examples on Excel VBA Workbook using side navigation. Below are the most frequently used Excel VBA Workbook methods.
Excel VBA Workbook Object Methods:
- Activate: To Activate a Workbook
- Close: To Close a Workbook
- Protect: To Protect a Workbook
- ProtectSharing: To ProtectSharing a Workbook
- RefreshAll: To RefreshAll a Workbook
- RejectAllChanges: To RejectAllChanges a Workbook
- RemoveUser: To RemoveUser in a Workbook
- RunAutoMacros: To RunAutoMacros in a Workbook
- Save: To Save a Workbook
- SaveAs: To SaveAs a Workbook
- SaveCopyAs: To SaveCopyAs a Workbook
- SendMail: To SendMail a Workbook
- UnProtect: To UnProtect a Workbook
- UnProtectSharing: To UnProtectSharing a Workbook
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
- Excel VBA Workbook Object Methods:
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
One Comment
-
Gamini Heraliyawala
December 9, 2015 at 1:07 PM — ReplyCan you kindly tell me the difference between two classes “Workbook” and “Workbooks” and how to address them with codes please…
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
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.