Hack 60 Run Macros Automatically![]() ![]() Macros are all about automation, but to run they typically require you to click a toolbar button or select a menu item. This hack shows you how to create macros with minds of their own that run whenever you create, open, or close certain templates or documents. If you often do the same thing when you first open a document, such as checking one of the document properties or turning on field-code shading, why not have Word do it for you? There are five special names you can give your macros that cause them to run when certain things happen in the Word world. These are known as AutoMacros, and how they behave depends both on their names and on where they're stored. These are the five AutoMacros available in Word: AutoOpen This macro runs (or "fires") when you open a file where the macro is stored. However, if you create a macro named AutoOpen in a template, the macro won't fire when you create a new document based on the template (for that you'd use an AutoNew macro, described below). AutoNew This macro fires when you base a new document on the document or template where you stored the macro. AutoClose This macro fires when you close the document or template where you stored the macro. AutoExec This special AutoMacro runs only when stored in a global template. It fires when the global template is loaded. If you a put a macro named AutoExec in your Normal template, it will run every time you start Word. AutoExit This special AutoMacro runs only when stored in a global template. It fires when you unload the global template. If you put a macro named AutoExit in your Normal template, it will run every time you exit Word. You might find it easier to organize and keep track of your AutoMacros if you create separate code modules for them. For example, if you rename a code module in a template as AutoNew, whenever you create a document based on that template, Word will execute the macro named Main within that module. To change the name of a code module, open the Visual Basic Editor [Hack #2], select the module, and then rename it using the Properties window. 7.5.1 Disabling AutoMacrosIn addition to using the Word startup switches [Hack #52], you can open documents from within VBA to control which, if any, AutoMacros run. The following macro opens a document named foo.doc, but first disables any AutoMacros: Sub OpenFooDoc( ) The Word documentation mentions the DisableAutoMacros command but provides no information on the corresponding command to reenable the macros (it's not EnableAutoMacros, as you might expect). You just need to supply an optional argument to the DisableAutoMacros command: Sub ReactivateAutoMacros( )
|