Hack 2 Macros 101: A Crash Course![]() ![]() which can help you automate tedious and time-consuming tasks.Word 6 or later lets you write, record, and play macros, or short programs that automate tasks in Word. The term macro comes from macrocommand, which originally referred to a bunch of commands strung together and executed all at once. Typically, you would record a sequence of commands, give the sequence a name, and then play it back as needed. You can certainly use Word macros for this purpose, but it represents only the tip of the iceberg.You create Word macros using Visual Basic for Applications, usually abbreviated as VBA. Even recorded macros get translated into VBA, which you can then examine or edit.VBA belongs to the BASIC family of computer languages. Compared to other computer languages, such as C or Java, you may find it easier to master. But like any language, you'll need to use it in order to learn it.A true VBA tutorial falls outside the scope of this book. This hack simply shows you how to create and run a macro like the ones used in this book.
1.3.1 Nuts and BoltsMost of the macros in this book, as well as any you record within Word, use the subroutine (Sub) procedure. Each one begins with the following line: Sub MacroNamewhere MacroName is the name of the macro. Each ends with this line: End SubThe instructions you give Word fit between these two lines. Cooking offers a useful analogy. In fact, you can think of a macro as a recipe. You begin with the list of ingredients at the top and then add a sequence of actions to transform those ingredients into something edible. You can even split some recipes into several shorter recipesi.e., one for the sauce, one for the meatto make them easier to follow. The same goes for macros. In the example below, note the list of "ingredients" at the top, followed by the rest of the code to work those ingredients into the main course: Sub CountCommentsByBob( )The next section shows you how to put macros to work in your documents. 1.3.2 Hello, WorldA tradition in computer books is to present the first example as a simple program that announces its existence to the world. In Word VBA, that would go something like this: Sub HelloWorldTo create this macro, select Tools display the Macros dialog. A listbox at the bottom, labeled "Macros in," lists all the open templates and documents where you can store your macro, as shown in Figure 1-11. For example, choose the "All active templates and documents" option to create your macro in the Normal.dot template. Figure 1-11. Choosing where to store a macro![]() "Macro name" field and press the Create button, as shown in Figure 1-12. Figure 1-12. Creating a new macro from the Macros dialog box![]() module to hold your macro code, named NewMacros.Word launches the Visual Basic Editor.Word fills in the first and last lines of the macro for you and inserts some comments about the macro. (The comments help the people who read the programs. In VBA, comments always start with a single quotation mark or apostrophe.)You will see the shell of your new macro in the Visual Basic Editor, as shown in Figure 1-13. The Project Explorer, in the top left, lists all open documents and templates, including any add-ins (such as the MSWordXML ToolBox [Hack #92] ). Notice that the NewMacros module is highlighted in the Modules section of the Normal template. Figure 1-13. The Visual Basic Editor![]() End Sub and type the following: MsgBox "Hello, World!"Now press the Play button (the green wedge) on the toolbar to run the macro. You'll see the dialog shown in Figure 1-14. Figure 1-14. Greetings from your first macro![]() template, just start a new line after End Sub and type in the first line for another macro. You can also paste code from other macros directly into the Visual Basic Editor. 1.3.3 Organizing and Debugging Your MacrosIf you want to create a new module to help organize your macros, select the template or document where the new module will go from within the Project Explorer, then select Insert modules created like this are always named Module1, Module2, and so on, as shown in Figure 1-15. In the Properties window, located just under the Project Explorer (see Figure 1-13), you can rename the modules. Figure 1-15. A new module inserted into the Normal template![]() source of program bugstyping errorsyou should always include the following as the very first line of code in any module: Option ExplicitThis tells Word to make sure you've declared every variable you use in the macro. To continue with the cooking analogy, it's like checking the recipe to make sure you listed every ingredient at the top. If you try to run a macro with a misspelled variable name, Word will warn you and highlight the undeclared variable, as shown in Figure 1-16. Figure 1-16. Word can help find mistakes in your macros![]() Return to Microsoft Word. 1.3.4 Running MacrosTo run a macro from within Word, select Tools press the Run button, as shown in Figure 1-17. Figure 1-17. Running a Macro from within Word![]() button or keyboard shortcut. Select Tools the Commands tab, and select Macros from the Categories column, as shown in Figure 1-18. In the Commands column, find the macro and drag it to a toolbar or menu. After you place the macro, you can right-click it to change its name or add an image to its button, as shown in Figure 1-19. Figure 1-18. Selecting the Macros category from the Customize dialog![]() Figure 1-19. Changing the name of the button used to activate a macro placed on a toolbar or menu![]() your workflow, consider separating those into a separate Macros template [Hack #50] that will load automatically whenever Word starts. 1.3.5 Getting Help from the EditorThe Visual Basic Editor is a full-featured development environment that includes several features designed to help you write VBA code. 1.3.5.1 IntelliSenseAs you type VBA code, the editor will attempt to complete the statement for you, as shown in Figure 1-20. Figure 1-20. The Visual Basic Editor can help you write code faster![]() can explicitly request a list of items that match the text you've already typed by pressing Ctrl-spacebar. 1.3.5.2 The Immediate windowIn the Immediate window, you can enter individual statements that are executed immediately. When a statement is prefaced with a question mark, the return value is printed to the Immediate window, as shown in Figure 1-21. Figure 1-21. Using the Immediate window![]() the following line of code in a macro: Debug.Print StringToPrintReplace StringToPrint with a text string or a string variable you want to keep an eye on, which will be printed to the Immediate window. This technique is shown in Figure 1-22. 1.3.5.3 Stepping through codeAs you test out a macro, it can help to "step" through it as it runs. Word will execute one line of the macro, then wait for you to tell it to run the next line. In this way, you can slow down a macro and better understand it. If you hover your mouse over a variable while stepping through the code, Word displays the current contents of the variable as a ToolTip.To step through a macro, put your cursor anywhere inside it and press F8. Each time you press F8, you execute another line of code. The line that will be executed the next time you press F8 will be highlighted in yellow, and an arrow will appear at the left, as shown in Figure 1-22. Figure 1-22. Using the Visual Basic Editor to step through a macro line by line![]() 1.3.6 Exploring the Word Object ModelIn Word VBA, all of Word's parts are represented as objects. A document is an object, a paragraph is an object, and even a font name is an object. All of these objects are interrelated, and evaluating and manipulating them is the basis of programming Word with VBA.To browse the Word object model, select View from within the Visual Basic Editor. Using the Object Browser can be an overwhelming experience for beginners, but it can be a great help in figuring out how to automate a particular component or task within Word. The Object Browser is shown in Figure 1-23. Figure 1-23. Using the VBA Object Browser![]() |