When working with an Excel workbook, there are a few basic operations that any user needs to know how to carry out. The following are 2 of the most important ones:
- Opening a workbook.
- Closing a workbook.
These 2 actions are just as important if you’re working with Visual Basic for Applications.
In this tutorial, I focus on topic #2: How you can easily close an Excel workbook with VBA.
For these purposes, in the first few sections of this tutorial, I introduce some VBA constructs that help you create macros that close workbooks. My focus is, mainly, in the Workbook.Close method. However, I also introduce the Workbooks.Close method, which allows you to quickly close all open workbooks. At the end of that first section, I discuss the topic of closing Excel workbooks without prompts and introduce some of the most common ways of achieving this.
In the second section of this post, I go through 8 macro code examples. These VBA code samples use the constructs introduced in the first section for purposes of closing Excel workbooks in different situations. All of the macros are accompanied by an explanation. You can easily adjust the code samples in order to fit your own needs.
This Excel VBA Close Workbook Tutorial is accompanied by an Excel workbook containing the macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Please use the following table of contents to quickly navigate to the section that interests you the most. For best results, you may want to read the whole blog post.
Let’s start by taking a look at the…
Workbook.Close Method
You can use the Workbook.Close method for purposes of closing the applicable workbook object.
The basic syntax of Workbook.Close is as follows:
expression.Close(SaveChanges, Filename, RouteWorkbook)
The following are the applicable definitions for purposes of the statement above:
- expression: Workbook object.
- SaveChanges: Optional argument. You use SaveChanges for purposes of specifying whether to save changes (True) or not (False).
- Filename: Optional argument. Filename allows you to specify the filename used by Excel when saving.
- RouteWorkbook: Optional argument. Makes reference to workbook routing. In that context, it allows you to determine whether the workbook is sent to the next recipient (True) or not (False).
Since expression represents a Workbook object, I simplify the syntax above to the following:
Workbook.Close(SaveChanges, Filename, RouteWorkbook)
Let’s start by taking a closer look at the 3 parameters (SaveChanges, Filename and RouteWorkbook) above. After covering these arguments, I provide a few additional comments about the Workbook.Close method.
SaveChanges Parameter
You use the SaveChanges parameter to specify whether Visual Basic for Applications saves changes to the workbook (or not) when the workbook:
- Has unsaved changes.
- Doesn’t appear in any other open windows.
Both of these conditions must be met in order for VBA to consider SaveChanges. In other words, VBA ignores SaveChanges in the following situations:
- When there aren’t any unsaved changes to the workbook.
- Where there are changes to the workbook, but the workbook appears within other open windows.
SaveChanges is an optional argument. You generally use the following values when working with it:
- True: Close workbook and save changes.
- False: Close workbook without saving changes.
If you omit the SaveChanges parameter and the relevant workbook contains unsaved changes, Excel displays a dialog box. This dialog asks the user whether the changes should be saved or not.
Filename Parameter
Filename allows you to specify the filename under which Excel saves the changes to the closed workbook.
Filename is an optional parameter. Additionally, Filename is only relevant if you set SaveChanges to True. Whenever you set the SaveChanges parameter to False, the changes aren’t saved at all.
If you omit Filename and the workbook has no previous filename, Excel displays the Save As dialog box and asks the user to provide the filename.
Despite the above, if you want to ensure that a particular workbook is saved under a certain name and close it, you can generally proceed as follows:
- Use the Workbook.SaveAs method to save the workbook; and
- Close the workbook by using the Workbook.Close method.
This way of proceeding is suggested by authorities such as author Richard Mansfield (in Mastering VBA for Microsoft Office 2016). Some of the advantages of using the SaveAs method (vs. the Filename parameter) for these purposes are the following:
- Ensures that the workbook is always saved under the filename you specify.
- Allows you to take advantage of the 10 parameters of the SaveAs method. By using these parameters, you can specify items such as (i) file format, and (ii) protection password.
RouteWorkbook Parameter
The RouteWorkbook parameter is associated to workbook routing. You can use RouteWorkbook to specify whether the workbook is routed to the next recipient or not.
RouteWorkbook is optional.
The main rules that Visual Basic for Applications uses to determine how to deal with RouteWorkbook are as follows:
- If there’s no need to send the workbook to the next recipient, VBA ignores RouteWorkbook.
For example, the workbook doesn’t need to be routed if (i) there’s no routing slip attached, or (ii) the routing has already occurred.
- If the workbook needs to be routed, VBA applies the value you specify for RouteWorkbook. You can use the following 2 values:
- True: VBA routes the workbook to the next recipient.
- False: The workbook isn’t sent.
- If you omit RouteWorkbook and the workbook need to be send, Excel asks the user whether the workbook is routed or not.
Workbook.Close Method And Auto_Close Macros
Auto_Close macros aren’t executed when you close the workbook from VBA. This is relevant if your workbook uses Auto_Close macros (vs. the BeforeClose event) for purposes of automatically running a macro before a workbook closes. The Workbook.Close method does trigger the BeforeClose event.
If you need to deal with Auto_Close macros and want the macro to be executed when you use the Workbook.Close method, use the Workbook.RunAutoMacros method.
Workbook.Close Method And Add-Ins
Usually, you install and uninstall add-ins through the Add-Ins dialog.
You can also open and close add-ins. In other words, you can theoretically apply the Workbook.Close method to an add-in.
As a consequence of the above, if you’ve accessed an add-in as a workbook (vs. using the Add-Ins dialog box), you can close it with the Close method. However, as a general rule, this isn’t the most appropriate way to deal with add-ins.
The reason for this is explained by Excel authorities Dick Kusleika and Mike Alexander in Excel 2016 Power Programming with VBA, as follows:
Using the Close method on an installed add-in removes the add-in from memory but does not set its Installed property to False. Therefore, the Add-Ins dialog box still lists the add-in as installed, which can be confusing.
Therefore, as a general rule, use the AddIn.Installed property for purposes of installing and removing add-ins.
Workbooks.Close Method
You can also apply the Close method to the collection of all open Excel workbooks. In other words, you can use the Workbooks.Close method to close all Excel workbooks at once.
The basic syntax of Workbooks.Close is as follows:
expression.Close
“expression” represents the Workbooks collection. Therefore, I simplify the above as follows:
Workbooks.Close
The Workbooks.Close method is, to a certain extent, similar to the Workbook.Close method I explain above. For example, Auto_Close macros aren’t executed when you close a workbook with either of these methods. Therefore, my comments above regarding Auto_Close macros and Workbook.Close are also generally applicable to Workbooks.Close.
There’s, however, a very important difference between Workbook.Close and Workbooks.Close:
Workbooks.Close takes no parameters. As I explain above, Workbook.Close has 3 parameters (SaveChanges, Filename and RouteWorkbook).
As a consequence of the above, if you want to use any (or all) of the parameters I describe above while closing all open workbooks, you generally have to rely on loops.
Further below, I provide macro code examples that you can use to close all open workbooks using either of these 2 methods:
- Workbooks.Close.
- Workbook.Close (+ loops).
Excel VBA To Close Workbook Without Prompts
In certain cases, you want to ensure that Excel closes a particular workbook without showing any prompts.
When working with the Close VBA method, the prompts that you usually have to deal with ask one of the following questions:
- Should Excel save the changes?
- What filename should Excel use?
There are a few different ways in which you can handle this using Visual Basic for Applications. The most common ways of tackling this issue are the following 4:
- Saving the workbook prior to using the Close method.
- Appropriately using the SaveChanges and Filename parameters of the Workbook.Close method.
- Using the Application.DisplayAlerts property.
- Setting the Workbook.Saved property to True.
I cover the topic of how to save a workbook using VBA (#1 above) in a separate blog post that you can find in the Archives. I cover both the SaveChanges and Filename arguments (#2 above) in this tutorial.
Therefore, in the following sections, I introduce the remaining VBA constructs #3 (Application.DisplayAlerts) and #4 (Workbook.Saved). Using either of these 2 properties results in Excel closing the workbook without prompts. In both cases, Excel closes the file without saving the changes.
Application.DisplayAlerts Property
The Application.DisplayAlerts property allows you to specify whether or not Excel displays certain prompts and alerts. For these purposes, you can set Application.DisplayAlerts to either of the following values:
- True: The default value. Excel displays alerts and messages.
- False: The alerts and messages aren’t displayed. If a particular alert or message requires a user response, Excel uses the default.
The basic syntax of Application.DisplayAlerts is as follows:
expression.DisplayAlerts
“expression” is the Excel Application object. Therefore, I simplify the above as follows:
Application.DisplayAlerts
Macro example #7 below uses the Application.DisplayAlerts property for purposes of closing a workbook without prompts. There are, however, other (better) ways of using VBA to close an Excel workbook without displaying prompts. I provide further explanation of this matter in the relevant section (for macro sample #7) further below.
Workbook.Saved Property
From a general perspective, the Workbook.Saved property indicates whether changes have been made to a particular Excel workbook since the last time it was saved. In other words, Workbook.Saved indicates whether the workbook has unsaved changes.
The basic syntax of Workbook.Saved is as follows:
expression.Saved
“expression” is a Workbook object. Therefore, I simplify the above as follows:
Workbook.Saved
The Saved property is, however, read/write. Therefore, you can set Workbook.Saved to either of the following values:
- True: No changes have been made since the last time the workbook was saved.
- False: Changes have been made.
By setting Saved to True prior to closing a workbook, you can close a workbook without Excel displaying a prompt. In such case, the changes to the workbook aren’t saved.
I provide a practical code example showing how you can easily do this further below (macro example #8).
In the following sections, I provide 8 macro code examples that allow you to close an Excel workbook using VBA. These 8 macro samples cover several of the most common situations you’re likely to encounter.
The Sub procedure examples I provide work with the active workbook. For these purposes, I use the Application.ActiveWorkbook property (ActiveWorkbook). By replacing the object reference, you can easily adjust these macros in order to work with other workbooks.
Macro Code Example #1: Excel VBA Close Workbook
At the most basic level, you can use a statement with the following structure to close an Excel workbook:
Workbook.Close
The following sample macro (Close_Workbook) closes the active workbook:
The macro example has a single statement that follows the structure I describe above:
ActiveWorkbook.Close
This statement is built by using the following items:
- ActiveWorkbook: The Application.ActiveWorkbook property returns the active workbook.
- Close: The Close method closes the active workbook returned by item #1.
Macro Code Example #2: Excel VBA Close Workbook Without Saving Changes
If you want to close a workbook without saving changes, you can use a statement that uses the following syntax:
Workbook.Close SaveChanges:=False
The following macro example (Close_Workbook_Without_Saving_Changes) closes the active workbook without saving changes:
The following are the items within the macro’s single statement:
- ActiveWorkbook: The active workbook.
- Close: The Close method.
- SaveChanges:=False: The SaveChanges parameter of the Workbook.Close method is set to False. Therefore, Excel doesn’t save changes prior to closing the workbook.
This macro is substantially the same as the previous example #1. The only new item is the SaveChanges argument (#3).
Macro Code Example #3: Excel VBA Close Workbook And Save Changes
You can use the following statement structure to close a workbook and save the changes:
Workbook.Close SaveChanges:=True
The following sample Sub procedure (Close_Workbook_Save_Changes) closes the active workbook and saves changes:
The only statement within the macro has the following 3 components:
- ActiveWorkbook: Reference to the active workbook.
- Close: The Close method.
- SaveChanges:=True: Sets the SaveChanges parameter of Workbook.Close to True. As a consequence of this, Excel saves the changes when closing the workbook.
This procedure is almost identical to macro sample #2 above. The only difference is the value to which the SaveChanges parameter (#3 above) is set (True vs. False).
Macro Code Example #4: Excel VBA Close Workbook And Save Changes With Filename
The VBA statement structure that I show below allows you to do the following:
- Save the workbook before closing.
- Set the filename that Excel uses if the workbook has no previously associated filename.
The following VBA statement structure allows you to do the above:
Workbook.Close SaveChanges:=True, Filename:=”fileNameString”
For these purposes, “fileNameString” is the file name you want Excel to use.
As I mention further above (section about the Filename parameter), using the statement I provide in this section doesn’t always result in the workbook being saved with the filename you want. In order to ensure that the workbook is saved always under the desired filename, you can generally use the Workbook.SaveAs method prior to calling the Workbook.Close method.
The following macro example (Close_Workbook_Save_Changes_Filename) closes the active workbook and saves changes under the specified filename. The filename under which the workbook is saved (if applicable) is “Excel VBA Close Workbook”.
The statement within the macro above has the following components:
- ActiveWorkbook: Application.ActiveWorkbook property.
- Close: Workbook.Close method.
- SaveChanges:=True: Sets the SaveChanges parameter of Workbook.Close to True.
- Filename:=”Excel VBA Close Workbook”: The Filename argument of the Close method. Specifies that the filename that Excel uses is “Excel VBA Close Workbook”.
This sample macro is very similar to the previous example #3. The only new item is the Filename parameter (#4).
Macro Code Examples #5 And #6: Excel VBA Close All Workbooks
In this section, I provide 2 macro examples that you can use to close all Excel workbooks at once.
As I mention above, you can use the Workbooks.Close method in order to close all the members of the Workbooks collection (i.e. all open workbooks). Therefore, you can use the following statement for purposes of closing all open Excel workbooks:
Workbooks.Close
The following macro code sample (Close_All_Workbooks) closes all workbooks with the Workbooks.Close method. The single statement within this macro is the one I explain above.
However, as I explain above, Workbooks.Close takes no parameters.
The Workbook.Close method does take parameters. The Workbook.Close method works with only one workbook at a time. In order to close all open workbooks at once, you can use a For Each… Next loop. The resulting structure of the relevant VBA loop is as follows:
For Each Workbook In Workbooks
Workbook.Close
Next Workbook
The following procedure example (Close_All_Workbooks_Loop) uses the Workbook.Close method and a For Each… Next loop to close all workbooks:
The process followed by this macro to close all open workbooks is as follows:
- Close the first open workbook.
- Check whether there are elements left within the collection of open workbooks.
- If there are open workbooks left:
- Close the next workbook.
- Repeat step #2 above.
- If there are no open workbooks left (step #2), exit the For Each… Next loop and end the macro.
The following diagram illustrates this procedure:
Let’s take a closer look at each of the lines of code within this sample macro:
Line #1: Dim myWorkbook As Workbook
The Dim statement declares the myWorkbook object variable.
Line #2: For Each myWorkbook In Workbooks
Opening statement of a For Each… Next loop. This repeats the execution of the statement within the loop (line #3 below) for each workbook within the Workbooks collection.
The 2 relevant items within this line of code are the following:
- myWorkbook: myWorkbook variable. Used to iterate through all the elements within the Workbooks collection (item #2).
- Workbooks: The Application.Workbooks property returns the collection of all open workbooks.
Line #3: myWorkbook.Close
This statement is exactly the same as that in macro sample #1 above. You can easily modify this statement to use the SaveChanges and/or Filename properties. Examples #2 through #4 are examples of how you can do this.
When within the For Each… Next loop, this line #3 results in Excel closing the applicable workbook. The closed workbook, therefore, is dependent on the current iteration of the loop.
Line #4: Next myWorkbook
Closing statement of the For Each… Next loop.
Macro Code Examples #7 And #8: Excel VBA Close Workbook Without Prompt
This section provides 2 macro code examples that allow you to close a workbook without prompts.
The first macro sample (#7) uses the following basic structure:
Application.DisplayAlerts = False
Workbook.Close
This results in Excel closing the workbook without prompts. Additionally, the workbook isn’t saved.
As I mention above when introducing the Application.DisplayAlerts property, you’re generally better off avoiding this particular VBA code structure. The other options I discuss in this tutorial (saving the workbook prior to calling Close, or using the SaveChanges and Filename parameters of Close) are more appropriate in most situations.
The following macro example (Close_Workbook_Without_Prompt_1) turns off Excel’s prompts and alerts prior to closing the workbook. Therefore, Excel closes the active workbook without prompts.
This sample macro is composed of the following 2 statements:
- Application.DisplayAlerts = False: Sets the Application.DisplayAlerts property to False. As a consequence, Excel turns off prompts.
- ActiveWorkbook.Close: The Application.ActiveWorkbook property and the Workbook.Close method are used to close the active workbook.
The second macro within this section uses the following syntax:
With Workbook
.Saved = True
.Close
End With
By setting the Workbook.Saved property to True, you indicate that no changes have been made since the last time the workbook was saved. In other words, you’re telling Excel that the workbook you’re closing doesn’t need to be saved.
The following macro code sample (Close_Workbook_Without_Prompt_2) sets the Saved property to True prior to calling the Workbook.Close method. As a consequence of this, the active workbook is closed without displaying prompts.
Let’s take a closer look at each of the lines of code within this sample Sub procedure:
Line #1: With ActiveWorkbook
Opening line for a With… End With block. As a consequence of this, the statements within the block (lines #2 and #3) work with the object specified in this line #1. That object is the active workbook (ActiveWorkbook).
Line #2: .Saved = True
Sets the Workbook.Saved property to True. Indicates that no changes have been made to the active workbook (in line #1 above) since last time the workbook was saved.
Line #3: .Close
Calls the Workbook.Close method. Closes the active workbook (in line #1 above).
Line #4: End With
Closing line of the End… End With statement.
Conclusion
After reading this Excel VBA tutorial, you have the knowledge you need to start crafting macros that quickly close Excel workbooks in several different scenarios.
In the first section of this tutorial, you read about the 2 VBA methods you can use to close Excel workbooks:
- Workbook.Close.
- Workbooks.Close.
In addition to reading about how you can easily use each of these methods, you’ve seen why most VBA Sub procedures rely on the Workbook.Close method. You’ve also read about how, by appropriately using the parameters of Workbook.Close or combining this method with other VBA constructs, you can specify how Excel acts when closing a workbook.
Finally, you’ve seen 8 examples of macro code that put the above VBA constructs and information in practice.
Overall, the information and examples within this tutorial allow you to easily and quickly create Excel macros that achieve a variety of objects. The following are some examples of what you can now do with Visual Basic for Applications:
- Close a particular Excel workbook.
- Close a workbook without saving changes.
- Close a workbook and save the changes. This includes the possibility of setting the filename Excel uses when saving.
- Close all open workbooks at once.
- Close an Excel workbook without any prompts.
This Excel VBA Close Workbook Tutorial is accompanied by an Excel workbook containing the macros I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Books Referenced In This Excel Tutorial
- Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
- Mansfield, Richard (2016). Mastering VBA for Microsoft Office 2016. Indianapolis, IN: John Wiley & Sons Inc.
In this Article
- Open a Workbook in VBA
- Open Workbook From Path
- Open Workbook – ActiveWorkbook
- Open Workbook and Assign to a Variable
- Workbook Open File Dialog
- Open New Workbook
- Open New Workbook To Variable
- Open Workbook Syntax
- Open Workbook Read-Only
- Open Password Protected Workbook
- Open Workbook Syntax Notes
- Close a Workbook in VBA
- Close Specific Workbook
- Close Active Workbook
- Close All Open Workbooks
- Close First Opened Workbook
- Close Without Saving
- Save and Close Without Prompt
- Other Workbook Open Examples
- Open Multiple New Workbooks
- Open All Excel Workbooks in a Folder
- Check if a Workbook is Open
- Workbook_Open Event
- Open Other Types of Files in VBA
- Open a Text file and Read its Contents
- Open a Text File and Append to it
- Opening a Word File and Writing to it
In this tutorial, you will learn how to use VBA to open and close Excel Workbooks and other types of Files in several ways.
VBA allows you to open or close files using the standard methods .Open and .Close.
If you want to learn how to check if a file exists before attempting to open the file, you can click on this link: VBA File Exists
Open a Workbook in VBA
Open Workbook From Path
If you know which file you want to open, you can specify its full path name in the function. Here is the code:
Workbooks.Open "C:VBA FolderSample file 1.xlsx"
This line of the code opens “Sample file 1” file from the “VBA Folder”.
Open Workbook – ActiveWorkbook
When you open a workbook, it automatically becomes the ActiveWorkbook. You can reference the newly opened workbook like so:
ActiveWorkbook.Save
When you reference a sheet or range and omit the workbook name, VBA will assume you are referring to the ActiveWorkbook:
Sheets("Sheet1").Name = "Input"
Open Workbook and Assign to a Variable
You can also open a workbook and assign it directly to an object variable. This procedure will open a workbook to the wb variable and then save the workbook.
Sub OpenWorkbookToVariable()
Dim wb As Workbook
Set wb = Workbooks.Open("C:VBA FolderSample file 1.xlsx")
wb.Save
End Sub
Assigning workbooks to variables when they open is the best way to keep track of your workbooks
Workbook Open File Dialog
You can also trigger the workbook Open File Dialog box. This allows the user to navigate to a file and open it:
Sub OpenWorkbook ()
Dim strFile As String
strFile = Application.GetOpenFilename()
Workbooks.Open (strFile)
End Sub
As you can see in Image 1, with this approach users can choose which file to open. The Open File Dialog Box can be heavily customized. You can default to a certain folder, choose which types of files are visible (ex. .xlsx only), and more. Read our tutorial on the Open File Dialog Box for detailed examples.
Open New Workbook
This line of code will open a new workbook:
Workbooks.Add
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 New Workbook To Variable
This procedure will open a new workbook, assigning it to variable wb:
Sub OpenNewWorkbook()
Dim wb As Workbook
Set wb = Workbooks.Add
End Sub
Open Workbook Syntax
When you use Workbooks.Open you might notice that there are many options available when opening the workbook:
The Filename is required. All other arguments are optional – and you probably won’t need to know most of the other arguments. Here are the two most common:
Open Workbook Read-Only
When workbook is opened read-only, you can’t save over the original file. This prevents the file from being edited by the user.
Workbooks.Open "C:VBA FolderSample file 1.xlsx", , True
VBA Programming | Code Generator does work for you!
Open Password Protected Workbook
A workbook might be password-protected. Use this code to open the password-protected workbook:
Workbooks.Open "C:VBA FolderSample file 1.xlsx", , , "password"
Open Workbook Syntax Notes
Notice that in the image above, we included a parenthesis “(” to show the syntax. If you use parenthesis when working with Workbooks.Open, you must assign the workbook to a variable:
Sub OpenWB()
Dim wb As Workbook
Set wb = Workbooks.Open("C:VBA FolderSample file 1.xlsx", True, True)
End Sub
Close a Workbook in VBA
Close Specific Workbook
Similarly to opening a workbook, there are several ways to close a file. If you know which file you want to close, you can use the following code:
Workbooks.Close ("C:VBA FolderSample file 1.xlsx")
This line of code closes the file “Sample file 1” if it’s opened. If not, it will return an error, so you should take care of error handling.
Close Active Workbook
If you want to close the Workbook which is currently active, this line of code will enable you to do that:
ActiveWorkbook.Close
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Close All Open Workbooks
To close all open Workbooks, you can simply use this code:
Workbooks.Close
Close First Opened Workbook
This will close the first opened/created workbook:
Workbooks(1).Close
Replace 1 with 2 to close the second opened / created workbook and so on.
Close Without Saving
This will close a Workbook without saving and without showing the save prompt:
ActiveWorkbook.Close savechanges:=False
Save and Close Without Prompt
Similarly this will save and close a Workbook without showing the save prompt:
ActiveWorkbook.Close savechanges:=True
Note: There are several other ways to indicate whether to save or not save a Workbook and also whether to show prompts or not. This is discussed in more detail here.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Other Workbook Open Examples
Open Multiple New Workbooks
This procedure will open multiple new workbooks, assigning the new workbooks to an array:
Sub OpenMultipleNewWorkbooks()
Dim arrWb(3) As Workbook
Dim i As Integer
For i = 1 To 3
Set arrWb(i) = Workbooks.Add
Next i
End Sub
Open All Excel Workbooks in a Folder
This procedure will open all Excel Workbooks in a folder, using the Open File Dialog picker.
Sub OpenMultipleWorkbooksInFolder()
Dim wb As Workbook
Dim dlgFD As FileDialog
Dim strFolder As String
Dim strFileName As String
Set dlgFD = Application.FileDialog(msoFileDialogFolderPicker)
If dlgFD.Show = -1 Then
strFolder = dlgFD.SelectedItems(1) & Application.PathSeparator
strFileName = Dir(strFolder & "*.xls*")
Do While strFileName <> ""
Set wb = Workbooks.Open(strFolder & strFileName)
strFileName = Dir
Loop
End If
End Sub
Check if a Workbook is Open
This procedure will test if a workbook is open:
Sub TestByWorkbookName()
Dim wb As Workbook
For Each wb In Workbooks
If wb.Name = "New Microsoft Excel Worksheet.xls" Then
MsgBox "Found it"
Exit Sub 'call code here, we'll just exit for now
End If
Next
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook_Open Event
VBA Events are “triggers” that tell VBA to run certain code. You can set up workbook events for open, close, before save, after save and more.
Read our Workbook_Open Event tutorial to learn more about automatically running macros when a workbook is opened.
Open Other Types of Files in VBA
You can use the VBA to open other types of files with VBA – such as txt or Word files.
Open a Text file and Read its Contents
The VBA open method allows you to read or write to the file once you have opened it. To read the contents of a file, we can open the file for INPUT.
Sub OpenTextFile()
Dim strFile As String
Dim strBody As String
Dim intFile As Integer
strFile = "C:datatest.txt"
intFile = FreeFile
Open strFile For Input As intFile
strBody = Input(LOF(intFile), intFile)
'loop here through your text body and extract what you need
''some vba code here
Debug.Print strBody
Close intFile
End Sub
The code above will open the text file “test.txt” and then it will read the entire contents of the file to the strBody variable. Once you have extracted the file data into the strBody variable, you can use it for what you require. Using the Debug.Print command above enables us to see the contents of the strBody variable in the Immediate window in the VBE.
Open a Text File and Append to it
We can also open a text file in VBA, and then append to the bottom of the file using the Append method.
Sub AppendToTextFile()
Dim strFile As String
Dim strBody As String
Dim intFile As Integer
strFile = "C:datatest.txt"
intFile = FreeFile
Open strFile For Append As intFile
'add two lines to the bottom
Print #intFile, "This is an extra line of text at the bottom"
Print #intFile, "and this is another one"
'close the file
Close intFile
End Sub
The above code will open the text file and then append 2 lines of text to the bottom of the file using the #intFile variable (the # sign is the key!). The code then closes the file.
Opening a Word File and Writing to it
We can also use VBA in Excel to open a Word file.
Sub OpenWordFile()
Dim wApp As Object
Dim wDoc As Object
Set wApp = CreateObject("Word.Application")
Set wd = wApp.documents.Open("c:datatest.docx")
wApp.Visible = True
End Sub
This code will open a copy of Word, and then open the document test.docx.
In this tutorial, I will cover the how to work with workbooks in Excel using VBA.
In Excel, a ‘Workbook’ is an object that is a part of the ‘Workbooks’ collection. Within a workbook, you have different objects such as worksheets, chart sheets, cells and ranges, chart objects, shapes, etc.
With VBA, you can do a lot of stuff with a workbook object – such as open a specific workbook, save and close workbooks, create new workbooks, change the workbook properties, etc.
So let’s get started.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
Referencing a Workbook using VBA
There are different ways to refer to a Workbook object in VBA.
The method you choose would depend on what you want to get done.
In this section, I will cover the different ways to refer to a workbook along with some example codes.
Using Workbook Names
If you have the exact name of the workbook that you want to refer to, you can use the name in the code.
Let’s begin with a simple example.
If you have two workbooks open, and you want to activate the workbook with the name – Examples.xlsx, you can use the below code:
Sub ActivateWorkbook() Workbooks("Examples.xlsx").Activate End Sub
Note that you need to use the file name along with the extension if the file has been saved. If it hasn’t been saved, then you can use the name without the file extension.
If you’re not sure what name to use, take help from the Project Explorer.
If you want to activate a workbook and select a specific cell in a worksheet in that workbook, you need to give the entire address of the cell (including the Workbook and the Worksheet name).
Sub ActivateWorkbook() Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate Range("A1").Select End Sub
The above code first activates Sheet1 in the Examples.xlsx workbook and then selects cell A1 in the sheet.
You will often see a code where a reference to a worksheet or a cell/range is made without referring to the workbook. This happens when you’re referring to the worksheet/ranges in the same workbook that has the code in it and is also the active workbook. However, in some cases, you do need to specify the workbook to make sure the code works (more on this in the ThisWorkbook section).
Using Index Numbers
You can also refer to the workbooks based on their index number.
For example, if you have three workbooks open, the following code would show you the names of the three workbooks in a message box (one at a time).
Sub WorkbookName() MsgBox Workbooks(1).Name MsgBox Workbooks(2).Name MsgBox Workbooks(3).Name End Sub
The above code uses MsgBox – which is a function that shows a message box with the specified text/value (which is the workbook name in this case).
One of the troubles I often have with using index numbers with Workbooks is that you never know which one is the first workbook and which one is the second and so on. To be sure, you would have to run the code as shown above or something similar to loop through the open workbooks and know their index number.
Excel treats the workbook opened first to have the index number as 1, and the next one as 2 and so on.
Despite this drawback, using index numbers can come in handy.
For example, if you want to loop through all the open workbooks and save all, you can use the index numbers.
In this case, since you want this to happen to all the workbooks, you’re not concerned about their individual index numbers.
The below code would loop through all the open workbooks and close all except the workbook that has this VBA code.
Sub CloseWorkbooks() Dim WbCount As Integer WbCount = Workbooks.Count For i = WbCount To 1 Step -1 If Workbooks(i).Name <> ThisWorkbook.Name Then Workbooks(i).Close End If Next i End Sub
The above code counts the number of open workbooks and then goes through all the workbooks using the For Each loop.
It uses the IF condition to check if the name of the workbook is the same as that of the workbook where the code is being run.
If it’s not a match, it closes the workbook and moves to the next one.
Note that we have run the loop from WbCount to 1 with a Step of -1. This is done as with each loop, the number of open workbooks is decreasing.
ThisWorkbook is covered in detail in the later section.
Also read: How to Open Excel Files Using VBA (Examples)
Using ActiveWorkbook
ActiveWorkbook, as the name suggests, refers to the workbook that is active.
The below code would show you the name of the active workbook.
Sub ActiveWorkbookName() MsgBox ActiveWorkbook.Name End Sub
When you use VBA to activate another workbook, the ActiveWorkbook part in the VBA after that would start referring to the activated workbook.
Here is an example of this.
If you have a workbook active and you insert the following code into it and run it, it would first show the name of the workbook that has the code and then the name of Examples.xlsx (which gets activated by the code).
Sub ActiveWorkbookName() MsgBox ActiveWorkbook.Name Workbooks("Examples.xlsx").Activate MsgBox ActiveWorkbook.Name End Sub
Note that when you create a new workbook using VBA, that newly created workbook automatically becomes the active workbook.
Using ThisWorkbook
ThisWorkbook refers to the workbook where the code is being executed.
Every workbook would have a ThisWorkbook object as a part of it (visible in the Project Explorer).
‘ThisWorkbook’ can store regular macros (similar to the ones that we add-in modules) as well as event procedures. An event procedure is something that is triggered based on an event – such as double-clicking on a cell, or saving a workbook or activating a worksheet.
Any event procedure that you save in this ‘ThisWorkbook’ would be available in the entire workbook, as compared to the sheet level events which are restricted to the specific sheets only.
For example, if you double-click on the ThisWorkbook object in the Project Explorer and copy-paste the below code in it, it will show the cell address whenever you double-click on any of the cells in the entire workbook.
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) MsgBox Target.Address End Sub
While ThisWorkbook’s main role is to store event procedure, you can also use it to refer to the workbook where the code is being executed.
The below code would return the name of the workbook in which the code is being executed.
Sub ThisWorkbookName() MsgBox ThisWorkbook.Name End Sub
The benefit of using ThisWorkbook (over ActiveWorkbook) is that it would refer to the same workbook (the one that has the code in it) in all the cases. So if you use a VBA code to add a new workbook, the ActiveWorkbook would change, but ThisWorkbook would still refer to the one that has the code.
Creating a New Workbook Object
The following code will create a new workbook.
Sub CreateNewWorkbook() Workbooks.Add End Sub
When you add a new workbook, it becomes the active workbook.
The following code will add a new workbook and then show you the name of that workbook (which would be the default Book1 type name).
Sub CreateNewWorkbook() Workbooks.Add MsgBox ActiveWorkbook.Name End Sub
Open a Workbook using VBA
You can use VBA to open a specific workbook when you know the file path of the workbook.
The below code will open the workbook – Examples.xlsx which is in the Documents folder on my system.
Sub OpenWorkbook() Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx") End Sub
In case the file exists in the default folder, which is the folder where VBA saves new files by default, then you can just specify the workbook name – without the entire path.
Sub OpenWorkbook() Workbooks.Open ("Examples.xlsx") End Sub
In case the workbook that you’re trying to open doesn’t exist, you’ll see an error.
To avoid this error, you can add a few lines to your code to first check whether the file exists or not and if it exists then try to open it.
The below code would check the file location and if it doesn’t exist, it will show a custom message (not the error message):
Sub OpenWorkbook()
If Dir("C:UserssumitDocumentsExamples.xlsx") <> "" Then
Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx")
Else
MsgBox "The file doesn't exist"
End If
End Sub
You can also use the Open dialog box to select the file that you want to open.
Sub OpenWorkbook()
If Dir("C:UserssumitDocumentsExamples.xlsx") <> "" Then
Workbooks.Open ("C:UserssumitDocumentsExamples.xlsx")
Else
MsgBox "The file doesn't exist"
End If
End Sub
The above code opens the Open dialog box. When you select a file that you want to open, it assigns the file path to the FilePath variable. Workbooks.Open then uses the file path to open the file.
In case the user doesn’t open a file and clicks on Cancel button, FilePath becomes False. To avoid getting an error in this case, we have used the ‘On Error Resume Next’ statement.
Saving a Workbook
To save the active workbook, use the code below:
Sub SaveWorkbook() ActiveWorkbook.Save End Sub
This code works for the workbooks that have already been saved earlier. Also, since the workbook contains the above macro, if it hasn’t been saved as a .xlsm (or .xls) file, you will lose the macro when you open it next.
If you’re saving the workbook for the first time, it will show you a prompt as shown below:
When saving for the first time, it’s better to use the ‘Saveas’ option.
The below code would save the active workbook as a .xlsm file in the default location (which is the document folder in my system).
Sub SaveWorkbook() ActiveWorkbook.SaveAs Filename:="Test.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
If you want the file to be saved in a specific location, you need to mention that in the Filename value. The below code saves the file on my desktop.
Sub SaveWorkbook() ActiveWorkbook.SaveAs Filename:="C:UserssumitDesktopTest.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
If you want the user to get the option to select the location to save the file, you can use call the Saveas dialog box. The below code shows the Saveas dialog box and allows the user to select the location where the file should be saved.
Sub SaveWorkbook() Dim FilePath As String FilePath = Application.GetSaveAsFilename ActiveWorkbook.SaveAs Filename:=FilePath & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled End Sub
Note that instead of using FileFormat:=xlOpenXMLWorkbookMacroEnabled, you can also use FileFormat:=52, where 52 is the code xlOpenXMLWorkbookMacroEnabled.
Saving All Open Workbooks
If you have more than one workbook open and you want to save all the workbooks, you can use the code below:
Sub SaveAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks wb.Save Next wb End Sub
The above saves all the workbooks, including the ones that have never been saved. The workbooks that have not been saved previously would get saved in the default location.
If you only want to save those workbooks that have previously been saved, you can use the below code:
Sub SaveAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Path <> "" Then wb.Save End If Next wb End Sub
Saving and Closing All Workbooks
If you want to close all the workbooks, except the workbook that has the current code in it, you can use the code below:
Sub CloseandSaveWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Name <> ThisWorkbook.Name Then wb.Close SaveChanges:=True End If Next wb End Sub
The above code would close all the workbooks (except the workbook that has the code – ThisWorkbook). In case there are changes in these workbooks, the changes would be saved. In case there is a workbook that has never been saved, it will show the save as dialog box.
Save a Copy of the Workbook (with Timestamp)
When I am working with complex data and dashboard in Excel workbooks, I often create different versions of my workbooks. This is helpful in case something goes wrong with my current workbook. I would at least have a copy of it saved with a different name (and I would only lose the work I did after creating a copy).
Here is the VBA code that will create a copy of your workbook and save it in the specified location.
Sub CreateaCopyofWorkbook() ThisWorkbook.SaveCopyAs Filename:="C:UserssumitDesktopBackupCopy.xlsm" End Sub
The above code would save a copy of your workbook every time you run this macro.
While this works great, I would feel more comfortable if I had different copies saved whenever I run this code. The reason this is important is that if I make an inadvertent mistake and run this macro, it will save the work with the mistakes. And I wouldn’t have access to the work before I made the mistake.
To handle such situations, you can use the below code that saves a new copy of the work each time you save it. And it also adds a date and timestamp as a part of the workbook name. This can help you track any mistake you did as you never lose any of the previously created backups.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) ThisWorkbook.SaveCopyAs Filename:="C:UserssumitDesktopBackupCopy" & Format(Now(), "dd-mm-yy-hh-mm-ss-AMPM") & ".xlsm" End Sub
The above code would create a copy every time you run this macro and add a date/time stamp to the workbook name.
Create a New Workbook for Each Worksheet
In some cases, you may have a workbook that has multiple worksheets, and you want to create a workbook for each worksheet.
This could be the case when you have monthly/quarterly reports in a single workbook and you want to split these into one workbook for each worksheet.
Or, if you have department wise reports and you want to split these into individual workbooks so that you can send these individual workbooks to the department heads.
Here is the code that will create a workbook for each worksheet, give it the same name as that of the worksheet, and save it in the specified folder.
Sub CreateWorkbookforWorksheets() Dim ws As Worksheet Dim wb As Workbook For Each ws In ThisWorkbook.Worksheets Set wb = Workbooks.Add ws.Copy Before:=wb.Sheets(1) Application.DisplayAlerts = False wb.Sheets(2).Delete Application.DisplayAlerts = True wb.SaveAs "C:UserssumitDesktopTest" & ws.Name & ".xlsx" wb.Close Next ws End Sub
In the above code, we have used two variable ‘ws’ and ‘wb’.
The code goes through each worksheet (using the For Each Next loop) and creates a workbook for it. It also uses the copy method of the worksheet object to create a copy of the worksheet in the new workbook.
Note that I have used the SET statement to assign the ‘wb’ variable to any new workbook that is created by the code.
You can use this technique to assign a workbook object to a variable. This is covered in the next section.
Assign Workbook Object to a Variable
In VBA, you can assign an object to a variable, and then use the variable to refer to that object.
For example, in the below code, I use VBA to add a new workbook and then assign that workbook to the variable wb. To do this, I need to use the SET statement.
Once I have assigned the workbook to the variable, all the properties of the workbook are made available to the variable as well.
Sub AssigntoVariable() Dim wb As Workbook Set wb = Workbooks.Add wb.SaveAs Filename:="C:UserssumitDesktopExamples.xlsx" End Sub
Note that the first step in the code is to declare ‘wb’ as a workbook type variable. This tells VBA that this variable can hold the workbook object.
The next statement uses SET to assign the variable to the new workbook that we are adding. Once this assignment is done, we can use the wb variable to save the workbook (or do anything else with it).
Looping through Open Workbooks
We have already seen a few examples codes above that used looping in the code.
In this section, I will explain different ways to loop through open workbooks using VBA.
Suppose you want to save and close all the open workbooks, except the one with the code in it, then you can use the below code:
Sub CloseandSaveWorkbooks() Dim wb As Workbook For Each wb In Workbooks If wb.Name <> ThisWorkbook.Name Then wb.Close SaveChanges:=True End If Next wb End Sub
The above code uses the For Each loop to go through each workbook in the Workbooks collection. To do this, we first need to declare ‘wb’ as the workbook type variable.
In every loop cycle, each workbook name is analyzed and if it doesn’t match the name of the workbook that has the code, it’s closed after saving its content.
The same can also be achieved with a different loop as shown below:
Sub CloseWorkbooks() Dim WbCount As Integer WbCount = Workbooks.Count For i = WbCount To 1 Step -1 If Workbooks(i).Name <> ThisWorkbook.Name Then Workbooks(i).Close SaveChanges:=True End If Next i End Sub
The above code uses the For Next loop to close all the workbooks except the one that has the code in it. In this case, we don’t need to declare a workbook variable, but instead, we need to count the total number of open workbooks. When we have the count, we use the For Next loop to go through each workbook. Also, we use the index number to refer to the workbooks in this case.
Note that in the above code, we are looping from WbCount to 1 with Step -1. This is needed as with each loop, the workbook gets closed and the number of workbooks gets decreased by 1.
Error while Working with the Workbook Object (Run-time error ‘9’)
One of the most common error you may encounter when working with workbooks is – Run-time Error ‘9’ – Subscript out of range.
Generally, VBA errors are not very informative and often leave it to you to figure out what went wrong.
Here are some of the possible reasons that may lead to this error:
- The workbook that you’re trying to access does not exist. For example, if I am trying to access the fifth workbook using Workbooks(5), and there are only 4 workbooks open, then I will get this error.
- If you’re using a wrong name to refer to the workbook. For example, if your workbook name is Examples.xlsx and you use Example.xlsx. then it will show you this error.
- If you haven’t saved a workbook, and you use the extension, then you get this error. For example, if your workbook name is Book1, and you use the name Book1.xlsx without saving it, you will get this error.
- The workbook you’re trying to access is closed.
Get a List of All Open Workbooks
If you want to get a list of all the open workbooks in the current workbook (the workbook where you’re running the code), you can use the below code:
Sub GetWorkbookNames() Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range("A1").Activate For i = 1 To wbcount Range("A1").Offset(i - 1, 0).Value = Workbooks(i).Name Next i End Sub
The above code adds a new worksheet and then lists the name of all the open workbooks.
If you want to get their file path as well, you can use the below code:
Sub GetWorkbookNames() Dim wbcount As Integer wbcount = Workbooks.Count ThisWorkbook.Worksheets.Add ActiveSheet.Range("A1").Activate For i = 1 To wbcount Range("A1").Offset(i - 1, 0).Value = Workbooks(i).Path & "" & Workbooks(i).Name Next i End Sub
Open the Specified Workbook by Double-clicking on the Cell
If you have a list of file paths for Excel workbooks, you can use the below code to simply double-click on the cell with the file path and it will open that workbook.
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Workbooks.Open Target.Value End Sub
This code would be placed in the ThisWorkbook code window.
To do this:
- Double click on the ThisWorkbook object in the project explorer. Note that the ThisWorkbook object should be in the workbook where you want this functionality.
- Copy and paste the above code.
Now, if you have the exact path of the files that you want to open, you can do that by simply double-clicking on the file path and VBA would instantly open that workbook.
Where to Put the VBA Code
Wondering where the VBA code goes in your Excel workbook?
Excel has a VBA backend called the VBA editor. You need to copy and paste the code into the VB Editor module code window.
Here are the steps to do this:
- Go to the Developer tab.
- Click on the Visual Basic option. This will open the VB editor in the backend.
- In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
You May Also Like the Following Excel VBA Tutorials:
- How to Record a Macro in Excel.
- Creating a User Defined Function in Excel.
- How to Create and Use Add-in in Excel.
- How to Resue Macros by placing it in the Personal Macro Workbook.
- Get the List of File Names from a Folder in Excel (with and without VBA).
- How to Use Excel VBA InStr Function (with practical EXAMPLES).
- How to Sort Data in Excel using VBA (A Step-by-Step Guide).
Home / VBA / VBA Close Workbook (Excel File)
To close an Excel file, you need to use the “Close” method. With this method you can, specify if you want to save the changes or not. And, if you want to save and close a file that is not saved yet you can specify the path where you want to save it before closing.
The following is the syntax for the close method.
Workbook.Close (SaveChanges, FileName, RouteWorkbook)
Steps to Close a Workbook
- Specify the workbook that you want to close.
- Use the close method with that workbook.
- In the code method, specify if you want to save the file or not.
- In the end, mention the location path where you want to save the file before closing.
In this tutorial, we will look at different ways that you can use to close a workbook in Excel using VBA.
Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook
Close a Workbook without Saving
If you want to save the active workbook without saving you need to use code like the following.
ActiveWorkbook.Close SaveChanges:=False
In this code, I have specified the “False” for the “SaveChanges” argument. So VBA will ignore if there are any changes in the workbook which are not saved. And if you want to close a specific workbook you can use the name of that workbook. Just like the following code.
Workbooks("book1").Close SaveChanges:=False
If you have data in the workbook and you skip the “SaveChanges” argument, then Excel will show a dialog box to confirm if you want to save the workbook or not. The point is: It is better to specify the “SaveChanges” argument even if it’s optional.
Close a Workbook after Saving
As you have seen, there’s an argument in the CLOSE method to specify the path location. Let’s say if you wish to save the “Book6” to the folder on the desktop. Here’s the code that you need to use.
Workbooks("Book6").Close _
SaveChanges:=True, _
Filename:="C:UsersDellDesktopmyFoldermyFile.xlsx"
This code is going to save the workbook “Book6” into the folder that is saved on my desktop with the name “myFIle.xlsx”. But here’s one thing that you need to take care of: IF you already have a workbook with the same name then it will replace that file with the new one.
Don’t worry, there’s a solution that you can use. The following code checks if there’s any file exists with the name that you want to use
Sub vba_close_workbook()
Dim wbCheck As String
wbCheck = Dir("C:UsersDellDesktopmyFoldermyFile.xlsx")
If wbCheck = "" Then
Workbooks("Book6").Close _
SaveChanges:=True, _
Filename:="C:UsersDellDesktopmyFoldermyFile.xlsx"
Else
MsgBox "Error! Name already used."
End If
End Sub
More on VBA Workbooks
VBA Save Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)
- VBA Workbook
This tutorial shows how to close all open excel workbooks except the active workbook at once using VBA
METHOD 1. Close all Excel workbooks except the active workbook at once using VBA
VBA
Sub Close_all_excel_files_except_active_file()
Dim wb As Workbook
For Each wb In Application.Workbooks
If Not (wb Is Application.ActiveWorkbook) Then
wb.Close
End If
Next
End Sub
NOTES
Note 1: This VBA code will close all the open excel files except for the active excel file at once.
Related Topic | Description | Related Topic and Description |
---|---|---|
Close an Excel workbook | How to close a single workbook | |
Save an Excel workbook | How to save an Excel workbook |
Эти макросы помогут вам закрыть все открытые файлы Excel, оставив лишь текущий файл.
Выбирайте любой из них — они мало чем отличаются.
Первый оставляет открытой только активную книгу, независимо от того, из какого файла запущен этот макрос:
Sub CloseAllWorkbooks1() ' закрываем все книги, кроме текущей (активной) Dim wb As Workbook: Application.ScreenUpdating = False For Each wb In Workbooks ' перебираем все открытые книги If Not wb Is ActiveWorkbook Then ' если это не этот файл If wb.Windows(1).Visible Then wb.Close ' закрываем его End If Next wb End Sub
Второй макрос оставляет открытой только ту книгу, из которой запущен этот самый макрос, независимо от того, какая книга активна на момент запуска:
Sub CloseAllWorkbooks2() ' закрываем все книги, кроме той, из которой запущен макрос Dim wb As Workbook: Application.ScreenUpdating = False For Each wb In Workbooks ' перебираем все открытые книги If Not wb Is ThisWorkbook Then If wb.Windows(1).Visible Then wb.Close Next wb End Sub
Третья версия макроса отличается от первой лишь тем, что все файлы закрываются с сохранением изменений:
(первый макрос в этом случае выдаёт диалоговое окно — сохранять файл, или нет)
Sub CloseAllWorkbooks3() ' закрываем все книги, кроме текущей (активной), С СОХРАНЕНИЕМ изменений Dim wb As Workbook: Application.ScreenUpdating = False For Each wb In Workbooks ' перебираем все открытые книги If wb.Windows(1).Visible = True And (Not wb Is ActiveWorkbook) Then ' закрываем с сохранением только изменённые файлы wb.Close (Not wb.Saved) ' ранее сохранённые файлы просто закрываются End If Next wb End Sub
Ну и четвертый вариант — тоже закрывает все открытые файлы, только изменения в этих файлах не сохраняются:
Sub CloseAllWorkbooks4() ' закрываем все книги, кроме текущей (активной), БЕЗ СОХРАНЕНИЯ изменений Dim wb As Workbook: Application.ScreenUpdating = False For Each wb In Workbooks ' перебираем все открытые книги If wb.Windows(1).Visible Then If Not wb Is ActiveWorkbook Then wb.Close False Next wb End Sub
I know this is an old post but for those who visit here from searches may find it helpful.
This code was found and modified. It will give you every SHEET in every WORKBOOK in every INSTANCE. From there you can determine the active instance.
Module…………..
Declare Function FindWindowEx Lib "User32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Declare Function GetClassName Lib "User32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Declare Function IIDFromString Lib "ole32" (ByVal lpsz As Long, ByRef lpiid As UUID) As Long
Declare Function AccessibleObjectFromWindow Lib "oleacc" (ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As UUID, ByRef ppvObject As Object) As Long
Type UUID 'GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Code……………………
Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}"
Const OBJID_NATIVEOM As Long = &HFFFFFFF0
Sub ListAll()
Dim I As Integer
Dim hWndMain As Long
On Error GoTo MyErrorHandler
hWndMain = FindWindowEx(0&, 0&, "XLMAIN", vbNullString)
I = 1
Do While hWndMain <> 0
Debug.Print "Excel Instance " & I
GetWbkWindows hWndMain
hWndMain = FindWindowEx(0&, hWndMain, "XLMAIN", vbNullString)
I = I + 1
Loop
Exit Sub
MyErrorHandler:
MsgBox "GetAllWorkbookWindowNames" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
End Sub
Sub GetWbkWindows(ByVal hWndMain As Long)
Dim hWndDesk As Long
Dim hWnd As Long
Dim strText As String
Dim lngRet As Long
On Error GoTo MyErrorHandler
hWndDesk = FindWindowEx(hWndMain, 0&, "XLDESK", vbNullString)
If hWndDesk <> 0 Then
hWnd = FindWindowEx(hWndDesk, 0, vbNullString, vbNullString)
Do While hWnd <> 0
strText = String$(100, Chr$(0))
lngRet = GetClassName(hWnd, strText, 100)
If Left$(strText, lngRet) = "EXCEL7" Then
GetExcelObjectFromHwnd hWnd
Exit Sub
End If
hWnd = FindWindowEx(hWndDesk, hWnd, vbNullString, vbNullString)
Loop
On Error Resume Next
End If
Exit Sub
MyErrorHandler:
MsgBox "GetWbkWindows" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
End Sub
Function GetExcelObjectFromHwnd(ByVal hWnd As Long) As Boolean
Dim fOk As Boolean
Dim I As Integer
Dim obj As Object
Dim iid As UUID
Dim objApp As Excel.Application
Dim myWorksheet As Worksheet
On Error GoTo MyErrorHandler
fOk = False
Call IIDFromString(StrPtr(IID_IDispatch), iid)
If AccessibleObjectFromWindow(hWnd, OBJID_NATIVEOM, iid, obj) = 0 Then 'S_OK
Set objApp = obj.Application
For I = 1 To objApp.Workbooks.Count
Debug.Print " " & objApp.Workbooks(I).Name
For Each myWorksheet In objApp.Workbooks(I).Worksheets
Debug.Print " " & myWorksheet.Name
DoEvents
Next
fOk = True
Next I
End If
GetExcelObjectFromHwnd = fOk
Exit Function
MyErrorHandler:
MsgBox "GetExcelObjectFromHwnd" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
End Function
I hope this helps someone
on
March 8, 2022, 2:47 PM PST
How to create a VBA procedure that closes all open workbooks in Excel
This simple procedure can save you a lot of time when you’re finished with your work. Susan Harkins tells you how.
Some of us work with several Microsoft Excel workbooks open at the same time. Either we open them and work a while and move on to the next, or they have a link or connection that requires that they all be open at the same time. Regardless of how you end up with lots of open workbooks, closing them all manually, one by one, can be tedious.
The good news is that you can use a VBA procedure to shut them all instead. In this article, I’ll show you a simple procedure that saves each workbook, if necessary, before closing it and then moves on to the next workbook, eventually saving and closing them all.
SEE: 83 Excel tips every user should master (TechRepublic)
I’m using Microsoft 365 on a Windows 10 64-bit system. (I recommend that you wait to upgrade to Windows 11 until all the kinks have been worked out.) You can download the .bas file, which contains the procedure, and import the file into your Personal.xlsb workbook. Excel Online doesn’t support VBA.
Where the procedure goes
The first thing to get out of the way is this: You can’t store this procedure in just any workbook. If it’s the last workbook open, the procedure will close it first and stop. This is the type of procedure that belongs in your personal workbook. This workbook, named Personal.xlsb opens every time you open Excel and is hidden by default. All procedures in Personal.xlsb are available to all open workbooks. It’s a library of sorts.
Open the Visual Basic Editor (VBE) by pressing Alt + F11. If the Project Window to the left isn’t visible, press Ctrl + R or choose Project Explorer from the View menu. If Personal.xlsb is in the Project Explorer, expand it and double-click Module1 to open its code window.
If Personal.xlsb isn’t in the Project Window, you need to record a short procedure as follows:
-
- Return to the worksheet and click the Developer tab.
- In the Macros group, click Record Macro.
- In the resulting dialog, you only need to choose where the procedure will be stored. From the Store Macro In dropdown, choose Personal Macro Workbook (Figure A).
- Click OK
- Click Stop Recording in the Macros group on the Developer tab.
Return to the VBE and you’ll find Personal.xlsb in the Project Window, as shown in Figure B. Double-click Module1 to open its code sheet and delete the procedure you just created. You don’t need this procedure; its only purpose was to unhide Personal.xlsb.
Figure A
Choose where to store the procedure. Figure B
Now Personal.xlsb is available. With an open code sheet for Personal.xlsb, you’re ready to add the code shown in Listing A. It really is as simple as it looks (Figure C). If you are using a ribbon version, be sure to save the workbook as a macro-enabled file. If you’re working in the menu version, you can skip this step.
Listing A
Sub CloseWorkbooks()
'Save and close all open workbooks.
Dim wb As Workbook
'Turns off screen.
Application.ScreenUpdating = False
'Cycles through open workbooks and closes them.
For Each wb In Workbooks
Debug.Print wb.Name
If wb.Name <> "PERSONAL.XLSB" Then
wb.Close SaveChanges:=True
End If
Next wb
'Turns on screen.
Application.ScreenUpdating = True
'Closes Excel.
Application.Quit
End Sub
Figure C
Enter CloseWorkbooks() into Personal.xlsb’ Module 1 code sheet. The procedure is in the downloadable .bas files, which you can import into the Personal.xlsb file’s Module 1. If you enter the code manually, don’t paste from this web page. Instead, copy the code into a text editor and then paste that code into the Personal.xlsb module. Doing so will remove any phantom web characters that might otherwise cause errors.
Once you have the procedure in Personal.xlsb, you can run it from any workbook.
About the procedure
This procedure first declares a Workbook object variable as wb and turns off screen updating so you won’t actually see files closing. The For Each statement cycles through all the open workbook objects and closes them, using the =True value to save each workbook before closing, unless the current workbook is Personal.xlsb. In that case, VBA skips this step and continues with the next workbook. The code must skip the Personal.xlsb workbook because if it closes, it also stops running, perhaps leaving workbooks open. Once all the workbooks are closed, the Application.Quit statement closes Excel. If you want to leave Excel open, you can comment out this statement.
If Excel is open, close it. Open a few Excel workbooks and from any open workbook, click the Developer tab and then click Macros in the Macros group. In the resulting dialog, shown in Figure D, select the CloseWorkbooks procedure and click Run. The procedure saves and closes each open workbook and then quits Excel.
Figure D
Choose the CloseWorkbooks() procedure to close all open workbooks. Most likely, you won’t want to work through all those steps to run this macro. I recommend that you add it to the Quick Access Toolbar (QAT) or a custom group. If you need help with that, read How to add Office macros to the QAT toolbar for quick access.
Also See
-
Get lifetime access to Microsoft Office 2021 for just $50
(TechRepublic Academy) -
How to use the many text wrapping options in Microsoft Word
(TechRepublic) -
Windows 11 cheat sheet: Everything you need to know
(TechRepublic) -
Checklist: Securing Windows 10 systems
(TechRepublic Premium) -
More must-read Microsoft coverage
(TechRepublic on Flipboard)
-
Microsoft
-
Software