Chapter 5

Managing Documents with Events

The main functionality for creating and managing Microsoft Office documents is reflected in the commands on the File menu in Word, Excel, PowerPoint, Microsoft Access, and Microsoft Outlook. You use the File menu, among other things, to create new documents and to open, save, close, and print existing ones. When you use the mouse or a keyboard shortcut to invoke one of these File menu commands, Office determines what command has been invoked and what action should be carried out.

When one of these actions, or events, occurs, your Microsoft Visual Basic for Applications program can respond, allowing you to determine when a document is created, opened, saved, closed, or printed. This chapter describes the event procedures that are called in your programs when any one of the following commands or their programmatic equivalents (as described in Chapter 4) are invoked through the File menu or through Visual Basic code: New, Open, Close, Save, Save As, Save as Web Page, and Print. After you set up event procedures to handle the occurrence of the actions New, Open, Save, Close, and Print, you can develop solutions like the following:

IMPORTANT
In some cases you'll find that you can't perform certain operations when the code is executed within an event procedure. For example, if you add the line Pres.Close in the NewPresentation event procedure in PowerPoint, an error will occur indicating that this operation can't be performed in the event procedure. Also, an application may not allow your program to quit the application (that is, execute Application.Quit) in an event procedure.