Microsoft Office 2000/Visual Basic Programmer's Guide   

Working with Events

An event is an action that is typically performed by a user, such as clicking a mouse button, pressing a key, changing data, or opening a document or form, but the action can also be performed by program code, or by the system itself. You can write event procedure code to respond to such actions at either of two levels:

Access provides a different model that responds to events on Form and Report objects, and most of the controls on them, such as ListBox and TextBox objects. UserForms, which can be used from Excel, Word, and PowerPoint, provide a similar event model to Access forms.

The Outlook Application object provides 6 events that can be used from the ThisOutlookSession module or a COM add-in running from an installation of the Outlook application: ItemSend, NewMail, OptionsPagesAdd, Quit, Reminder, and Startup. To create code that responds to a user's actions in the Outlook user interface, you can use the WithEvents keyword to declare object variables that can respond to Outlook Explorer, Inspector, and MAPIFolder object events. All Outlook item objects, except the NoteItem object, can respond to up to 11 events, such as the Open, Read, and Reply events.

The FrontPage Application object provides 10 events that allow your solution to respond to the creation and editing of pages and FrontPage-based webs: OnPageNew, OnPageOpen, OnBeforePageSave, OnAfterPageSave, and OnPageClose, and OnWebNew, OnWebOpen, OnBeforeWebPublish, OnAfterWebPublish, and OnWebClose.

In addition to the events supported by each Office application, the CommandBarButton object, CommandBarComboBox object, and CommandBars collection support events. For information about working with command bar events, see Chapter 6, "Working with Shared Office Components."

Responding to Document-Level Events

To create event procedures for events in Excel workbooks and Word documents, you need to work with the ThisWorkbook or ThisDocument modules. For example, to write an event procedure that will run when a Word document is opened, open the document and then open the Visual Basic Editor. In the Project Explorer, double-click ThisDocument to open the ThisDocument module. In the Object box in the Code window, click Document, and then click Open in the Procedure box. The Visual Basic Editor will create an event procedure template for the document's Open event. You can then enter any code you want to run whenever the document is opened. For example, the following event procedure sets certain features of the active window and view of a Word document when it is opened:

Private Sub Document_Open()
' Set Window and View properties to display document with document map
' in page layout view.
   With ActiveWindow
      .DisplayVerticalScrollBar = True
      .DisplayRulers = False
      .DisplayScreenTips = True
      .DocumentMap = True
      .DocumentMapPercentWidth = 25
      With .View
         .Type = wdPageView
         .WrapToWindow = True
         .EnlargeFontsLessThan = 11
         .ShowAll = False
         .ShowPicturePlaceHolders = False
         .ShowFieldCodes = False
         .ShowBookmarks = False
      End With
   End With
End Sub

The Document_Open procedure is available in the ThisDocument module in OpenEvent.doc in the ODETools\V9\Samples\OPG\Samples\CH04 subfolder on the Office 2000 Developer CD-ROM.

If you want to prevent code written in a document's Open event from running when the document is opened programmatically from another application, you can check the Application object's UserControl property to determine if the application was opened by a user. To see an example of how to do this, see "Working with Documents That Contain Startup Code" later in this chapter.

Responding to Application-Level Events

In Office 97, Excel was the only Office application that provided a rich set of application-level events. Microsoft Office 2000 now includes a comparable set of events for Word and PowerPoint with similar names across each application. For example, where Excel provides NewWorkbook and WorkbookOpen events, Word provides NewDocument and DocumentOpen events, and PowerPoint provides NewPresentation and PresentationOpen events. Providing consistent event handling and similar names across Word, Excel, and PowerPoint makes it easier to create a COM add-in that works across these applications. FrontPage doesn't supply as extensive a set of application-level events as the other Office applications, but FrontPage events also have similar names; for example, OnPageNew, OnWebNew, OnPageOpen, and OnWebOpen.

The NewDocument, NewWorkbook, NewPresentation, and PageNew events are useful for tasks such as automatically formatting new documents and inserting content such as the date, time, author, or latest company logo off the intranet. Similarly, the WebNew event can be used to automatically apply themes or to add pages and content to new FrontPage-based webs. The DocumentOpen, WorkbookOpen, PresentationOpen, and OnPageOpen events can be used to retrieve information from the document and update command bar customizations. The DocumentClose, DocumentSave, and DocumentPrint events in Word (and comparable events in Excel and PowerPoint) can be used to ensure that document properties, such as the author or subject, are entered in the document before the document can be closed, saved, or printed. Similarly, the FrontPage OnBeforePageSave, OnBeforeWebPublish, OnPageClose, and OnWebClose events can be used to check page properties or to check the sizes of image files on the page, and to verify hyperlinks before publishing a FrontPage-based web.

To write event procedures for the Application object, you must create a new class module and declare an object variable as type Application by using the WithEvents keyword. For example, you could create a class module named XLEvents and add the following declaration to create a private Excel Application object variable to respond to events:

Private WithEvents xlApp As Excel.Application

Once you have done this, you can click xlApp in the Object box of the class module's Code window, and then click any of the events in the Procedure box to write event procedures to respond to Excel Application object events. However, because you can't use the New keyword to create an instance of the Application object variable when you are declaring it by using the WithEvents keyword, you'll need to write a Set statement to do so in the class module's Initialize event like this:

Private Sub Class_Initialize
   Set xlApp = Excel.Application
End Sub

This process is called creating an event sink. To activate the event sink, you declare in another module a public (or private) object variable for your event sink class, and then run a procedure that will create an instance of your class before the events you want to handle occur. For example:

Public evtEvents As XLEvents

Public Sub InitXLEvents()
   Set evtEvents = New XLEvents
End Sub

Creating an event sink in a class module provides a way for you to create an independent object that will respond to application-level events. The VBA project that contains the class module and procedure used to initialize your event sink must be running before any of the events you want to trap occur. Because application-level events are triggered by events that occur while the application itself is being used to open and work with documents, you will most typically implement an event sink in an add-in to trap an application's application-level events, or in Automation code running from another application.

For detailed information about how to create an event sink for application-level events, see Chapter 9, "Custom Classes and Objects."