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.)
Figure 3-11. The docking options
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 ...
Get Writing Word Macros, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.