Tips
for Recording Macros The techniques of recording a macro are straightforward and well documented in Word's Help system, but there are some tricks you can use to make the process even easier. If your macro will require more than five or six steps, you should create a script for it, to prevent errors during recording. Before you start, perform the operations that make up your task, writing down each step as you go. It's usually better to assign macros to shortcut keys than to a toolbar button. Word already uses many common keystroke combinations, however. When you choose the keystroke combination in the Customize Keyboard dialog box, be sure to check for conflicts with existing keystrokes. This information appears just below the box where you enter your keystroke combination. Try Ctrl-Alt-Shift plus another key; these combinations are not assigned to normal Word functions. Choose a letter that will help you remember the function of your macro. Work slowly as you record, checking your script to make sure each operation is correct. There's no time limit, and the macro won't run any faster if you rush through. During recording, if you need to perform an action you don't want to record, click the Pause Recording button on the Macro toolbar. Click it again to resume recording. When you're finished with the final operation, click the Stop button on the Macro toolbar, and you're finished. Test your new macro to make sure it works properly.

Adopt Existing Macros
You can find lots of Word macros online, both on Microsoft's Web site and elsewhere. Macros are stored in .dot template files. You'll need to transfer the macros from the document or template into your Normal.dot template so you can use them in your documents. Here's how: Open the document or template containing the macros you want by choosing File, Open. Select Tools, Macro, Macro, then click Organizer in the dialog box that appears. In the Organizer dialog box, select the file containing the macros you want, using the drop-down list on the left side of the dialog box.
Select Normal.dot on the right side of
the Organizer dialog box. From the list on the left, select one or more
macros you want to copy to your default template, then click the Copy
button. Click Close. Word will automatically save the Normal.dot
template before you exit Word.
Caution:
Word macros are very powerful and have the potential to damage data on your system if badly or maliciously written. Be sure that the source of any outside macros is trustworthy.

Use Word Commands as Macros
You can run any Word command as a macro, including some commands not accessible from menus or toolbars. To do this, select Tools, Macro. Choose Word Commands from the Macros Available In drop-down list. Select the command you want, then click Run.
Note:
Each command has a brief description of its function, which appears when you select it.

Running a Macro The most convenient way to run a macro in Word is to attach the macro to a menu, toolbar, or keystroke shortcut. Here's a brief description of how to do this.
To attach a macro to a toolbar, make sure the toolbar is showing. If it isn't, choose Tools | Customize to open the Customize dialog box, then choose Toolbars and add a check next to the toolbar's name. With the Customize dialog open, choose Commands. In the Categories list box, select Macros. In the Commands list box, find the macro you want to add and drag it to the toolbar. You can then right-click on the button to modify its properties. To delete the macro from the toolbar, make sure the Customize dialog box is open and drag the button off the toolbar.
The menu system is a special-purpose toolbar. When you drag a macro to a menu on the menu bar, wait for the menu to open and then drag the button to position it on the menu of your choice.
To attach a macro to a keystroke, open the Customize dialog box and choose the Keyboard button. In the Categories list box, select Macros. Then go to the Macros list box and select the macro to associate with a keystroke. Move to the Press New Shortcut Key box, type the keystroke you want to use, and choose Assign.

