Chapter 28. Working with Macros in Word 2010

MENTION the word macro at a dinner party, and folks automatically assume you’re a Word expert (well...OK, maybe at a dinner party where the guests spend way too much time on their computers). But in reality, a macro can be a very simple set of formatting choices (like “indent this and italicize it”) or a complex operation that helps automate common procedures that you use often. Although the behind-the-scenes operation of a macro comes from instructions written in the Microsoft Visual Basic for Applications (VBA) programming language, you don’t have to be a programmer to write a macro. You can simply turn on the macro recording tool and let Word keep track of your operations while you complete the steps you want to include in the macro. You can then play back the macro whenever you want to perform those steps, and Word takes care of the process for you. You might create a macro to perform the following chores:

  • Speed up routine editing and formatting, such as using Find and Replace to clean up data copied from another source that contains manual line breaks and multiple paragraph marks.

  • Automate a complex series of tasks—for example, inserting a table with a specific size, table style, and certain table options (such as including a total row and banded columns).

  • Make an option in a dialog box more accessible, such as turning on and off the display of text boundaries.

  • Work around various limitations in Word, such as inserting a static date (one that does not update to the current system date) with a single click or keyboard shortcut.

  • Combine several repetitive tasks, such as switching to a specific document view, modifying the Zoom Level, and setting other view options.

If the idea of speeding up cumbersome tasks with a simple click of a button or keyboard shortcut is appealing, then read on. You do not need any previous programming knowledge to benefit from this chapter. However, you do need to be familiar with the content contained in this book, or at least be familiar with those areas in which you want to automate specific tasks.

This chapter covers the basic fundamentals of macros by showing you how to automate several of the tasks previously listed. We’ll start by using the Macro Recorder to create a few macros, cover some simple editing tasks, and then take a look at sharing macros with others (either ones you create or those that you obtain from someone else).

Note

Full exploration of macros and VBA is beyond the scope of this chapter—entire books are dedicated to this subject. Those who want to learn more will find a list of recommendations in the section titled What’s Next?.

A Bit About VBA and Macros

When you start working with macros, understanding a few concepts and some terminology is helpful, even if you do not plan to go beyond recording macros and simple editing. For starters, Visual Basic for Applications, or VBA, is a subset of Microsoft Visual Basic. The primary distinction between the two is that VBA is dependent on a host application, such as Word. This means that if you share macros created in Word with other users, they must also have Word installed to use them.

A macro is actually a VBA procedure, and the terms are used interchangeably. A procedure is a series of statements, or actions, that are grouped together to form one specific set of instructions that is associated with a specific name, or what is referred to as a macro.

Macros can be saved in macro-enabled documents or templates. When a document or template contains macros, they are contained in a specific portion of the file called a VBA Project (also known as a project). A VBA Project stores objects, such as a module, and a module stores macros. If this seems confusing, consider how documents are stored: they are stored on a specific drive (VBA Project), they are placed in a folder (module), and they are assigned a name (macro).

When you create a template that contains macros, documents that are attached to the template are able to use macros stored in the template, and you can access the template’s VBA Project through the document. This means you can modify and create new macros in the attached template without actually opening the template in Word. However, like most features, the default behavior can be changed, and you can disable the editing capability, which is discussed in the section titled Protecting Your Macros.

Saving Macro-Enabled Documents and Templates

A document containing macros must be saved using the Word Macro-Enabled Document file type (.docm). Templates containing macros must be saved using the Word Macro-Enabled Template file type (.dotm). If you save a document or template using the macro free file types, Word Documents (.docx) or Word Templates (.dotx), any macros contained in the files will be removed. If you inadvertently try to use a macro-free file type to save a document or template that contains macros, a message box appears, alerting you that your VBA project cannot be saved in a macro-free document.

Caution

If you answer Yes to confirm that you want to save the file using a macro-free file type, the VBA Project will be discarded when you close the file. However, prior to closing, if you modify the VBA Project, such as editing an existing macros or recording a new one (which you will learn how to do in this chapter), you can recover the macros by using a macro-enabled file type to save the document or template.

To save a document or template containing macros, follow these steps:

  1. On the File tab, click Save As.

  2. In the Save As dialog box, display the Save As Type list and select either Word Macro-Enabled Document or Word Macro-Enabled Template.

  3. Provide a File Name and Save In location then click Save.

New macros and changes to existing macros are automatically saved when the document or template is saved.

