Excel VBA Workbook Before Close: How to Add Code
In this article
To run VBA code automatically before an Excel workbook closes, open the Visual Basic Editor (Alt+F11), double-click ThisWorkbook in the Project Explorer, choose Workbook from the left drop-down and BeforeClose from the right drop-down, then write your code inside the generated Private Sub Workbook_BeforeClose(Cancel As Boolean) procedure. That event fires every time the workbook is closed, whether by the user, by another macro, or when Excel shuts down. The Cancel parameter is the key to controlling the close: set Cancel = True to stop it, and set it back to False (or leave it alone) to let the close proceed.
What You'll Need
- Excel for Windows or Mac with macros enabled. The steps below use the standard Visual Basic Editor, which is the same on both platforms, though a few labels and shortcut keys can differ slightly by version, device or region.
- A workbook saved as .xlsm (macro-enabled) or .xlsb. A plain .xlsx file cannot store VBA code.
- Macro security set to allow macros. In Excel, go to File > Options > Trust Center > Trust Center Settings > Macro Settings and choose the setting your organisation permits. On Mac, look under Excel > Preferences > Security.
- Basic familiarity with the Visual Basic Editor: the Project Explorer, the Properties window, and how to insert a module.
Step-by-Step
- Enable the Developer tab. Go to File > Options > Customize Ribbon and tick Developer in the right-hand list. On Mac, go to Excel > Preferences > Ribbon & Toolbar and tick Developer. This gives you a button for Visual Basic and Macros, though the keyboard shortcut Alt+F11 works without it on Windows.
- Open the Visual Basic Editor. Press Alt+F11 (Windows) or Option+F11 (Mac), or click Developer > Visual Basic. A separate editor window opens.
- Find ThisWorkbook. In the Project Explorer pane (usually top-left; if hidden, press Ctrl+R), expand VBAProject (your workbook name) and double-click ThisWorkbook. Code placed here applies to that workbook only. Code in a standard module does not receive workbook events.
- Select the BeforeClose event. At the top of the code window are two drop-downs. Choose Workbook in the left one. In the right one, choose BeforeClose. The editor inserts an empty procedure named
Workbook_BeforeClosewith aCancel As Booleanargument. Do not rename it or change the argument, or the event will not fire. - Write the code you want to run. A typical starting point is a prompt that asks whether to save changes. For example:
This checks whether there are unsaved changes, offers Yes/No/Cancel, saves when Yes is chosen, and cancels the close when Cancel is chosen.Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim answer As VbMsgBoxResult If ThisWorkbook.Saved = False Then answer = MsgBox("Save changes before closing?", vbYesNoCancel + vbQuestion, "Close Workbook") Select Case answer Case vbYes ThisWorkbook.Save Case vbCancel Cancel = True End Select End If End Sub - Save the workbook as macro-enabled. Press Ctrl+S. If Excel warns that the file contains macros, choose Yes to keep the .xlsm format. Saving as .xlsx will strip the code.
- Test the event. Make a small edit so the workbook is dirty, then close it. Your prompt should appear. Choose each option in turn: Yes should save and close, No should close without saving, and Cancel should leave the workbook open.
- Add error handling for anything that touches other files or sheets. Wrap risky code in
On Error GoToand always resetCancelappropriately. If your code opens or writes another workbook, close that object and set it toNothingbefore the procedure ends, otherwise Excel may stay in memory after the window disappears. - Test with Excel's own close paths. Close via the window X, via File > Close, and by closing Excel entirely. The event should fire in all three cases. Also test with the workbook read-only and with shared workbooks, because some events behave differently there.
Common Mistakes
- Putting the code in a standard module. Only the ThisWorkbook code module receives workbook-level events. A procedure named
Workbook_BeforeClosein Module1 is just an ordinary macro and never runs automatically. - Renaming the procedure or changing its signature. The name and the
Cancel As Booleanargument must match exactly. Adding a second argument or changing the name breaks the link to the event. - Forgetting that
Cancelpersists. If you setCancel = Truein one branch and later decide to allow the close, you must set it back toFalse. Otherwise the workbook refuses to close with no visible reason. - Saving inside BeforeClose without checking
ThisWorkbook.Saved. Saving unconditionally can overwrite changes the user wanted to discard, and can trigger a second save prompt from Excel itself. - Assuming the event runs on a forced quit. If Excel is terminated by Task Manager, a crash, or a power loss, BeforeClose does not run. Do not rely on it for critical data logging; use it for prompts and light housekeeping.
- Leaving object references open. A workbook or range object that is not released can keep Excel running in the background after the window closes.
Tips
- Use
ThisWorkbook.Savedto detect unsaved changes. It isFalsewhen the workbook has been edited since the last save. - Keep BeforeClose code short and fast. Long loops or network calls make closing feel frozen and can trigger "Excel is not responding" messages.
- If you need to run cleanup on multiple workbooks, put the shared logic in a standard module and call it from each workbook's ThisWorkbook event.
- Use
Application.EnableEvents = Falsearound code that saves or closes other workbooks, then set it back toTrue, to avoid recursive event calls. - For testing, add a temporary
Debug.Printline at the top of the procedure and watch the Immediate Window (Ctrl+G) to confirm the event fires.
Troubleshooting
If the code does not run, first confirm the workbook is saved as .xlsm or .xlsb and that macros are enabled. Check that the procedure sits in ThisWorkbook and that its name is exactly Workbook_BeforeClose. If the workbook closes without any prompt, the event may be disabled: run Application.EnableEvents = True in the Immediate Window. If the workbook will not close at all, look for a path that sets Cancel = True without a way to reset it, and add a Cancel = False at the end of the procedure. If Excel remains in Task Manager after closing, check for unreleased object references and for a hidden instance created with CreateObject. If the prompt appears twice, you may have duplicate event code in both ThisWorkbook and a sheet module, or an add-in is also handling the event.
Frequently Asked Questions
Does Workbook_BeforeClose run when Excel itself is closed?
Yes, it runs when the workbook is closed as part of shutting down Excel, provided the close is a normal one. It does not run if Excel is terminated forcibly, crashes, or the machine loses power.
Can I stop a user from closing the workbook entirely?
You can set Cancel = True to block the close, but this is easy to bypass with macros disabled or Task Manager, so treat it as a convenience prompt rather than a security control.
Why does my BeforeClose code not fire when I close via a macro?
If another macro closes the workbook with events disabled (Application.EnableEvents = False), the event is skipped. Re-enable events before calling Close.
Can I use BeforeClose to save a backup copy?
Yes. Use ThisWorkbook.SaveCopyAs with a full path and file name. Keep the operation short and wrap it in error handling so a failed backup does not block the close.
Does BeforeClose work in Excel for Mac?
Yes, the event model is the same. Use Option+F11 to open the editor. Menu labels and some shortcut keys can differ slightly by version and region.
What is the difference between BeforeClose and BeforeSave?
BeforeClose fires when the workbook is closing. BeforeSave fires whenever a save is attempted, including saves triggered from inside BeforeClose. Use BeforeClose for close-time prompts and BeforeSave for validation before writing to disk.