Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

XL2000: How to Create and Use a Workbook_BeforeClose Procedure


View products that this article applies to.

Summary

You can run a Microsoft Visual Basic for Applications macro (Sub procedure) every time a particular workbook is closed, by attaching the procedure to the BeforeClose event of the workbook. This article contains sample code that illustrates how to use the BeforeClose event.

↑ Back to the top


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 attach a procedure to the BeforeClose event:
  1. Start the Visual Basic Editor (press ALT+F11)
  2. On the View menu, click Project Explorer.
  3. In the Project Explorer window, double-click the ThisWorkbook object.

    The module sheet for the ThisWorkbook object is opened.
  4. Type the following code in 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
    					
  5. Switch to Microsoft Excel by pressing ALT+F11.
  6. On the File menu, click Close.
The Workbook_BeforeClose procedure starts, which places the current date and time into Sheet1.

↑ Back to the top


References

For more information about the BeforeClose event, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type BeforeClose Event in the Office Assistant or the Answer Wizard, and then click Search to view the topic.

↑ Back to the top


Keywords: KB213639, kbprogramming, kbhowto, kbdtacode

↑ Back to the top

Article Info
Article ID : 213639
Revision : 6
Created on : 10/11/2006
Published on : 10/11/2006
Exists online : False
Views : 280