Sometimes you may need to save and close many workbooks at once. For each workbook you have opened, you need to activate the work, close it, and confirm save changes. There is no easy way to close them all down at one time. This little macro takes care of that annoyance.
Macro Code (VBA Code)
Sub SaveCloseAll() 'Step 1: Declare your variables Dim wb As Workbook 'Step 2: Loop through workbooks, save and close For Each wb In Workbooks wb.Close SaveChanges:=True Next wb End Sub
How This Macro Works
In this macro, the Workbooks collection loops through all the open workbooks. As the macro loops through each workbook, it saves and closes them down.
- Step 1 declares an object variable that represents a Workbook object. This allows us to enumerate through all the open workbooks, capturing their names as we go.
- Step 2 simply loops through the open workbooks, saving and closing them. If you don’t want to save them, change the SaveChanges argument from True to False.
How to Use This Macro
The best place to store this macro is in your Personal Macro Workbook. This way, the macro is always available to you. The Personal Macro Workbook is loaded whenever you start Excel. In the VBE Project window, it is named personal.xlsb.
- Activate the Visual Basic Editor by pressing
- Right-click personal.xlsb in the Project window.
- Choose Insert ➜ Module.
- Type or paste the code in the newly created module.
Don't see personal.xlsb in your project window?
If you don't see personal.xlsb in your project window, it doesn’t exist yet. You’ll have to record a macro, using Personal Macro Workbook as the destination.
To record the macro in your Personal Macro Workbook, select the Personal Macro Workbook option in the Record Macro dialog box before you start recording. This option is in the Store Macro In drop-down box.
Simply record a couple of cell clicks and then stop recording. You can discard the recorded macro and replace it with this one.