XL2000: How to Create and Use a Workbook_BeforeClose Procedure (213639)



The information in this article applies to:

  • Microsoft Excel 2000

This article was previously published under Q213639

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.

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.

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.

Modification Type:MinorLast Reviewed:10/11/2006
Keywords:kbdtacode kbhowto kbProgramming KB213639