Note

If you are saving a file in an older file format, such as a Word 97-2003 Document (.doc) or Word 97-2003 Template (.dot), there is no distinction between macro-enabled and macro-free files; macros are saved directly in the file when using these file types.

Additionally, when you save a macro-enabled file, the macros are not converted to XML, they are saved in a binary format. For those interested in knowing more about the document parts that comprise an Office Open XML file, macros are stored in a document part named vbaProject.bin.

Recording a Macro

As mentioned earlier, a macro can be as simple as recording steps, or actions, you already perform in Word—you don’t even need to learn a programming language. You can also use the Macro Recorder to record the bulk of your macro and later edit it in the Visual Basic Editor. This section of the chapter eases you into the realm of macros, starting with how to plan a macro, considerations you should take into account, and using the Macro Recorder to record a macro.

Setup and Planning

Before you start working with macros, make sure the Developer tab is displayed on the Ribbon, shown in Figure 28-1. The Developer tab contains options in the Code group for recording and running macros.

The Developer tab contains access to advanced features, such as macros, but it is not displayed by default.

Figure 28-1. The Developer tab contains access to advanced features, such as macros, but it is not displayed by default.

Tip

To display the Developer tab, on the File tab, click Options, and then click Customize Ribbon. In the list on the right, select the Developer check box then click OK.

You also need to check your Macro Security settings and ensure that you are able to allow your macros to run after they are created. To check Macro Security, follow these steps:

  1. On the File tab, click Options, and then click Trust Center.

  2. Click the Trust Center Settings button then click Macros Settings. Your macro security options will display as shown here:

    The Developer tab contains access to advanced features, such as macros, but it is not displayed by default.
  3. Select the option Disable All Macros With Notification if necessary.

    You can use any option except Disable All Macros Without Notification, but Disable All Macros With Notification is the recommended setting.

  4. Select the Message Bar section and verify the option is selected for Show The Message Bar In All Applications When Active Content, Such as ActiveX Controls and Macros, Has Been Blocked.

  5. Click OK to close the Trust Center Settings and then click OK to accept your changes and close Word Options.

If you have not disabled the Message Bar and your Macro Security settings are set to Disable All Macros With Notification, when you open a document or template that contains macros (or open or create a document based on a template that contains macros), the macros are initially disabled. To enable them, click the Options button that appears in the Message Bar. In the Microsoft Office Security Options dialog box, select Enable This Content then click OK.

Note

If you want to disable macros, display the Microsoft Office Security Options dialog box and select Help Protect Me From Unknown Content (Recommended), as opposed to closing the Message Bar.

Some macros have been known to cause the Message Bar to redisplay when opening or creating new documents, even if the document or template you are opening or creating does not actually contain macros.

Note

For more information on Macro Security, see Chapter 20.

Prior to recording a macro, consider the following:

  • First, practice the steps that you will record. The macro recorder is similar to a video recorder, and every action will be captured, including switching document views and moving your insertion point—even your mistakes are recorded. For macros that will involve several steps, consider jotting down a few notes to help you remember the correct sequence of steps.

  • When you are recording, the mouse cannot be used to select text or move the cursor—you will need to use the keyboard instead. You can review navigation and text selection methods in Chapter 8.

  • If you are creating a macro for a specific template, and the macro will navigate to specific locations in documents based on the template, then consider adding Bookmarks in the template. Then in your macro you can use Go To (F5) to navigate to the correct location. For more on using Bookmarks, see Chapter 8.

