In this chapter
How Office Applications Store Macros
Troubleshooting Recorded Macros
Digitally Signing Macros You Create
Extra Credit: Getting Ready to Tackle VBA
Office macros are small computer programs that perform tasks on your behalf. And when we say small, we mean very small. A skilled programmer can create a macro that does something meaningful with just a few lines of program code, written in the underlying programming language of Office, Visual Basic for Applications (VBA).
Anyone can create powerful macros using tools built into Word, Excel, and PowerPoint (OneNote does not support the use of macros). But most people never use Office macros. Why? The two most common reasons are
After you learn what macros can do, you’ll probably think of dozens of ways you can use them to automate simple tasks. But there’s no getting around the fact that you have to invest some time and effort before you can use macros successfully. For instance, in Word, Excel, or PowerPoint, you can turn on a macro recorder that captures the results of your clicks and keystrokes as you perform a task. The recorder generates program code that you can save as a macro you can play back later to perform the same task. As we note in this chapter, however, most recorded macros require some tweaking of the generated code before they will work as you expect. As a result, you need to understand basic programming principles to make the most of these tools.
If you learned how to create and use macros in a previous Office version, your skills are directly transferable to Office 2007. First, though, you have to find all those familiar tools. In Office 2007 programs that use the new Ribbon-based interface, you’ll find a tiny Macros group at the far right of the View tab (see Figure 26.1); it contains basic tools for viewing existing macros and recording a new one.
Figure 26.1. The default Macros group contains this limited set of tools for creating and managing macros.
You’ll find a more complete set of macro-related tools on the Developer tab, which is normally hidden. To unhide it so you can begin using macros in Word, Excel, or PowerPoint, click the Office button, click Word (or Excel or PowerPoint) Options, and click to select the check box next to Show Developer tab in the Ribbon. As Figure 26.2 shows, the Code group contains commands to open the Visual Basic Editor, the Macros dialog box, the macro recorder, and the Macro Security dialog box.
Figure 26.2. You’ll find a more complete set of macro tools on the Developer tab, which is hidden by default.
When you make the Developer tab visible in one Office program, it becomes visible in all other Ribbon-based programs as well.
The more you know about macros and VBA, the more you’re able to use them effectively. In this chapter, we explain how macros work, how to troubleshoot recorded macros, and how to manage a collection of macros.
Most of the time, you use the individual programs that make up Microsoft Office interactively—typing text, inserting graphics, formatting, saving, and printing. That’s fine when you’re creating new content, but it’s no fun at all when you have to perform the same task regularly. Even a procedure that requires only three or four mouse clicks can become unbearable if you have to repeat it several times a day. The problem is even more acute if you perform any weekly tasks using Word or Excel where the step-by-step instructions are so complicated you have to print out a cheat sheet. If you have any such complicated task on your daily or weekly to-do list, you’re a prime candidate to create a macro that automates that task using a single command.
Macros can be surprisingly short—even a one-line macro can perform helpful tasks—or they can run for hundreds of lines, with loops and variables and input boxes, and other elements you normally associate with a full-fledged programming language.
In this chapter, we focus on the core elements of understanding, creating, fine-tuning, and using macros. For more detailed instructions, you’ll need to find other sources of information. One surprisingly useful source is just a click away. The Help file for each program in the Office family includes a Developer Reference section that explains basic concepts. This resource defines the purpose and syntax of each available programming object, often with code samples that you can cut and paste directly into your own projects. To see the local copy of the Developer Reference, open the Help window for the program for which you’re planning to write a macro, click the drop-down arrow to the right of the Search box, and choose Developer Reference under the Content from This Computer section.
With rare exceptions, you can create a macro to automate any task you can do manually in Word, Excel, or PowerPoint.
Macros are ideal for automating routine drudge work—those everyday tasks that normally require multiple menu selections and mouse clicks. For example, you can use macros to do any of the following tasks:
You can use macros for simple tasks, such as toggling a group of Word or Excel settings for a specific task, or for complex document assembly processes. You can assign a macro to a toolbar button, a keyboard shortcut, or a menu command.
What shouldn’t you do with macros? Each individual Office program includes features that help you automate tasks without having to use macros. When there’s a good alternative to writing a custom macro, the alternative is almost always preferable:
For hints on how to bring in boilerplate text, see “Using AutoCorrect to Type Faster,” p. 90.
To tailor a Find in Word, see “Finding and Replacing Text and Other Parts of a Document,” p. 182.
The Visual Basic Editor (see Figure 26.3) is the tool you use to view and edit Office macros.
Figure 26.3. The Visual Basic Editor usually contains two dockable, resizable panes, plus a large open area for writing programs and creating custom dialog boxes.
To open the Visual Basic Editor in Word, Excel, or PowerPoint, press Alt+F11. The Visual Basic Editor sits in its own window, separate from the Office application that opened it. For the simple tasks that we describe in this chapter, you’ll use only the code window, where you can see the code created by the macro recorder and directly edit it. If you’re interested in exploring the editor in more detail, use its excellent Help files.
Each Office program handles macros in a slightly different way. Although the precise details are complex, here’s a quick summary of how each Office application stores macros:
.docm
extension), a macro-enabled template (.dotm
), or the global macro-enabled template known as Normal.dotm. When you open a document that is associated with a macro-enabled template, macros in that template become available. If you store macro-enabled templates in the %ProgramFiles%Microsoft OfficeOffice12Startup folder, Word gives you access to macros stored in those templates whenever you start Word.For details on template locations, see “Where Does Word Store Templates?” p. 306.
.xlsm
) or templates (.xltm
). Unlike Word, Excel does not maintain a link between a workbook and the template you use to create it; if you add or edit a macro in a template, that macro is available only in new workbooks you create with that template. Excel automatically opens all workbooks in the %appdata%MicrosoftExcelXLSTART folder when it starts, including the hidden workbook Personal.xlsm. Thus, all macros in Personal.xlsm are available all the time.For details on templates, see “Customizing Excel,” p. 393.
.pptm
) and templates (.potm
). Like Excel, PowerPoint uses templates only to create new files, so adding or editing macros in a template will not affect existing presentations based on that template. PowerPoint does not have a Startup folder or anything resembling a global template. Macros written or recorded in earlier versions of PowerPoint should work in PowerPoint 2007.To understand the role of templates in PowerPoint, see “PowerPoint File Types,” p. 544.
Unless you’re a skilled programmer, avoid trying to automate anything but the most routine PowerPoint tasks with VBA. Compared with Word and Excel, its capability to help you with everyday tasks is incomplete. There’s no easy way to copy macros from one presentation to another short of copying and pasting code in the Visual Basic Editor. The lack of a global template makes it difficult to manage macros, and there is precious little documentation unless you dive into the Visual Basic Editor.
Word and Excel allow you to kick off the Macro Recorder by choosing Macros on the View tab and then clicking the Record Macros menu. The Macro Recorder exists in PowerPoint 2007 as well, but the command to start and stop the recorder has been inexplicably left off the View and Developer tabs. To record a PowerPoint macro, use the legacy keyboard commands Alt+T, M, R to start, and use the same keyboard combination to stop recording.
In theory, when you turn on the macro recorder, VBA “watches” as you perform some action or series of actions. When you turn off the recorder, you can replay the resulting recorded macro to replicate that series of actions.
In practice, you’ll more often use the macro recorder to eliminate the tedious steps of creating a macro. Unfortunately, a recorded macro rarely solves a real-world problem by itself. After recording a macro, you’ll typically need to make some modifications.
You can also use the recorder to capture the steps of a particular task and then copy all or part of the recorded macro into a larger macro.
As anyone who’s used the Office macro recorder for more than a few minutes can tell you, the macro recorder can’t record every single action you take. There are two fundamental reasons why the recorder can fail:
This type of failure, generally completely undocumented, happens without any warning to you. The recorder doesn’t stop and there’s no other feedback. You know the failure occurred only because the macro fails to work when you play it back.
After you turn on the macro recorder, it records the effect of your actions, not the actions themselves. The full effect of your actions goes into the recorded macro, not the means you used to apply them. For example:
When recording, instead of using the mouse, you’ll frequently have to resort to obscure keyboard navigation keys. To move to the beginning of the current paragraph in Word (or the previous paragraph, if the insertion point is already at the beginning of a paragraph), press Ctrl+↑. To select the word to the right of the insertion point (the first word in the paragraph, if you previously moved to the beginning of the paragraph), press Ctrl+Shift+ →. To italicize the word, press Ctrl+I.
Nobody, but nobody, memorizes all of Word’s obscure key combinations. To create a lengthy document listing them all, open the Macros dialog box, click in the Macro Name box, type listcommands
, and then click OK. Unfortunately, there’s no easy equivalent for PowerPoint or Excel.
Word, Excel, and PowerPoint include simple macro recorders that all work in essentially the same way. To record a macro in Word, for example, follow these steps:
ItalicizeFirstWord
, in this example).
Figure 26.4. Replace the generic Macro1 name with a descriptive macro name, but don’t use spaces or punctuation marks.
After recording a macro, it’s essential that you test it to see whether it works the way you expect. To quickly run a Word macro, follow these steps:
Figure 26.5. All available macros appear in the Macros dialog box.
Using the Macro dialog box enables you to run all currently available macros, regardless of which program you’re using. If you’re going to use the macro regularly, it’s easier to assign the macro to the Quick Access toolbar, or to a keyboard shortcut, as we explain in the Troubleshooting section at the end of this chapter.
Macros rarely work right the first time. Recorded macros, in particular, frequently require some tweaking before they work as intended. If the macro you recorded doesn’t work, re-record it and see whether you can use a different method for accomplishing the same result. Edit a recorded macro only when it works most of the time, but occasionally fails to work the way you expect, or triggers an error message.
Fortunately, Office makes it relatively easy to edit a recorded macro. It even supports you in your bug-extermination efforts by allowing you to run the macro program one line at a time, and see what the effect of each command might be. Here’s how to use the Visual Basic Editor to step through a macro recorded in Word (the steps in Excel and PowerPoint are virtually identical):
Figure 26.6. When you step into a macro for troubleshooting, the line that’s about to be run appears highlighted.
Frequently, you’ll be able to identify the location of the problem (or problems) in a macro by stepping through it in this way. Although the solution might not be at all clear—there are lots of VBA commands, and each one behaves in a different way—being able to narrow the problem down to a line or two can make a huge difference.
After you isolate the line that you suspect is causing the problem, position the insertion point within that line and press F1. That action brings up context-sensitive VBA Help, which might present a possible solution.
Follow the same procedures to step through Excel and PowerPoint macros; you’ll find recorded macros in the current workbook or presentation, in a module called Module1. Press F8 to step through the macro.
When a recorded macro doesn’t work as you expect, chances are the problem is one of several common errors. Table 26.1 lists common mistakes and suggested troubleshooting steps.
Table 26.1. Common Macro Problems
In addition, any number of unusual circumstances can trigger errors in recorded macros. For example, if you search for the word widget in a document where that word is in a footer and not in the body of the document, the search will succeed. When you record that action in a VBA/Word macro, everything appears to work just fine. But when you play back the recorded macro in the same document, Word won’t find the word you’re looking for no matter how many times you run it—in fact, it will trigger a run time error. The recorded version of the Find operation works differently from the interactive version when it comes to footers.
Just because a macro appears to work in a handful of simple tests doesn’t mean that the macro will work correctly all the time. Word macros are notorious for working properly inside simple documents, but failing—without any warning whatsoever—when run on a table, in text boxes, on pictures, in a document with Track Changes enabled, in headers and footers, in comments, in footnotes, and on and on. It can be devilishly difficult to find the problems and, after they are found, to figure out how to fix them.
Will your recorded macro work properly every time you run it? Frankly, there’s no way to know for sure—VBA macros hardly fall into the category of “probably correct” computer programs—but you can improve the odds of a macro working correctly by employing two time-honored testing techniques:
For example, the ItalicizeFirstWord macro example (in the “Recording a Macro” section earlier in this chapter) should italicize the first word in the current paragraph, but in one particular case it won’t. When the insertion point is at the beginning of a paragraph, this macro italicizes the first word of the preceding paragraph. Running through the macro a step at a time reveals that the culprit is the MoveUp command; when you point to that command and press F1, the context-sensitive help suggests several examples. The solution? You have to MoveRight once before performing a MoveUp, to stay in the original paragraph.
The recorded ItalicizeFirstWord macro contains a second problem as well. When you run the macro and then leave the insertion point in the same paragraph and run the macro again, it removes the italic formatting from the first word. Stepping through the macro again lets us see the problem: The Selection.Font.Italic line toggles the italic attribute on and off. According to the Help file, the Italic property “can be set to True
, False
, or wdToggle
.” Changing the value from wdToggle
to True
causes it to work properly.
Although each of the Office programs offers myriad ways to run macros, three simple methods in Word, Excel, or PowerPoint will get you going:
For details on setting up macros as buttons, see “Customizing the Quick Access Toolbar,” p. 33.
Office 2007 includes a number of security measures to help protect you from macro-based malware. Digital signatures lie at the heart of the approach most frequently encountered by Office users.
A digital signature identifies the source of a macro. Developers must apply for digital signatures from certifying authorities, which verify the identity of developers before issuing them a signature. Certifying authorities can revoke a certificate after issuing it if they discover evidence that a developer is distributing viruses or unsafe software.
The default settings for Office 2007 disable all macros except those included as part of files stored in trusted locations (typically the Templates and startup folders).
For more details on trusted locations, see “Setting Security Options in the Trust Center,” p. 702.
Those are excellent security precautions, but they get in the way if you create a document, workbook, presentation, or template that contains macros you want to reuse or share with other people.
If you are writing VBA programs that you want to share with other people without requiring them to lower their security settings to unacceptable levels, you must:
If your users have their security set to disable macros without notification, they won’t be able to use your macros, and they won’t be told why unless you sign your macros.
For more details on setting up security levels to manage macros, see “Managing Security for Add-ins, Macros, and Other External Content,” p. 701.
You have three options for obtaining a digital certificate:
To sign a VBA project, follow these steps:
After using your self-generated digital certificate to sign a project, you can examine its contents by clicking the Detail button. A self-signed certificate is marked with a red X that indicates it is not trusted because it can’t be traced back to a trusted certifying authority.
If you copy a document, template, or workbook containing a macro project that has been digitally signed with a self-generated certificate, you’ll be unable to open any of those macros on another computer. Windows protests that it can’t authenticate the certificate and thus gives you only the option to disable the macros and open the document.
Are you stymied? Not at all. If you’re absolutely, positively confident of the identity of the party who created the macros—for instance, if you created and signed them yourself on one computer and you want to use them on another computer in the same office—you can tell Windows that you want your self-generated certificate to be fully trusted. To do this, you need to install the certificate as a Trusted Root Certification Authority. Follow these steps:
certmgr.msc
and click OK. The Windows Certificates console opens.Now when you inspect the properties of the certificate, you’ll see that the red X has been replaced with an official seal of approval. You’ll also discover that your macros work flawlessly on the new computer.
I recorded a macro and told Word to run it whenever I press Shift+F5. I changed my mind after discovering that Word has a built-in command already assigned to Shift+F5. How do I change the macro so it runs when I push Shift+F6, and restore Word’s built-in command to Shift+F5?
In Word, click the arrow at the right of the Quick Access Toolbar and choose More Commands from the menu. This opens the Customize tab of the Word Options dialog box; click the Customize button at the bottom of the dialog box, to the right of the Keyboard Shortcuts heading. In the Categories list on the left, click Macros; then, in the Macros list on the right, select the name of the macro that you recorded. In the Current Keys box at the lower left, click the unwanted keyboard shortcut (in this case, Shift+F5), and then click Remove. That removes the Shift+F5 key assignment for your recorded macro and restores the assignment to Word’s default command. Click in the Press New Shortcut Key box, and press Shift+F6. Click Assign; then click Close twice. Shift+F5 will revert to the old GoBack function. Shift+F6 will run your recorded macro.
In Excel, the procedure is much simpler: Open the Macros dialog box, click the name of the macro and click the Options button. Your keyboard shortcut can consist of Ctrl+ any letter or number. Clear the box to remove the shortcut, or type a new letter to change it.
Ready to start working with VBA? Good. Take a few moments to organize your screen and customize the Visual Basic Editor. That way, you won’t have to hunt and click so much to get going. (To start the Visual Basic Editor, just start your favorite Office program and press Alt+F11.)
The behavior of the Visual Basic Editor is controlled by choosing Tools, Options and clicking the Editor tab. In particular, consider selecting the Require Variable Declaration check box. That will protect you from the single most common source of programming errors—misspellings.
If you do a lot of VBA programming, do yourself a favor and take advantage of the Windows support for multiple monitors. That way, you can keep the Visual Basic Editor window open on one monitor and view the current Office application on the other monitor. If you have only a single screen to work with, arrange your windows so that the application is in the top half of the screen and the Visual Basic Editor is in the bottom half. In either of these configurations, you can step through your program, keeping track of the active command in the Visual Basic Editor window, while watching the effects of your program in the top window.
As you become more proficient, you might want to add the Immediate Window (choose View, Immediate Window) so you can change variable values as the program runs and test unfamiliar VBA commands. You might also want to get rid of the Properties window (in the lower-left corner; View, Properties Window) if you won’t be working with custom-built dialog boxes.
Even if you’re new to programming and have only just begun writing your first VBA programs, you should always keep several tips in mind:
18.116.63.5