Excel VBA lets you automate tasks like closing unused workbooks without manually dragging each one into a folder. The straightforward solution is to loop through all open workbooks and close those that aren’t the active one—ensuring only one remains open at a time. This is especially useful in scripts that need to manage multiple files during processing.

What You'll Need

  • A Microsoft Excel application with VBA enabled (enable it in Excel Options > Customize Ribbon > Main Tabs > Developer).
  • The ability to edit the Excel workbook’s Visual Basic Editor (press Alt+F11 to open it).
  • Basic understanding of VBA syntax (e.g., `Application` objects, `Workbooks` collection).
  • An existing Excel application running (tested directly on Excel 2016–2024).

Step-by-Step

  1. Open the Excel application and press Alt+F11 to launch the Visual Basic Editor. If prompted, allow the macro security setting to allow full trust or modify it as needed.
  2. In the Project Explorer pane on the left, double-click the ThisWorkbook item in the "Excel Objects" folder. This code will run whenever the workbook opens.
  3. Replace the existing code with this VBA snippet:
    
        Private Sub Workbook_Open()
            Dim wb As Workbook
            Dim i As Long
    
            ' Loop through all open workbooks
            For i = 1 To Application.Workbooks.Count
                Set wb = Application.Workbooks(i)
    
                ' Close all workbooks except the active one
                If wb.Name <> ActiveWorkbook.Name Then
                    wb.Close SaveChanges:=False
                End If
            Next i
        
  4. Close the Visual Basic Editor (press Ctrl+Z to undo the last step if needed). Now test the macro:
    1. Open multiple Excel files (e.g., 3–5 workbooks).
    2. Select one workbook to remain active and leave the others open.
    3. Manually trigger the macro by going to Developer > Macros and selecting Workbook_Open. Choose "Run."
    Only the active workbook should remain open. If others close unexpectedly, proceed to troubleshooting.

Common Mistakes

  • Closing the active workbook: The code checks `wb.Name <> ActiveWorkbook.Name`, so the active workbook is never closed. If it still closes, double-check that no other code in the same file or another macro is overriding this logic.
  • Permission errors: If Excel blocks the macro due to security settings, adjust the macro security level in File > Options > Trust Center > Trust Center Settings > Macro Settings to "Enable all macros (not recommended for production environments)."
  • Missing `Application` object: The `Application.Workbooks.Count` relies on the `Application` object. If the macro is placed elsewhere (e.g., `Module1`), add `Option Explicit` at the top and ensure the macro is assigned to `ThisWorkbook_Open` (not a standard module).
  • Windows task manager warnings: Excel may show the macro as "not responding" during execution. This is normal—press Alt+F4 to close the editor after the macro completes, or run it in a separate Excel session.

Tips

  • Protect the active workbook: If you’re editing the active workbook during automation, add a `If ActiveWorkbookProtected Then Application.Unprotect ActiveWorkbook.Name` check before the loop to avoid errors.
  • Test with a single file first: Open one workbook, manually trigger the macro, and verify it doesn’t close itself. Then add a second file to test loop behavior.
  • Debugging output: Insert a `Debug.Print` statement after `Set wb = Application.Workbooks(i)` to verify the loop iterates over all workbooks:
    
        Debug.Print "Closing workbook: " & wb.Name
        
    Check the Output window (View > Output Window) for errors.
  • Performance note: For large numbers of open workbooks (>100), consider optimizing by adding a timeout or using `Workbooks.OpenFilename` to load only specific files instead of iterating all open ones.
  • Alternative trigger: If you prefer not to bind the macro to `Workbook_Open`, replace `Private Sub Workbook_Open()` with a standard button macro in the Developer tab:
    1. Go to Developer > Insert > Button and add a button to the sheet.
    2. Double-click the button to open the macro editor.
    3. Paste the same loop code but assign it to the button’s macro.

Troubleshooting

  • Nothing happens:
    1. Ensure the macro is saved in the same workbook where you’re testing it. If placed in a separate module, bind it to `ThisWorkbook_Open`.
    2. Restart Excel and reopen the files. Temporary settings (e.g., macro options) may interfere.
    3. Check for conflicts: Run VBA’s built-in error handler by adding this before the loop:
      
            On Error Resume Next
            End Sub
            
      If you see an error, check the Output window for details.
  • Excel crashes or freezes:
    1. Try running the macro in a new Excel session (right-click the icon > New Workbook).
    2. Close all other Excel instances to avoid resource conflicts.
    3. Update Excel to the latest version (check Help > About Microsoft Excel).
  • Macro errors like "Run-time error '91': Object variable or With block variable not set":
    1. Add `Option Explicit` at the top of your module to enforce variable declarations.
    2. Ensure `Application.Workbooks(i)` is always assigned inside the loop (no `If` conditions that skip the assignment).

Frequently Asked Questions

What if I need to close the active workbook too?

Remove the `If wb.Name <> ActiveWorkbook.Name` condition from the loop. The code will now close all workbooks except the last one opened (since `Application.Workbooks.Count` returns workbooks in order of opening, not by active state).

Will this work in Excel Online?

No. Excel Online lacks VBA support, and macros are only available in desktop Excel (Windows/macOS). The process is identical in Excel for Mac.

How do I save the remaining workbooks before closing others?

Add `wb.Save` before `wb.Close SaveChanges:=False` to ensure the active workbook (and any others you want to save) remain intact:

wb.Save
wb.Close SaveChanges:=False

Why does my macro close half the workbooks?

This typically happens if:

  • The active workbook is one you opened recently, but another file (e.g., a template) is the "active" reference in the loop due to timing.
  • You’re testing in a session where other macros are running and closing files prematurely.

Solution: Use the `Debug.Print` tip above to inspect `wb.Name` in the Output window. Adjust the logic if needed (e.g., check file types or timestamps).

Can I make this macro run automatically at startup?

Yes, but only in the workbook where you placed the code. The `Workbook_Open` event triggers automatically when the file opens. For a global macro to run at Excel startup, use `ThisWorkbook_Startup` instead of `Workbook_Open`.

How do I undo the effect of this macro?

Close all open workbooks manually and reopen them. There’s no direct VBA undo, but you can log the names of closed files in a worksheet and reopen them later by pasting the list into `Workbooks.Open`.

This script is safe for personal use but avoid running it in shared workbooks to prevent unexpected deletions. Always test in a controlled environment first.