Getting
Started with VBA
By M. David Stone, PC Magazine
When Microsoft released Word 97, the flow of Word macro tips from our readers slowed to a trickle. The problem was that Word 97 introduced a new macro language, VBA (Visual Basic for Applications.) VBA is not just a new language that replaces the WordBasic language in all earlier versions of Word, it's also very different in concept. As a result, a lot of people who fearlessly delved into programming with WordBasic have chosen to avoid macros altogether in Word 97 and Word 2000. And people who never started with WordBasic are even less likely to try VBA.
That's a shame, because VBA has at least as much potential as WordBasic to make Word better match your needs. Once you've learned VBA in one Office program, you've learned most of what you need for writing VBA macros in other Office programs.
The aim of this article is to help you start learning VBA. We'll cover some useful specifics, such as how to create a message box. But the real goal is to give you strategies for learning more about VBA on your own. Note that all the step-by-step descriptions are based on Word 2000. There will be some minor differences if you're using Word 97.
Use the Recorder
Word's macro recorder is probably the key tool for learning how to write macros. When you don't know how to enter a Word command in a macro, record the command and then dissect what Word's macro recorder produces for you and modify it as needed.
Suppose you want to write a macro that includes a find-and-replace operation, acting on text you've selected. For our example, we'll search for tabs and replace them with asterisks. If you don't know the macro commands, you can record them.
Start by selecting some text. Then choose Tools | Macro | Record New Macro. Give the macro an appropriate name, such as Test1. Make sure the Store Macro In box is set to All Documents
(Normal.dot), then choose ok to close the Record Macro dialog box and return to your document with the macro recorder on.
Next, choose Edit | Replace, enter the tab symbol ^t (a caret followed by a lowercase t) in the Find What box, enter an asterisk (*) in the Replace With box, choose Replace All, then answer No when Word asks if you want to search the remainder of the document. Finally, choose Tools | Macro | Stop Recording, and then close the Find and Replace dialog box.
Now take a look at the macro Word recorded for you. Choose Tools | Macro | Macros to open the Macros dialog box, select Test1 in the Macro Name list, and choose Edit to open the VBA editor, as shown in Figure 1. The basic structure Word produces for a find-and-replace command is:
Sub Test1()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
The first line names the subroutine Test1. If you record this yourself, you'll see several comment lines immediately following this line. These begin with apostrophes to indicate that the macro should ignore them. The VBA editor will mark comments in a different color.
The next two lines in the macro tell Word not to look for any particular formatting in its search and not to Thursday, May 8, 2008 9:26 AM No Formatting buttons in the Find and Replace dialog box. After that comes a section that tells Word what settings to use when it searches. We've left out the individual settings to stress the structure, but they would appear between the With and End With statements. (We'll come back to those settings in a moment.) The line after the End With statement says: Working with the selected text, execute the Find command and replace all found items with the previously defined replacement text. The End Sub line signifies the end of the subroutine.
You'll want to run the macro to check that it works. The best way to run a macro when you're working with it is from the VBA window. Arrange the Word and VBA windows so you can see both your document and the macro. Then, make sure you can see either the Standard or the Debug toolbar in the VBA window.
Both toolbars include a Run Macro button, indicated by a solid, right-pointing triangle (second from the left on the Debug toolbar and roughly centered on the Standard toolbar.) To test the macro, first make sure the cursor in the macro window is located between the Sub Test1() and End Sub statements. Then select some text in the document window and click on the Run Macro button.
The macro will run the Find and Replace command, then it will ask if you want to search the rest of the document. This is a minor problem: You generally wouldn't want this question to pop up in the middle of a larger macro every time you run the macro. Choose No to end the macro, then take a look at the settings between the With and End With commands.
The section of the macro that we skipped over before reads:
Thursday, May 8, 2008 9:15 AM
">Thursday, May 8, 2008 9:15 AMquot;
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
If you compare this list to the choices in the Find and Replace dialog box, you'll find that most of the settings map to choices in the dialog box: Text maps to Find What, Replacement.Text maps to Replace With, and so on. There's only one option in this list that doesn't map to a choice in the dialog box. The option is Wrap, and the setting is
wdFindAsk. The name itself hints that this option is telling Word to ask you whether to continue searching.
Put your cursor in Wrap and hit F1. If Microsoft Visual Basic Help is installed, it will open to the information on the Wrap property. You'll find a description of three choices:
wdFindAsk, which asks whether to continue past the end of the selection;
wdFindContinue, which keeps searching without asking; and wdFindStop, which stops at the end of the selection. (If the help feature isn't installed, you'll see a message when you hit F1 asking if you want to install it. Choose Yes.)
The key lesson here is that you can use the help information as a powerful tool to solve specific problems. Also note that as you become more familiar with VBA, the VBA editor can fill in some blanks for you. Suppose, for example, that you know you have to change the Wrap property but you can't remember what you want to change it to. Try this: Right-click on wdFindAsk and choose List Constants. You'll see the pop-up window shown in Figure 2, with the three choices for the Wrap property. You should have no trouble picking the right choice from the list. As you work with the VBA editor, you'll find that it has a number of similar helpful features.
Message Boxes and Shell Commands
One of the more popular macros we've published in PC Magazine (judging by requests for an update in VBA) called on a DOS batch file to back up data files incrementally. If you name the macro
AutoExit, it will run every time you close Word. Aside from being useful, this macro shows how to use message boxes and how to have a macro run another program, in this case a dos batch file that does the actual backing up.
The batch file should be named Wwbu.bat and stored in the directory
C:Batfiles. For purposes of testing the macro, you might want to create a file by that name with the single line @ECHO Hi There, which will show that Word is successfully running a batch file. When the file runs, it will open a dos window and display Hi There at the C: prompt. To actually back up files, the batch file should have a command similar to:
xcopy c:data*.* g:data /s/m
where c:data is the first-level directory that contains all your data directories and G:data specifies where you want to store the backup copies. The /s tells Xcopy to copy all subdirectories. The /m limits the copying to files that have been modified since the last time you copied them.
You can create this batch file with any text editor. If you use Word, save the file as Text Only. (Choose File | Save,and set the Save as type to Text Only (*.txt.))
To create the macro itself, choose Tools | Macro | Macros, enter AutoExit as the macro name, then choose Create. Word will take you to the VBA editor. Enter the Sub
AutoExit() and End Sub lines and leave the cursor between them. You can then enter the following macro:
Dim Backup, Style, Title, Response
Backup = "Backup Files?"
Style = vbYesNo + vbDefaultButton1 + vbQuestion
Title = "Optional Backup on Exit"
Response = MsgBox(Backup, Style, Title)
If Response = vbYes Then
Dim RetVal
RetVal = Shell("c:batfileswwbu.bat", 1)
End If
The first five lines define a message box. The rest of the macro tests the response to the message box and either runs the batch file or doesn't, depending on the response.
The first line in this macro uses the Dim statement to create the variables Backup, Style, Title, and Response. This isn't strictly necessary unless you've set Word to require it by choosing Tools | Options | Editor and then checking the Require Variable Declaration check box. It's a good habit to get into (for reasons beyond the scope of this discussion.)
After creating the variables, the macro defines each one. To best understand the structure, jump ahead to the MsgBox function in the fifth line and note that it uses the first three variables. The Backup variable defines the prompt, the Style variable defines the message box buttons, and the Title variable defines the message box title. Going back to the definitions for the variables themselves, Backup and Title are straightforward text. Style is defined to show Yes and No buttons, with Yes as the default and with a question mark icon showing in the message box. For other message box possibilities, place the cursor on Msgbox in the VBA editor and hit F1.
The definition for the Response variable takes advantage of the Msgbox function. The If statement then tests the value of Response. If the user chooses Yes, the statement creates the RetVal variable and uses the Shell function to run the batch file.
The lesson here is that you really can jump into VBA and learn by doing. Notice that we have hardly mentioned such potentially confusing VBA concepts as objects, properties, methods, and so on. Once you get some hands-on experience and begin to get a feel for the language, you'll be in a much better position to understand those concepts. For the moment, just experiment with VBA-think of it as play-to see how it works.
|