For our first simple macro example, we will insert the current system date as a static date in your document. If you’ve ever inserted a date by using the Date And Time dialog box, more than likely practice is not necessary. To use the Macro Recorder and record a new macro, follow these steps:

  1. Create a new document and use the Word Macro-Enabled Document file type (as described in the preceding section) to save it in My Documents as MyFirstMacros.docm.

  2. Navigate to the Developer tab and in the Code group, click Record Macro. This will display the Record Macro dialog box shown in Figure 28-2.

    The Record Macro dialog box provides all of the options for creating a macro, including assigning the macro to a button or keyboard shortcut.

    Figure 28-2. The Record Macro dialog box provides all of the options for creating a macro, including assigning the macro to a button or keyboard shortcut.

  3. In the Macro Name text box, type a name for your macro, such as inserttodaysdate.

    Note

    Naming a macro is similar to naming a document, and you should use descriptive names. Macro names are limited to 80 characters when using the Record Macro dialog box; they must start with a letter; they can include letters and numbers; and they can’t include most special characters or spaces (you can use the underscore character to represent a space).

    If you give your macro the same name as an existing macro, you will be prompted to replace the existing macro. You can click Yes to replace the macro, click No to return to the Record Macro dialog box and modify the name, or click Cancel to cancel the macro recording.

    Additionally, if your macro uses the same name as a built-in command, your macro will replace the built-in functionality. For more on viewing built-in Word commands or replacing them with your own macro, see the Inside Out tip titled Inside Out: Viewing Word Commands.

  4. In the Store Macro In list, select MyFirstMacros.docm.

    If you save the macros in Normal.dotm, they will be available to all documents. However, it’s recommended that you initially save your macros in a separate document during the learning stages.

  5. Provide a description for your macro, if desired, and then click OK to begin recording.

    Your mouse pointer displays with a cassette tab, indicating that your actions are being recorded. The Record Macro button on the Developer tab will change to a Stop Recording button (you’ll use this button when you are finished recording your macro).

    Tip

    While you are recording a macro, you can click the Pause Recording button to perform any steps you do not want to record in your macro. When you are finished, click the Pause Recording button again to resume recording.

  6. On the Insert tab, in the Text group, click Date & Time to display the Date & Time dialog box.

  7. Select your preferred date format, clear the Update Automatically option if necessary, and then click OK.

    Do not add any additional steps unless you want your macro to contain other actions. For example, if you want to start a new paragraph after inserting the date, press Enter.

  8. On the Developer tab, click Stop Recording in the Code group.

  9. Test the macro.

    To test your macro, delete the previously inserted date, then on the Developer tab in the Code group, click Macros (or press Alt+F8) in the Macros dialog box, click InsertTodaysDate, and then click Run. The current system date should be inserted in your document at your insertion point.

Tip

For a one-click method to start and stop recording a macro, right-click the customizable status bar then click Macro Recording. Then, to access the Record Macro dialog box, click the Record Macro button on the status bar. Like the Record Macro button on the Developer tab, the Record Macro button will change to Stop Recording when you are recording a macro.

You might be wondering how navigating to the Developer tab, clicking the Macros button, selecting the macro from the list, and clicking Run can save time. You are correct in thinking it’s not necessarily any faster than inserting a date by using the Date & Time dialog box. For simple macros, the time-saving steps occur when you add the macro to your Quick Access Toolbar or assign it to a keyboard shortcut. Accomplishing both of these tasks is covered in the next section.

Running Macros

As you might have gathered in the previous section, using the Macros dialog box is not the most efficient way to run your macros. Ideally, running a macro should be as simple as clicking a button or pressing a keyboard shortcut. This section of the chapter covers how to add a macro to your Quick Access Toolbar, how to assign a keyboard shortcut to your macro, and how to use specifically named macros that will automatically run without being assigned to a button or keyboard shortcut.

