Using Events with the Document Object

Microsoft Word Visual Basic

Using Events with the Document Object

   

The Document object supports three events: Close, New and Open. You write procedures to respond to these events in the class module named "ThisDocument." Use the following steps to create an event procedure.

  1. Under your Normal project or document project in the Project Explorer window, double-click ThisDocument. (In Folder view, ThisDocument is located in the Microsoft Word Objects folder.)
  2. Select Document from the Object drop-down list box.
  3. Select an event from the Procedure drop-down list box.

    An empty subroutine is added to the class module.

  4. Add the Visual Basic instructions you want to run when the event occurs.

The following example shows a New event procedure in the Normal project that will run when a new document based on the Normal template is created.

Private Sub Document_New()
    MsgBox "New document was created"
End Sub

The following example shows a Close event procedure in a document project that runs only when that document is closed.

Private Sub Document_Close()
    MsgBox "Closing the document"
End Sub

Unlike auto macros, event procedures in the Normal template don't have a global scope. For example, event procedures in the Normal template only occur if the attached template is the Normal template.

If an auto macro exists in a document and the attached template, only the auto macro stored in the document will execute. If an event procedure for a document event exists in a document and its attached template, both event procedures will run.

Remarks

For information on creating event procedures for the Application object, see Using Events with the Application Object.