MORE INFORMATION
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
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.
- On the Tools menu, point to Macro, and then click Macros.
- Select the macro that you want, and then click Run.
The
Saved property returns the value
False if changes have been made to a workbook since it was last saved.
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: Closing the Workbook Without Saving Changes
To force a workbook to close without saving any changes, type the following
code in a Visual Basic module of that workbook:
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
Because the
Saved property is set to
True, Excel responds as though the workbook has already been saved and no changes have occurred since that last save.
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.
Sub CloseBook()
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
You can also use the
SaveChanges argument of the
Close method.
The following macro closes the workbook without saving changes:
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
Example 2: Closing the Workbook and Saving the Changes
To force a workbook to save changes, type the following code in a Visual Basic module of that workbook:
Sub Auto_Close()
If ThisWorkbook.Saved = False Then
ThisWorkbook.Save
End If
End Sub
This subprocedure checks to see if the file's
Saved property is set to
False. If so, the workbook has been changed since the last save, and those changes are saved.