Macros can also be added to the Ribbon. However, doing so requires some XML knowledge, and this capability isn’t found within the Word application. For more information on customizing the Ribbon, see “How to: Customize the Ribbon” in MSDN’s Developer center (http://msdn.microsoft.com/en-us/library/aa942954(VS.80).aspx).

Adding a Macro to the Quick Access Toolbar

As you might know from reading previous chapters, the Quick Access Toolbar can be easily customized with commands that are not on the Ribbon or with commands you prefer to have visible at all times. The Quick Access Toolbar can also be used as a one-click method for running macros. To add the previously created macro to your Quick Access Toolbar, follow these steps:

  1. Open MyFirstMacros.docm, if it’s not already open.

  2. Click the More button at the end of the Quick Access Toolbar.

  3. Click More Commands to open Word Options with the Customize section displayed.

  4. In the Choose Commands From list, select Macros.

    The macro, inserttodaysdate, will appear as Project.NewMacros.inserttodaysdate in the list of commands, as shown in Figure 28-3.

    Click the macro you want to add to the Quick Access Toolbar, click Add, and and then click OK.

    Figure 28-3. Click the macro you want to add to the Quick Access Toolbar, click Add, and and then click OK.

    Note

    The name of the macro, Project.NewMacros.inserttodaysdate, provides the location where the macro is stored, as previously discussed in the section titled A Bit About VBA and Macros. Project is the name of the VBA Project, NewMacros is the name of the module (which is automatically created when you use the Macro Recorder), and inserttodaysdate is the name of the macro.

  5. In the Customize Quick Access Toolbar list, select For MyFirstMacros.docm.

    You should store your Quick Access Toolbar customizations in the same location as your macro. Use For All Documents (Default) if the macro is stored in your Normal template.

    Note

    The list of current Quick Access Toolbar commands will disappear after you select For MyFirstMacros.docm from the Customize Quick Access Toolbar list. When you customize the Quick Access Toolbar for a specific document or template, the customizations will merge with the commands listed under For All Documents (Default) when the document, template, or a document attached to the template is opened.

  6. Select the macro (if it isn’t already selected) and then click Add to add it to your Quick Access Toolbar.

  7. Click the Modify button to open the Modify Button dialog box, shown here.

    Click the macro you want to add to the Quick Access Toolbar, click Add, and and then click OK.
  8. Select a symbol, or icon, for your macro, such as the Appointment Book icon. Then to modify the ScreenTip, change the Display Name for your macro. For example, type Insert the current date.

  9. Click OK to accept the changes in the Modify Button dialog box, and then click OK to accept the Quick Access Toolbar customizations.

    Your custom macro button appears on your Quick Access Toolbar, as shown here.

    Click the macro you want to add to the Quick Access Toolbar, click Add, and and then click OK.

When you close MyFirstMacros.docm, the custom macro button will be removed from the Quick Access Toolbar. You can also use the macros you created and stored in MyFirstMacros.docm with other documents by using the fileas a global template. For more on working with templates, see Chapter 4.

Assigning a Keyboard Shortcut to a Macro

In addition to adding your macros to your Quick Access Toolbar, you can assign keyboard shortcuts to your macros. The initial steps are similar to the steps used to add a macro to your Quick Access Toolbar. First, open MyFirstMacros.docm, display Word Options, and then click the Customize Ribbon tab. Then follow these steps:

  1. Click the Customize button to display the Customize Keyboard dialog box, as shown in Figure 28-4.

    Use the Customize Keyboard dialog box to create keyboard shortcuts for your macros.

    Figure 28-4. Use the Customize Keyboard dialog box to create keyboard shortcuts for your macros.

  2. In the Categories section, scroll to the bottom of the list then select Macros.

  3. Click the Save Changes In list and select MyFirstMacros.docm.

    InsertTodaysDate should now be visible in the Macros list, as shown in Figure 28-4.

  4. Place your cursor in the Press New Shortcut Key text box, and then press your desired keyboard shortcut on the keyboard, such as Ctrl+Shift+D.

    Note that Ctrl+Shift+D is a built-in keyboard shortcut and is assigned to Double Underline. If you use this keyboard shortcut to add double underline, select an alternate keyboard shortcut for your new macro and press those keys on the keyboard instead.

    Caution

    Depending on which combination you use, custom keyboard shortcuts may override built-in keyboard shortcuts, so be sure to check if the shortcut you want to use is available (or you don’t mind overwriting the built-in shortcut). You can check to see if your intended keyboard shortcut is currently assigned by looking below the Current Keys list after the keys you want to use are pressed.

  5. Click Assign then click OK to assign the keyboard shortcut. Close the Customize Keyboard dialog box then click OK to close Word Options.

    Tip

    After you are familiar with the steps for adding a macro to your Quick Access Toolbar, or assigning a keyboard shortcut to a macro, you can select one of these options when you start recording a new macro. In the Record Macro dialog box (shown in Figure 28-2), click the Button option to add the macro to your Quick Access Toolbar or click the Keyboard button to assign a keyboard shortcut.

Running a Macro Automatically

Most macros require you to click a button or use a keyboard shortcut to run the macro. However, a few macros will run automatically when a specific event occurs, such as when Word starts; when you open, close, or create a document; and when you exit Word.

A macro must be stored in your Normal template in order for it to run automatically when a document is created, opened, or closed. It must also use a macro name listed in Table 28-1, which also describes the events associated with the macros.

Table 28-1. List of Automatic Macros

Auto Macro Name

Description

AutoExec

Runs when Word starts

AutoOpen

Runs each time a document is opened

AutoNew

Run each time a document is created

AutoClose

Runs each time a document is closed

AutoExit

Runs when Word exits

Note

You can use other events, called Document-Level Events, to cause a macro to run automatically. However, they are out of the scope of this chapter.

For our automatic macro example, we’ll take a look at another task listed at the beginning of this chapter—combining several repetitive procedures, such as switching to a specific document view and modifying the Zoom Level.

Word users often need to open documents in a certain view and at a specified Zoom Level. In recent versions, if you create a new document based on the Normal template, Word uses the current view settings and Zoom Level, as opposed to older versions that use the settings stored in the Normal template. But you still can’t open documents in certain views and at specified Zoom Levels when you’re accessing previously created documents. However, a simple macro and the power of VBA gives you the tools to specify which view, Zoom Level, and any other viewing options will be applied. And these settings will be in effect for every document you open automatically using a macro named AutoOpen. To create the macro, use the following steps:

  1. On the Developer tab, click Record Macro.

  2. In the Macro Name text box, type AutoOpen. From the Store Macro In list, select All Documents (Normal.dotm)—if it isn’t already selected—as shown here.

    List of Automatic Macros
  3. Click OK to start recording. In the View options (on your status bar), click your desired view.

    Even if it’s the view you are currently using, the action will still be recorded.

  4. Click Zoom Level to open the Zoom dialog box and select your desired Zoom settings. (Changes made using the Zoom Slider are not recorded.)

  5. Make any other desired changes to your view then click Stop Recording.

  6. Test your macro by opening a document.

To fully test your macro, create a new document, switch to another view, change your view settings, and make another editing change, such as typing a space in the empty document and then pressing Backspace to delete the space. Then, save the document, close it, and reopen it.

Note

Why type a space just to delete it? Because altering your view or zoom settings by itself does not qualify as a change to the document. An action must appear in your Undo list for Word to actually save changes to your view.

Alternatively, you can verify your recorded macro by viewing the recorded code in the Visual Basic Editor, which is covered in the next section.

Editing Macros

Depending on the macro you record, sometimes you might need to edit and refine the results of the recorded macro. The beauty of VBA is that the syntax is fairly easy to read and comprehend. If you are interested in learning more about macros, viewing recorded code is a good place to start. For our editing example, we’ll take a look at another task discussed at the beginning of this chapter—making an option in a dialog box more accessible. This example will clear the Show Picture Placeholders option, which speeds scrolling through a document that contains a large number of inline images in Print Layout view, and we’ll make a simple edit to the macro so that each time you run it, the option will toggle on or off depending on its current state. To get started, follow these steps:

  1. Open MyFirstMacros.docm, navigate to the Developer tab, and click Record Macro.

  2. In the Macro Name text box, type TogglePicturePlaceholders. From the Store Macro In list, select MyFirstMacros.docm, add a description if desired, and then click OK to start recording.

  3. On the File tab, click Options then click Advanced.

  4. Select the Show Picture Placeholders option, which is located under the Show Document Content heading.

  5. Click OK to accept the change and close Word Options. (If the option is already selected, clear it; all we need is to have a change recorded.)

  6. On the Developer tab, click Stop Recording then click Macros.

  7. Select TogglePicturePlaceholders in the list of macros then click Edit.

    The Visual Basic Editor will open, and you will see both recorded macros, as shown in Figure 28-5.

    The InsertTodaysDate and TogglePicturePlaceholders macros shown in the Visual Basic Editor.

    Figure 28-5. The InsertTodaysDate and TogglePicturePlaceholders macros shown in the Visual Basic Editor.

Prior to editing, take a closer look at the macro you just recorded (you will take a closer look at the Visual Basic Editor in the next section) and note the following:

  • Each macro, or procedure, begins with the statement Sub, which stands for subroutine, and ends with End Sub. The text in between these lines is the code that is executed when you run the macro.

    Note

    Another set of paired statements you’ll see in recorded macros is Function and End Function. This structure groups related statements together, such as a group of options in a dialog box. And like Sub and End Sub, the group begins with the statement With and ends with the statement End With.

  • The green text, preceded by an apostrophe, is called Comment Text. As the name implies, this text is used for purposes of notes and documentation, which you can use to identify the macro, describe what it does, or give instructions as to its use. Comment text is ignored when the macro runs. You can safely delete these lines if you want. You can add an apostrophe anywhere in the macro, but any text that follows it (until the end of the current line) will be treated as Comment Text.

  • ShowPicturePlaceholders is set to a True/False (Boolean) value, as are all check boxes. True means the check box is selected, and False means the check box is cleared.

As mentioned earlier in this chapter, you do not need to know VBA to follow the syntax. Take the statement in the TogglePicturePlaceholders macro, for example. In the active window, the view option—Show Picture Placeholders—is selected, or turned on.

Because the Show Picture Placeholders option is a True/False (Boolean) value, to use the macro to toggle the view of Picture Placeholders, all we need to do is set Show Picture Placeholders to the reverse of its current value. To make the edit, follow these steps:

  1. Locate the TogglePicturePlaceholders macro. It should appear similar to the code here.

    The InsertTodaysDate and TogglePicturePlaceholders macros shown in the Visual Basic Editor.
  2. Select ActiveWindow.View.ShowPicturePlaceHolders and copy it.

  3. Replace True at the end of the line with Not and then paste the previously copied statement. The revised statement is shown here.

    The InsertTodaysDate and TogglePicturePlaceholders macros shown in the Visual Basic Editor.

    Note

    When you reference only an option (in VBA this is called a Property), as opposed to changing the value of the option, the current value of the option is returned. The Not operator reverses the current value, and if the current value is True, the Not operator toggles the value to change to False, and vice-versa.

  4. From the File menu, click Close And Return To Microsoft Word.

  5. Assign the macro to your Quick Access Toolbar by using the steps provided in the section titled Adding a Macro to the Quick Access Toolbar.

  6. Verify that you are using Print Layout view, insert an inline image (Text Wrapping is set to Inline With Text) in your document, and try out your new macro. The macro should toggle between viewing empty placeholders and viewing the image in the document.

The Visual Basic Editor

The Visual Basic Editor is a powerful automation tool. As mentioned earlier, covering all aspects of VBA and the Visual Basic Editor is beyond the scope of this chapter; entire books are dedicated to this subject alone. This section will discuss the elements of the Visual Basic Editor, many of which are used in this chapter. A diagram of the Visual Basic Editor is provided in Figure 28-6, and Table 28-2 describes each element in the diagram.

The Visual Basic Editor is the central hub for all of your macro needs; you can use it for creating, editing, and deleting macros.

Figure 28-6. The Visual Basic Editor is the central hub for all of your macro needs; you can use it for creating, editing, and deleting macros.

Table 28-2. The Visual Basic Editor

Element or term

Description

Project Explorer

Provides access to all available VBA Projects including open documents, templates, Normal template, loaded global templates, and an attached document template. The name of the file that contains the project is enclosed in parentheses next to the name of the project. Double-click a VBA Project—or an object, such as a module—in the VBA Project to open it and view the contents. If the Project Explorer is closed, from the View menu, click Project Explorer or press Ctrl+R.

Properties Pane

Displays properties of the selected object in the Project Explorer. Can be used to change the name of a module or project. The Properties pane is primarily used for other types of objects available in VBA, such as a UserForm, which is also called a dialog box. If the Properties pane is closed, from the View menu, click Properties Window or press F4.

Module

Contains a collection of macros. Each macro in the module is visually separated by a horizontal line.

Procedure View

Displays only the active macro in the module.

Full Module View

Displays all macros in the module.

Procedure List

Provides quick navigation between macros in the module. To quickly jump to another macro, select the macro from the Procedure List. This option is useful if you have several lengthy macros, or if you are viewing the module in Procedure view.

Additional Macro Options

As you become more familiar with using macros, you might find that you have macros that could use a more descriptive name, macros you do not want (it’s not unusual to have several failed macro recording attempts when you are in the learning stages), and macros that you want to use in other documents or templates. How to deal with each of these situations is covered in this section.

Renaming a Macro, Module, or Project

The easiest way to rename a macro, module, or project is to use the Visual Basic Editor. Note that the previously provided rules for naming macros still apply—names must start with a letter and they cannot contain spaces or special characters, except for the underscore character (which you can use in place of spaces). An exception to the rules previously provided is the character limit. You can use up to 255 characters in the macro name if you are naming or renaming it in the Visual Basic Editor; names for modules and VBA Projects are limited to 30 characters. Additionally, similar to documents, macros contained in the same module must have a unique name, and modules in the VBA Project must likewise be uniquely named.

To rename a macro, simply change the name of the macro after the line that begins with Sub.

To rename the module or VBA Project, select the module or VBA Project in the Project Explorer. In the Properties pane, change the name in the (Name) text box.

Caution

If your macro is assigned to a button on your Quick Access Toolbar or a keyboard shortcut, changing the name of the macro, module, or VBA Project will disable the button or keyboard shortcut. You need to remove the disabled button from your Quick Access Toolbar and create it again. For a keyboard shortcut, you will need to reassign the keyboard shortcut to the renamed macro.

Deleting and Exporting Macros and Modules

To delete a macro, you can use one of the following methods:

  • Display the Macros dialog box, click Macros on the Developer tab or press Alt+F8, select the macro in the macros list then click Delete.

  • In the Visual Basic Editor, select the entire macro—starting with the line that begins Sub, through End Sub—and press Delete on the keyboard.

Deleting a macro does not remove the macro from your Quick Access Toolbar (you need to manually remove the button). If you assigned a keyboard shortcut to the macro, no further action is required.

To delete a module, select the module in the Project Explorer. From the File menu, click Remove ModuleName. You will be prompted to export the module before removing it, as shown in Figure 28-7.

You are asked whether you want to export a macro before removing it.

Figure 28-7. You are asked whether you want to export a macro before removing it.

If you click Yes, the Export File dialog box will display, in which you can provide a name and location for your exported module, as shown in Figure 28-8.

Use the Export File dialog box to export your module and save it prior to deleting and removing the module from your VBA Project.

Figure 28-8. Use the Export File dialog box to export your module and save it prior to deleting and removing the module from your VBA Project.

You can use standard file naming rules for your exported module because it will be saved as an external file. Note that the file uses a .bas file extension. However, it is nothing more than a text file, and you can use Notepad to open it and view the contents.

Tip

If you want to delete an entire VBA Project, save the document or template in a macro-free file format, such as Word Document (.docx) or Word Template (.dotx). Doing so will remove the entire VBA Project from the document or template. If you want to preserve the macros, export the modules from the VBA Project prior to saving the file in the macro-free file format.

Importing Macros and Modules

There might be a time when you want to add your exported module back to the VBA Project, or import a module for use in another VBA Project. To import a previously exported module, in the Project Explorer, select the VBA Project to which you want to add the module. Then, from the File menu, click Import File. The Import File dialog box will display (it is similar to the Export File dialog box that is shown in Figure 28-8). To import the module, navigate to your saved module, select it, and then click Open. The module should now be added to your VBA Project.

If you want to use a single macro from the exported file, you can use Notepad to open the previously saved file, copy the macro, and paste it in any module. Alternatively, you can import the entire module and delete any macros you do not want to keep.

Another way to share macros between documents and templates is to open both files and then copy and paste the macros between the modules, just as you would copy and paste content between documents.

Note

You can also use the Organizer—available in the Macros dialog box on the Developer tab—to copy, rename, and delete modules. However, if you are comfortable using the Visual Basic Editor, you will find it is more flexible than the Organizer because the Organizer is limited to working only with modules and not individual macros. For more information on using the Organizer, see Chapter 4.

Protecting Your Macros

You can protect your macros from alteration by assigning a password to your VBA Project. To do so, follow these steps:

  1. Display the Visual Basic Editor (click the Visual Basic button on the Developer tab or press Alt+F11).

  2. From the Tools menu, click Project Properties.

  3. Click the Protection tab, as shown in the following image, then select Lock Project For Viewing.

    Protecting Your Macros
  4. In the Password text box, type a password and then type it again in the Confirmation text box. (The Password and Confirmation are both required.)

Once your VBA Project is protected, you will be prompted to enter the password the first time you access it, such as when you double-click the VBA Project in the Project Explorer to open it, or use the Macros dialog box to edit or delete the macro after the file has been closed and reopened.

As with passwords in general, keep in mind that if you lose the password, you won’t be able to access the VBA Project. Though some password cracking utilities are available, there are no guarantees they will work, and their success depends on the complexity (or more accurately, the simplicity) of the password you used to secure the VBA Project.

Digitally Signing Macros

Macros are digitally signed for a couple of reasons. The primary reason is to provide authentication for the macros when you share them with others. Another reason is so a user can disable all macros except for those that are digitally signed for security reasons. Even if you do not intend to digitally sign your macros, this section of the chapter will still be beneficial to you. You might come into contact with macros that have been digitally signed, and the more you know about digital signatures, the more you can make informed decisions when it comes to macro security.

In the tools that came with your version of Microsoft Office 2010, you’ll find a program called SelfCert, a digital signature utility. This utility will help you digitally sign the macros and VBA projects you create, whether you are sharing your macros with others or they are for your own personal use in documents and templates.

Creating a Self-Signed Digital Signature

You can use SelfCert to create a digital signature yourself; it is intended to be used for macros that you use in your personal documents and templates. With a SelfCert digital signature, you can disable all macros except for those that are digitally signed. (For more on security settings, see Chapter 20.)

A digital signature created using SelfCert can be shared with others. However, it relies more on trust than true authentication. When SelfCert is used to create a digital signature, no authentication is required, and any name can be used for the digital signature. As you have likely surmised, anyone can easily create a digital signature using someone else’s name or a corporation’s name. It’s for this reason that an authenticated digital signature can be provided only by a Certificate Authority.

Third-Party Digital Signature

If you are sharing your macro with others, you need to obtain a third-party digital signature for code signing to ensure that the macro is truly secure. A digital signature for code signing is issued by a third party which is called a certificate authority (CA). This third party validates the identity of the applicant for the digital signature before it is assigned and later keeps track of the digital signature to determine if it has expired or been revoked. Microsoft maintains a list of all third-party certification authorities, and you can view or download the list by visiting this Microsoft Office site at http://support.microsoft.com/kb/931125.

Caution

If the other user does not have your digital signature when you use SelfCert.exe to digitally sign a VBA Project and they later share your macros with others, they will be prevented from enabling the macros. For more information, see the Troubleshooting tip titled Troubleshooting.

To create a digital signature using SelfCert, follow these steps:

  1. Click the Start button then click All Programs. Choose Microsoft Office and point to Microsoft Office 2010 Tools.

  2. Click Digital Certificate for VBA Projects.

    The Create Digital Certificate dialog box appears, as shown in Figure 28-9.

    The Create Digital Signature dialog box is where you create a digital signature for your personal use.

    Figure 28-9. The Create Digital Signature dialog box is where you create a digital signature for your personal use.

  3. In the Your Certificate’s Name text box, type a name for your digital certificate then click OK.

Your digital signature has been created, and you can now use it to sign your macros for personal use.

Digitally Signing a VBA Project

When you digitally sign your macros, you are actually providing a digital signature for the VBA Project, which as previously mentioned is the primary container for your macros. After you have obtained a digital signature or created one for your personal use, you can digitally sign your VBA Project as follows:

  1. Open the document or template you want to sign.

  2. On the Developer tab, click Visual Basic or press Alt+F11.

  3. In Project Explorer, select your VBA Project.

  4. From the Tools menu, click Digital Signature to display the Digital Signature dialog box, shown here:

    Digitally Signing a VBA Project
  5. Click Choose, select your digital signature from the Select Certificate dialog box, and then click OK.

    The digital certificate name will display in the Digital Signature dialog box.

  6. Click OK to digitally sign your VBA Project and close the Digital Signature dialog box.

Note

If you previously selected a digital signature, you do not need to click Choose and select the digital signature again. To use the current digital signature, click OK in the Digital Signature dialog box.

After your VBA Project has been digitally signed, depending on the type of digital signature you used, you might need to digitally sign the VBA Project again if you create new macros or modify previously created macros.

What’s Next?

Now that you know the information in this chapter, you might be amazed at how much you can do using the Macro Recorder and a little knowledge about the Visual Basic Editor.

If this chapter has whet your appetite for macro knowledge, several resources are available to help you learn more. Here are two recommendations:

  • The Word MVP Site (www.mvps.org/word). This Web site contains answers to frequently asked Word questions and provides tutorials and articles for using VBA in Word.

  • The Microsoft Developers Network (MSDN; msdn.microsoft.com/en-us/office/aa905482.aspx). This Web site isn’t strictly for developers; it includes topics for beginners, too. It also contains a wealth of sample code that you can copy and paste in your VBA Projects. Some samples can be used as-is, whereas others might need to be tweaked to fit your needs.

As you continue to explore and expand your experience with Word 2010, I hope you’ll enjoy the creative, collaborative, and flexible ways in which you can create projects large and small. Be sure to check Office.com from time to time for new articles, templates, and tools, and if you have questions or curiosities about Word features you rarely use, visit the Word Solution Center (http://support.microsoft.com/ph/11377#tab0) to get the latest fixes, product guides, and how-to advice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset