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
Go to Top
In this Article
- The Workbook Object
- Workbook Index Number
- Activate Workbook, ActiveWorkbook, and ThisWorkbook
- Activate Workbook
- ActiveWorkbook
- ThisWorkbook
- Open Workbook
- Open and Assign to Variable
- Open File Dialog
- Create New (Add) Workbook
- Add New Workbook to Variable
- Close Workbook
- Close & Save
- Close without Save
- Workbook Save As
- Other Workbook VBA Examples
- Workbook Name
- Protect Workbook
- Loop Through all Open Workbooks
- Workbook Activate Event
This guide will introduce you working with the Workbook Object in VBA.
The Workbook Object
First, in order to interact with workbooks in VBA, you must understand the Workbook Object.
With the workbook object, you can reference workbooks by their name like this:
Workbooks("Book2.xlsm").Activate
However, this code will only work if the workbook is open. If the workbook is closed, you will need to provide the full workbook path:
Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")
Instead of typing out the full path, if your desired workbook is in the same directory as the workbook where your code is stored, you could use this line code to open the workbook:
Workbooks.Open (ThisWorkbook.Path & "book2.xlsm")
This makes use of the ThisWorkbook object that we will discuss in the next section.
Workbook Index Number
Last, you can reference workbooks by their “Index Number”. The index number of a workbook corresponds to the order that the workbook was opened (technically its the workbook’s position in the Workbooks Collection).
Workbooks(1).Activate
This is useful if you want to do something like close the first (or last) opened workbook.
Activate Workbook, ActiveWorkbook, and ThisWorkbook
If a workbook is NOT ACTIVE, you can access the Workbook’s objects like this:
Workbooks("Book2.xlsm").Sheets("Sheet1").Range("A1").value = 1
However, if the workbook is Active, you can omit the workbook object:
Sheets("Sheet1").Range("A1").value = 1
And if you want to interact with the workbook’s active sheet, you can also ommit the sheets object:
Range("A1").value = 1
Activate Workbook
To activate a workbook, use the Activate Method.
Workbooks("Book2.xlsm").Activate
Now you can interact with Book2’s object’s without explicitly stating the workbook name.
ActiveWorkbook
The ActiveWorkbook object always refer to the active workbook. This is useful if you’d like to assign the ActiveWorkbook to a variable to use later.
Dim wb As Workbook
Set wb = ActiveWorkbook
ThisWorkbook
The ThisWorkbook object always refers to the workbook where the running code is stored. To activate ThisWorkbook, use this line of code:
ThisWorkbook.Activate
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Open Workbook
To open a workbook, use the Open Method:
Workbooks.Open ("C:UsersStevePC2Downloadsbook2.xlsm")
The newly opened workbook will always become the ActiveWorkbook, allowing you to easily interact with it.
ActiveWorkbook.Save
The Open Method has several other arguments, allowing you to open read-only, open a password-protected workbook, and more. It’s covered here in our article about Opening / Closing Workbooks.
Open and Assign to Variable
You can also open a workbook and assign it to a variable at the same time:
Dim wb As Workbook
Set wb = Workbooks.Open("C:UsersStevePC2Downloadsbook2.xlsm")
Open File Dialog
You can also trigger the Open File Dialog Box like this:
Sub OpenWorkbook ()
Dim strFile As String
strFile = Application.GetOpenFilename()
Workbooks.Open (strFile)
End Sub
VBA Programming | Code Generator does work for you!
Create New (Add) Workbook
This line of code will create a new workbook:
Workbooks.Add
The new workbook now becomes the ActiveWorkbook, allowing you to interact with it (ex. save the new workbook).
Add New Workbook to Variable
You can also add a new workbook directly to a variable:
Dim wb As Workbook
Set wb = Workbooks.Add
Close Workbook
Close & Save
To close a workbook with saving, use the Close Method with SaveChanges set to TRUE:
ActiveWorkbook.Close SaveChanges:=True
Close without Save
To close without saving, set SaveChanges equal to FALSE:
ActiveWorkbook.Close SaveChanges:=False
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook Save As
The SaveAs Method is used to save a workbook as.
To save a workbook with a new name, in the same directory, you can imply use this:
ActiveWorkbook.SaveAs "new"
where “new” is the new file name.
To save a workbook in a new directory with a specific file extension, simply specify the new directory and file name:
ActiveWorkbook.SaveAs "C:UsersStevePC2Downloadsnew.xlsm"
Other Workbook VBA Examples
Workbook Name
To get the name of a workbook:
MsgBox ActiveWorkbook.Name
Protect Workbook
To protect the workbook structure from editing, you can use the Protect Method (password optional):
Workbooks("book1.xlsm").Protect "password"
To unprotect a workbook use the UnProtect Method:
Workbooks("book1.xlsm").Unprotect "password"
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Loop Through all Open Workbooks
To loop through all open workbooks:
Sub LoopThroughWBs()
Dim wb As Workbook
For Each wb In Workbooks
MsgBox wb.Name
Next wb
End Sub
Workbook Activate Event
You can run some code whenever a specific workbook is opened with the Workbook Open Event.
Place this procedure your workbook’s ThisWorkbook Module:
Private Sub Workbook_Open()
Sheets("sheet1").Activate
End Sub
This procedure will activate Sheet1 every time the workbook is opened.
“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.)
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.
Содержание
- Workbook object (Excel)
- Remarks
- Example
- Events
- Methods
- Properties
- See also
- Support and feedback
- Объект Workbook (Excel)
- Замечания
- Пример
- События
- Методы
- Свойства
- См. также
- Поддержка и обратная связь
- VBA Working with Workbooks (The Workbook Object)
- The Workbook Object
- Workbook Index Number
- Activate Workbook, ActiveWorkbook, and ThisWorkbook
- Activate Workbook
- ActiveWorkbook
- ThisWorkbook
- VBA Coding Made Easy
- 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
- VBA Code Examples Add-in
- VBA Workbook – A Guide to Work with Workbooks in VBA
- Workbooks Object
- Workbook Object
- Refer to a Workbook in VBA
- 1. By Name
- 2. By Number
- 3. By ThisWorkbook
- 4. By ActiveWorkbook
- Access all the Methods and Properties
- For example to use a Method with Workbook
- For example to use a Property with Workbook
- Using “WITH” Statement with Workbook
- Declaring a Variable as a Workbook
- Dealing with Errors
- 2 thoughts on “VBA Workbook – A Guide to Work with Workbooks in VBA”
Workbook object (Excel)
Represents a Microsoft Excel workbook.
The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel.
The ThisWorkbook property of the Application object returns the workbook where the Visual Basic code is running. In most cases, this is the same as the active workbook. However, if the Visual Basic code is part of an add-in, the ThisWorkbook property won’t return the active workbook. In this case, the active workbook is the workbook calling the add-in, whereas the ThisWorkbook property returns the add-in workbook.
If you are creating an add-in from your Visual Basic code, you should use the ThisWorkbook property to qualify any statement that must be run on the workbook that you compile into the add-in.
Example
Use Workbooks (index), where index is the workbook name or index number, to return a single Workbook object. The following example activates workbook one.
The index number denotes the order in which the workbooks were opened or created. Workbooks(1) is the first workbook created, and Workbooks(Workbooks.Count) is the last one created. Activating a workbook doesn’t change its index number. All workbooks are included in the index count, even if they are hidden.
The Name property returns the workbook name. You cannot set the name by using this property; if you need to change the name, use the SaveAs method to save the workbook under a different name.
The following example activates Sheet1 in the workbook named Cogs.xls (the workbook must already be open in Microsoft Excel).
The ActiveWorkbook property of the Application object returns the workbook that’s currently active. The following example sets the name of the author for the active workbook.
This example emails a worksheet tab from the active workbook by using a specified email address and subject. To run this code, the active worksheet must contain the email address in cell A1, the subject in cell B1, and the name of the worksheet to send in cell C1.
Events
Methods
Properties
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Объект Workbook (Excel)
Представляет книгу Microsoft Excel.
Замечания
Объект Workbook является членом коллекции Workbooks . Коллекция Книги содержит все объекты Workbook , открытые в настоящее время в Microsoft Excel.
Свойство ThisWorkbook объекта Application возвращает книгу, в которой выполняется код Visual Basic. В большинстве случаев это то же самое, что и активная книга. Однако если код Visual Basic является частью надстройки, свойство ThisWorkbook не вернет активную книгу. В этом случае активной книгой является книга, вызывающая надстройку, тогда как свойство ThisWorkbook возвращает книгу надстройки.
Если вы создаете надстройку на основе кода Visual Basic, следует использовать свойство ThisWorkbook для определения инструкции, которая должна выполняться в книге, которую вы компилируете в надстройку.
Пример
Используйте workbooks (index), где index — это имя книги или номер индекса, чтобы вернуть один объект Workbook . В следующем примере активируется одна книга.
Номер индекса обозначает порядок открытия или создания книг. Workbooks(1) — первая созданная книга, а Workbooks(Workbooks.Count) — последняя созданная. Активация книги не изменяет ее номер индекса. Все книги включаются в число индексов, даже если они скрыты.
Свойство Name возвращает имя книги. Нельзя задать имя с помощью этого свойства; Если необходимо изменить имя, используйте метод SaveAs , чтобы сохранить книгу под другим именем.
В следующем примере выполняется активация Sheet1 в книге с именем Cogs.xls (книга уже должна быть открыта в Microsoft Excel).
Свойство ActiveWorkbook объекта Application возвращает книгу, которая сейчас активна. В следующем примере задается имя автора для активной книги.
В этом примере вкладка листа из активной книги отправляется по электронной почте, используя указанный адрес электронной почты и тему. Для выполнения этого кода активный лист должен содержать адрес электронной почты в ячейке A1, тему в ячейке B1 и имя листа, отправляемого в ячейку C1.
События
Методы
Свойства
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
VBA Working with Workbooks (The Workbook Object)
In this Article
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:
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:
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:
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).
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:
However, if the workbook is Active, you can omit the workbook object:
And if you want to interact with the workbook’s active sheet, you can also ommit the sheets object:
Activate Workbook
To activate a workbook, use the Activate Method.
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.
ThisWorkbook
The ThisWorkbook object always refers to the workbook where the running code is stored. To activate ThisWorkbook, use this line of code:
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!
Open Workbook
To open a workbook, use the Open Method:
The newly opened workbook will always become the ActiveWorkbook, allowing you to easily interact with it.
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:
Open File Dialog
You can also trigger the Open File Dialog Box like this:
Create New (Add) Workbook
This line of code will create a new workbook:
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:
Close Workbook
Close & Save
To close a workbook with saving, use the Close Method with SaveChanges set to TRUE:
Close without Save
To close without saving, set SaveChanges equal to FALSE:
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:
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:
Other Workbook VBA Examples
Workbook Name
Protect Workbook
To protect the workbook structure from editing, you can use the Protect Method (password optional):
To unprotect a workbook use the UnProtect Method:
Loop Through all Open Workbooks
To loop through all open workbooks:
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:
This procedure will activate Sheet1 every time the workbook is opened.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA Workbook – A Guide to Work with Workbooks in VBA
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.
Refer to a Workbook in VBA
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.
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.
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.
2 thoughts on “VBA Workbook – A Guide to Work with Workbooks in VBA”
I love your tutorial on MS Excel VBA programming. I am writing from Cameroon.
I am aspiring to be an expert in VBA. Please can you be my coach? What do you
recommend?
Источник