VBA20Complete20Guide 1915108010
VBA20Complete20Guide 1915108010
“We are drowning in information but starved for knowledge.” – John Naisbitt
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.
Contents [hide]
https://excelmacromastery.com/excel-vba-workbook/ 1/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Task How to
https://excelmacromastery.com/excel-vba-workbook/ 2/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Task How to
Open workbook with the File Dialog See File Dialog section below function below
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.
End Sub
This example may look a little be confusing to a new user but it is actually quite simple.
The rst 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/excel-vba-workbook/ 4/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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.
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.
https://excelmacromastery.com/excel-vba-workbook/ 5/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
This means that VBA cannot nd the workbook you passed as a parameter.
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).
Note: To try this example create two open workbooks called Test1.xlsx and Test2.xlsx.
https://excelmacromastery.com/excel-vba-workbook/ 6/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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)
https://excelmacromastery.com/excel-vba-workbook/ 7/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
(https://excelmacromastery.com/wp-content/uploads/2014/12/ImmediateWindow2.jpg)
Shares
https://excelmacromastery.com/excel-vba-workbook/ 8/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
(https://excelmacromastery.com/wp-content/uploads/2014/12/ImmediateSampeText.jpg)
Workbooks(1) refers to the workbook that was opened rst. Workbooks(2) refers to the
workbook that was opened second and so on.
https://excelmacromastery.com/excel-vba-workbook/ 9/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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.
End Sub
https://excelmacromastery.com/excel-vba-workbook/ 10/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
End Sub
For accessing workbooks either of these methods is ne. The For Each
(http://excelmacromastery.com/the-ultimate-guide-to-loops-in-excel-vba/#The_For_Each_Loop)
loop is generally preferred when you are accessing a large number of objects. In terms of open
workbooks this is rarely an issue.
Note: Both examples read in the order of the rst opened to the last opened. If you want to read
in reverse order(last to rst) you can do this
End Sub
Open Workbook
https://excelmacromastery.com/excel-vba-workbook/ 11/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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
' Open the workbook and print the number of sheets it contains
Workbooks.Open ("C:\Docs\Book1.xlsm")
Debug.Print Workbooks("Book1.xlsm").Worksheets.Count
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 .
End Sub
https://excelmacromastery.com/excel-vba-workbook/ 12/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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.
If wk Is Nothing Then
Set wk = Workbooks.Open(sFullFilename)
End If
On Error Goto 0
Set GetWorkbook = wk
End Function
https://excelmacromastery.com/excel-vba-workbook/ 13/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Sub ExampleOpenWorkbook()
Dim wk As Workbook
Set wk = GetWorkbook(sFilename)
End Sub
This code is ne 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 le must be closed for the
application to run successfully. You can use the function below to simply check is the le
already open and if so inform the user that it must be closed rst.
https://excelmacromastery.com/excel-vba-workbook/ 14/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
End Select
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/excel-vba-workbook/ 15/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Sub ExampleUse()
End Sub
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 le.
You can specify whether to save the workbook or not and then the Excel messages will not
appear.
https://excelmacromastery.com/excel-vba-workbook/ 16/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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
wk.SaveAs "C:\Backups\accounts.xlsx"
The Workbook SaveAs method comes with twelve parameters which allow you to add a
password, set the le as read-only and so on. You can see the details here
(https://msdn.microsoft.com/en-us/library/o ce/ff841185.aspx)
You can also use VBA to save the workbook as a copy using SaveCopyAs
wk.SaveCopyAs "C:\Docs\Copy.xlsm"
Copy Workbook
https://excelmacromastery.com/excel-vba-workbook/ 17/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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
https://excelmacromastery.com/excel-vba-workbook/ 18/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
(https://excelmacromastery.com/wp-content/uploads/2014/12/FileDialog-
Workbooks.png)
The Windows File Dialog
The following function opens a workbook using the File Dialog. The function returns the full le
name if a le was selected. If the user cancels it displays a message and returns an empty
string.
https://excelmacromastery.com/excel-vba-workbook/ 19/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Dim FD As FileDialog
Set FD = Application.FileDialog(msoFileDialogFilePicker)
' Clean up
Set FD = Nothing
Done:
Exit Function
ErrorHandler:
MsgBox "Error: " + Err.Description
End Function
https://excelmacromastery.com/excel-vba-workbook/ 20/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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
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.
https://excelmacromastery.com/excel-vba-workbook/ 21/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Using ThisWorkbook is more useful than using Workbooks(). With ThisWorkbook we do not
need to worry about the name of the le. This gives us two advantages:
These may seem like very small advantages. The reality is your lenames will change all the
time. Using ThisWorkbook means your code will still work ne.
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.
End Sub
This can seem useful at rst. 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.
https://excelmacromastery.com/excel-vba-workbook/ 22/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
I hope I made it clear that you should avoid using ActiveWorkbook unless you really have to. In
this case be very careful.
End Sub
https://excelmacromastery.com/excel-vba-workbook/ 23/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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
Workbooks.Open ("C:\Docs\Book1.xlsm")
Debug.Print Workbooks("Book2.xlsm").Worksheets.Count
Debug.Print Workbooks("Book2.xlsm").Name
Workbooks("Book2.xlsm").Close
End Sub
https://excelmacromastery.com/excel-vba-workbook/ 24/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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.
When you create a new workbook you will generally want to Save it. The following code shows
you how to do this.
End Sub
When you create a new workbook it normally contains three sheets. This is determined by the
property Application.SheetsInNewWorkbook.
https://excelmacromastery.com/excel-vba-workbook/ 25/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
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.
End Sub
https://excelmacromastery.com/excel-vba-workbook/ 26/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
The following example has two Subs. The rst 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 nish of a section code using With.
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
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
https://excelmacromastery.com/excel-vba-workbook/ 27/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
5. To create a copy of an open workbook use the SaveAs property with a lename.
6. To create a copy of a workbook without opening use the FileCopy function.
7. To make your code easier to read and write use the With keyword.
8. Another way to make your code clear is to use a Workbook variables
9. To run through all open Workbooks use For Each wk in Workbooks where wk is a
workbook variable.
10. Try to avoid using ActiveWorkbook and Workbooks(Index) as their reference to a
workbook is temporary.
You can see a quick guide to the topic at the top of this post
Conclusion
This was an in-depth post about a very important element of VBA – the Workbook. I hope you
found it bene cial. 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 bene t 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. You may also want to check
out The Complete Guide to Worksheets in Excel VBA (http://excelmacromastery.com/the-
complete-guide-to-worksheets-in-excel-vba/). You can view all the posts by category here
(http://excelmacromastery.com/a-quick-guide-to-the-vba-posts/).
What’s Next
Once you understand Workbooks the next topics you may want to check out are Worksheets
(http://excelmacromastery.com/the-complete-guide-to-worksheets-in-excel-vba/) and Ranges
and Cells (http://excelmacromastery.com/the-complete-guide-to-ranges-and-cells-in-excel-
https://excelmacromastery.com/excel-vba-workbook/ 28/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
vba/). These three topics are a core part of VBA and it’s vital to understand them. You can get
the complete list of all the VBA posts here (http://excelmacromastery.com/a-quick-guide-to-
the-vba-posts/).
I also have a free eBook(see below) which you will nd useful if you are new to VBA.
(https://excelmacromastery.leadpages.co/leadbox/14791da73f72a2%3A106f25298346dc/563631833166
Please feel free to subscribe to my newsletter and get exclusive VBA content that you cannot
nd here on the blog, as well as free access to my eBook, How to Ace the 21 Most Common
Questions in VBA which is full of examples you can use in your own code.
(https://excelmacromastery.leadpages.co/leadbox/14791da73f72a2%3A106f25298346dc/563631833166
(https://excelmacromastery.leadpages.co/leadbox/14791da73f72a2%3A106f25298346dc/563631833166
(https://excelmacromastery.com/tag/open-workbook/) Range
(https://excelmacromastery.com/tag/range/) Workbooks
(https://excelmacromastery.com/tag/workbooks/) Workbooks Open
(https://excelmacromastery.com/tag/workbooks-open/) Worksheets
(https://excelmacromastery.com/tag/worksheets/)
Next
The Complete Guide To The VBA Worksheet (https://excelmacromastery.com/excel-
vba-worksheet/)
10 COMMENTS
Sidharth Saini
February 14, 2016 at 5:13 pm (https://excelmacromastery.com/excel-vba-workbook/#comment-2)
Very nicely explained topics. But symbols of > and < in examples are have problems. Please
change them.
Reply (https://excelmacromastery.com/excel-vba-workbook/?replytocom=2#respond)
Paul Kelly
February 15, 2016 at 3:26 pm (https://excelmacromastery.com/excel-vba-workbook/#comment-3)
Hi Sidharth,
Regards
Paul
Reply (https://excelmacromastery.com/excel-vba-workbook/?
replytocom=3#respond)
https://excelmacromastery.com/excel-vba-workbook/ 30/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Pooja
February 18, 2016 at 12:01 pm (https://excelmacromastery.com/excel-vba-workbook/#comment-4)
Hi Paul, I’ve gone through couple of websites to actually learn Macros if a person is novice and
none could provide the basics so clearly the way you are doing.
I’m actually learning VBA and macros through your website.
Gr8 work
Reply (https://excelmacromastery.com/excel-vba-workbook/?replytocom=4#respond)
Paul Kelly
February 18, 2016 at 1:45 pm (https://excelmacromastery.com/excel-vba-workbook/#comment-5)
Reply (https://excelmacromastery.com/excel-vba-workbook/?
replytocom=5#respond)
Petros
June 2, 2016 at 8:27 pm (https://excelmacromastery.com/excel-vba-workbook/#comment-6)
Reply (https://excelmacromastery.com/excel-vba-workbook/?replytocom=6#respond)
Paul Kelly
June 3, 2016 at 7:23 am (https://excelmacromastery.com/excel-vba-workbook/#comment-7)
Hi Petros
Reply (https://excelmacromastery.com/excel-vba-workbook/?
replytocom=7#respond)
Cor
https://excelmacromastery.com/excel-vba-workbook/ 31/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Hi Paul,
I like your site because the explanations you provide are really making me understand some
things I didn’t before.
However I found a few hickups in the ‘Finding all open workbooks section’. In the seconde and
third example (PrintWrkFileNameIdx and PrintWrkFileNameIdxRev) you use “Dim i” and then
continue with ‘”Next wrk”. I guess someone copied the rst example (PrintWrkFileName), where
“wrk” was actually used, and changed the contents
Greetings
Cor
Reply (https://excelmacromastery.com/excel-vba-workbook/?replytocom=8#respond)
Paul Kelly
August 24, 2016 at 9:01 am (https://excelmacromastery.com/excel-vba-workbook/#comment-9)
Hi Cor,
Thanks for your comment. Glad you like the site. I’ve update the post to x
those issues.
Regards
Paul
Reply (https://excelmacromastery.com/excel-vba-workbook/?
replytocom=9#respond)
sneha sheth
January 4, 2017 at 12:23 pm (https://excelmacromastery.com/excel-vba-workbook/#comment-2275)
hi paul….
what a great piece of work. i m glad i accessed ur site. being a software engineer my self … i
was really in search of logically connected concepts and not the syntax ….and i found both…
thanks a lot
Reply (https://excelmacromastery.com/excel-vba-workbook/?replytocom=2275#respond)
https://excelmacromastery.com/excel-vba-workbook/ 32/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
Paul Kelly
January 4, 2017 at 2:00 pm (https://excelmacromastery.com/excel-vba-workbook/#comment-2278)
Reply (https://excelmacromastery.com/excel-vba-workbook/?
replytocom=2278#respond)
LEAVE A REPLY
Your email address will not be published. Required elds are marked *
Name *
Email *
Website
Post Comment
Proudly powered by WordPress (http://wordpress.org/). Theme: Flat 1.7.8 by Themeisle (https://themeisle.com/themes/ at/).
https://excelmacromastery.com/excel-vba-workbook/ 33/34
9/8/2017 The Complete Guide To The VBA Workbook - Excel Macro Mastery
https://excelmacromastery.com/excel-vba-workbook/ 34/34