Events

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

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:

  • Document-level or subdocument-level events   These events occur for open documents and in some cases, for objects within them. For example, the Word Document object can respond to the Open, New, and Close events; the Excel Workbook object can respond to events such as the Open, BeforeClose, and BeforeSave events; and the Excel Worksheet object can respond to events, such as the Activate and Calculate events. Microsoft® PowerPoint® supports only application-level events.
  • Application-level events   These events occur at the level of the application itself, for example, when a new Microsoft® Word document, Microsoft® Excel workbook, or PowerPoint presentation is created, for which the corresponding events are the NewDocument, NewWorkbook, and NewPresentation events.

Microsoft® 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 Microsoft® Outlook® Application object provides events that can be used from the ThisOutlookSession module or a COM add-in running from an installation of the Outlook application, such as 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 events, such as the Open, Read, and Reply events.

The Microsoft® FrontPage® Application object provides events that make it possible for your solution to respond to the creation and editing of pages and FrontPage-based webs, such as 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.

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 Microsoft® 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

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 a user opened the application.

Responding to Application-Level Events

Microsoft® Office XP 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 OnPageNew 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 OnWebNew 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 can 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

When 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 this way:

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.

See Also

Objects, Collections, and Object Models: Technology Backgrounder | Objects Exposed by an Object Model | Collections | Properties and Methods | Using the Object Browser | Working with the Outlook Object Model | Working with Shared Office Components