Share this Page URL

The Word Object Model > The Document Object - Pg. 427

object is always available, and can be referenced simply as Application. When you are working with Word objects from VBA hosted by other applications, you need to explicitly create the Word Application object using CreateObject or GetObject (Example 18-30). Example 18-30. Using CreateObject Set appWord = CreateObject("Word.Application") The first code fragment in Example 18-31 uses one of the methods of the Application object to maximize the Word window, while the second restores the Word window, then moves and resizes it to a specific size and position. Example 18-31. Controlling the Application Window Application.WindowState = wdWindowStateMaximize With Application .WindowState = wdWindowStateNormal .Move Left:=0, Top:=97 .Resize Width:=473, Height:=489 .Move Left:=135, Top:=51 End With The Document Object The Document object is used to work with Word documents in VBA code. To work with the currently open document, use the ActiveDocument property of the Appli- cation object, as in the code fragment in Example 18-32. Example 18-32. Using the Document Object Set doc = Application.ActiveDocument Events are external actions on an object to which the object can react. The Document object has three events, for which you can write event procedures. The code in an event procedure runs when the event occurs. The Open event fires when a document is opened, the Close event when a document is closed, and the New event fires when a new document is created from a template. To create an event procedure for a document, open the document, then open the VBA window (Figure 18-4). Select the document's project in the Project Explorer. Open the Microsoft Word Objects folder for the document, and double-click the ThisDocument object to open its module. Drop down the Objects box (the one at the top left of the Code window) and select the Document object. Drop down the Events/Procedures box (the one at the top right of the Code window) to see the three document events. Selecting an event creates a code stub for that event. Next, type the code to be run when the event occurs in its event procedure. The Document_New event procedure in Example 18-33 hides the Word window and pops Working with VBA The Word Object Model | 427