O'Reilly logo

Writing Word Macros, Second Edition by Steven Roman PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Document Events

As we have discussed, each Word document has three events associated with it: Open, Close, and New. Any code that we place in the event procedure for one of these events will execute when the event occurs (or fires, as programmers say). To experiment with these events and when they fire, we can add the code shown in Figure 3-12 to each event. (This is a very handy trick for events that are associated with controls on a user form, as well.)

The docking options

Figure 3-11. The docking options

Illustrating the document events

Figure 3-12. Illustrating the document events

As you will see in the next chapter, the MsgBox command displays a simple dialog box containing some text on the screen.

To follow along, you should first select the ThisDocument node for a Word document in the Project window (don’t forget to double-click on the node to open the corresponding code window, or use the F7 key). Then select Document in the Object box and each of Close, New, and Open in turn in the Procedure box. For each event, type in the single line of code that you see in Figure 3-12. Then repeat the process with the TemplateProject that the document is based upon. However, change the code slightly by replacing the word “Document” with “Template”, as in:

	MsgBox "Template close event fired."

Now close the active document. You should see two message ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required