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.
Save and Close All Workbooks at Once
'---------------- Modules ---------------- 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.
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.
Most VBA code should be placed in Standard Modules unless specified.
If you see a comment
'------------------ Modules------------------ in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?
The following steps teach you how to put VBA code into a Standard Module:
- Activate the Visual Basic Editor by pressing ALT + F11.
- Right-click the project/workbook name in the Project Window.
- Choose Insert -> Module.
- Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
- Click Run button on the Visual Basic Editor toolbar.
- For more information, learn this course: Programming with Excel VBA