To use either of the following examples, follow these steps:
- Start Excel and open a new workbook.
- Press ALT+F11 to start the Visual Basic editor.
- On the Insert menu, click Module.
- Type the sample macro code into the module sheet.
- Press ALT+F11 to return to Excel.
- In Microsoft Office Excel 2003 and in earlier versions of Excel, point to Macro on the Tools menu, and then click Macros.
In Microsoft Office Excel 2007, click Macros in the Code group on the Developer tab.
Note If the Developer tab is not available, consider the following steps:
- Click the Microsoft Office Button, and then click Excel Options.
- In the Popular category, under Top options for working with Excel, click to select the Show Developer tab in the Ribbon check box, and then click OK.
- Select the macro that you want, and then click Run.
You can use the reserved subroutine name "Auto_Close" to specify a macro that should run whenever a workbook is closed. By doing this, you can control how the document is handled when the user is finished and has instructed Excel to close the document.
Example 1: Close the workbook without saving changesTo force a workbook to close without saving any changes, type the following code in a Visual Basic module of that workbook:
ThisWorkbook.Saved = True
The DisplayAlerts property of the program can be used for the same purpose. For example, the following macro turns DisplayAlerts off, closes the active workbook without saving changes, and then turns DisplayAlerts on again.
Application.DisplayAlerts = False
Application.DisplayAlerts = True
The following macro closes the workbook without saving changes:
Example 2: Close the workbook and save the changesTo force a workbook to save changes, type the following code in a Visual Basic module of that workbook:
If ThisWorkbook.Saved = False Then
Article ID: 213428 - Last Review: May 16, 2017 - Revision: 2