Microsoft KB Archive/193663

= XL98: How to Create and Use a Workbook_BeforeClose Procedure =

Article ID: 193663

Article Last Modified on 6/17/2005

-

APPLIES TO


 * Microsoft Excel 98 for Macintosh

-



This article was previously published under Q193663



SUMMARY
If you want to run a Visual Basic for Applications macro every time a particular workbook is closed, you can attach a Visual Basic procedure to the BeforeClose event of the workbook. This article contains an example that illustrates how to use the BeforeClose event.



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. The following example illustrates how to use the BeforeClose event. In this example, a cell is updated with the current date and time when the workbook is closed.  Save and close any open workbooks and then open a new workbook. Start the Visual Basic Editor by pressing OPTION+F11. On the View menu, click Project Explorer. Double-click the ThisWorkbook object in the Project Explorer window.

The module sheet for the ThisWorkbook object is opened.  Type the following code into the module sheet: Private Sub Workbook_BeforeClose(Cancel As Boolean)

' Place the current date and time into cell A1 of Sheet1. Worksheets("sheet1").Range("a1").Value = _ Format(Date + Time, "mm/dd/yy hh:mm")

' Save the current workbook. ThisWorkbook.Save End Sub  Switch to Microsoft Excel by pressing OPTION+F11. On the File menu, click Save As. Type the name for your workbook in the Save As box, and then click OK.</li> On the File menu, click Close.</li></ol>

The Workbook_BeforeClose procedure will start, and the current data and time will be placed into Sheet1.

For additional information about using Auto_Close procedures in earlier versions of Microsoft Excel, please see the following article in the Microsoft Knowledge Base:

141563 XL: How to Create and Use an Auto_Close Procedure

<div class="references_section">