Getting Started with VBA in Word 2010

Summary:  Introduces new programmers to using Visual Basic for Applications (VBA) programming to extend Microsoft Word 2010. This topic summarizes the VBA language, instructions about how to access VBA in Word 2010, a detailed solution to a real-world Word VBA programming problem, and tips about how to program and debugging.

Applies to: Office 2010 | Open XML | Visual Studio Tools for Microsoft Office | Word 2007 | Word 2010

In this article
What is a Macro, Why Would I Want One, and How Can I Create One?
Part 2: Writing More Complex Macros
Conclusion
Additional Resources
About the Author

Published:  April 2010

Provided by: Shauna Kelly

Contents

  • Part 1: An End-to-End Macro Example

  • Part 2: Writing More Complex Macros

  • Conclusion

  • Additional Resources

  • About the Author

What is a Macro, Why Would I Want One, and How Can I Create One?

A macro enables you to put Word on autopilot.

It can be frustrating to perform a frequent task in Word if you have to use a long sequence of mouse clicks or key strokes every time that you perform the task. When you write a macro, you can bundle up a collection of commands and instruct Word to start them with only one click or one keystroke.

This article assumes that you are a skilled user of Word. It also does not assume that you know anything about computer programming or software development.

This article is in two parts:

  1. The first part of the article describes an end-to-end example: how to write a simple macro, where you can save it, how to create a button on the Quick Access Toolbar or create a keyboard shortcut to run the macro, and how to copy that macro to another computer (so you can use it at home and at work, or so you can share it with a colleague). That will give you a simple example.

  2. The second part of the article examines macros in detail: how to write more complex macros and how to ensure that your macro actually does what you want and does not create errors or problems.

Part 1: An End-to-End Macro Example

One purpose of macros is to enable you to perform a task with one click or one keystroke.

I often create documents that contain hyperlinks to Web sites. By default, Word requires me to follow, or open, a hyperlink, by pressing CTRL while clicking the hyperlink. The following image shows the default option for following a hyperlink.

Figure 1. Press CTRL and click the hyperlink to follow it

Default option for following a hyperlink

The following image shows the alternative option for following a hyperlink by clicking it.

Figure 2. Click to follow hyperlink

Alternative option for following a hyperlink

Sometimes that is useful, but sometimes I prefer to follow a hyperlink by clicking it (Figure 2). I may configure that setting many times a day. To do that, click the File button, and under Help, I click Options. In the Word Options dialog, I click Advanced, and then under Editing options, I select (or clear) Use CTRL+Click to follow hyperlink and then click OK. Doing that sequence of mouse clicks repeatedly is frustrating. I want to be able to click one time to configure this setting.

This section describes how to create a simple macro to toggle between using CTRL+Click and only clicking a hyperlink. To create this macro, you will learn how to:

  • Create a Word Macro-Enabled Template file (.dotm) to store your macro and save it in the Word Startup folder.

  • Open and use the Visual Basic Editor, which is part of Word.

  • Write a macro in the Visual Basic Editor.

  • Test your macro.

  • Create a button on the Quick Access Toolbar to run your macro.

  • Create a keyboard shortcut to run your macro.

  • Save your file, load it as an add-in and, if you need to, share it with a colleague, or use it on another computer.

This section describes each step.

Creating a File to Hold Your Macro

Before you start to write a macro, think about how and where you want to save it.

Word lets you save macros in two Word file types: a Word Macro-Enabled Document file (.docm) and a Word Macro-Enabled Template file (.dotm). It is not a recommended practice to store macros in a document. Macros are usually stored in a Word Macro-Enabled Template file (.dotm).

It is possible to save macros in the Normal Template (Normal.dotm), but that makes it difficult to organize or share your macros. It is usually better to create your own file and store your macros there.

Where to save your template file depends on how you want to use the macros. You must decide whether you want to use your macros with all the documents that you might work on or only with some documents.

For example, you may create a template for monthly sales reports, and you may have macros to format those reports. In this case, save the template file in the User Templates folder, and use that template as the basis for new documents. (To verify the User Templates folder, click the File tab, and then click Options. In the Word Options dialog, click Advanced, and then click the File Locations button.) If a macro is stored in a template, then only documents attached to that template can access the macro. Other documents will be unable to "see" the macro.

In this article, you will create macros that can be used by any document. To do that, you will create a Macro-Enabled Template file. First, close any Word files that you have open. To create the new file to hold your macros, click the File button, click New, and then click My Templates. In the New dialog box, select the Template option button and then click OK. Save the file as a Macro-Enabled Template file that is named MyWordTools.dotm in the Word Startup folder. (To verify the Word Startup folder, click the File tab, and then click Options. In the Word Options dialog, click Advanced, and then click the File Locations button.)

Using the Visual Basic Editor

Word macros are written in a programming language called Visual Basic for Applications (VBA).

You write macros in a part of Word that most users never see: the Visual Basic Editor (the VBE). Open the VBE by using any one of the following methods:

  • Press the keyboard shortcut, Alt+F11

  • Click the Visual Basic button on the Developer tab. To do that, click the File tab, and then click Options. On the Word Options dialog box, click Customize Ribbon. In the right side of the dialog box, select the Developer tab. Click OK to return to your document, and then on the Developer tab, click the Visual Basic button.

  • Add the Visual Basic command to the Quick Access Toolbar.

Before you start to use the VBE, on the Tools menu, click Options. In the Options dialog box, on the Editor tab, ensure that all the check boxes are selected.

In the upper-left side of the VBE you will see the Project Explorer. This shows all files that are currently open in Word. Expect to see Normal (which refers to Normal.dotm) and MyWordTools (the new file that you just created).

The following image shows the MyWordTools project in the Visual Basic Editor Project Explorer.

Figure 3. Visual Basic Editor Project Explorer

Visual Basic Editor Project Explorer

Within your file, macros are stored in Modules. To add a module to your file, in the Project Explorer, select the MyWordTools file (Figure 3). On the Insert menu, click Module. When you add a module to your file, you will see the module added in the Project Explorer and in the Properties Window under it (Figure 4). You can rename a module using the Properties Window. Leave the name as Module1.

The following image shows Module1 in the Visual Basic Editor Project Explorer.

Figure 4. Visual Basic Editor Project Explorer

Visual Basic Editor properties window

Finally, you will see that the entry for your file is named TemplateProject. Although it is not necessary, it is recommended that you give it a more descriptive name. To do that, right-click the entry for the MyWordTools file, and then click TemplateProject Properties on the shortcut menu (Figure 5).

The following image shows the TemplateProject Properties… menu item

Figure 5. Properties menu item

Selecting project properties pop-up menu item

In the Template Project-Project Properties dialog, change the Project name to MyWordTools.

Writing Your Macro

The large white area on the right in the VBE is where you write the code of your macro. If you cannot see it, on the View menu, click Code to see the code window. Word automatically inserts the statement Option Explicit at the top of the code window. Do not delete this.

You want a macro to toggle between the two possible settings, in Word, for following a hyperlink. It will work like other buttons that toggle a setting in Word. The Bold button on the Home tab, for example, will text bold if it is not bold and make text not bold text if it is currently bold.

Copy and paste the following macro code example into the code window.

    Sub ToggleHyperlinkCtrlClick()
        Options.CtrlClickHyperlinkToOpen = Not Options.CtrlClickHyperlinkToOpen
    End Sub

This is a short macro named ToggleHyperlinkCtrlClick, and it only has one line of code. The one line of code in our macro means "Change the Word option that controls whether I have to use CTRL+Click to open a hyperlink to the opposite of its current setting, that is, to Not its current setting" (Figure 6).

The following image shows a line-by-line explanation of the ToggleHyperLinkCtrlClick method.

Figure 6. Explanation of the ToggleHyperLinkCtrlClick method

Code in Visual Basic Editor code window

Testing Your Macro

To test your macro, use the following procedure.

To test the macro

  1. Arrange the Word and VBE windows so you can see them side by side.

  2. Click the main Word window. Type several paragraphs of text into the MyWordTools.dotm document. Include some hyperlinks in your text (Figure 7).

    The following image shows the MyWordTools document and the ToggleHyperLinkCtrlClick code in the VBE side by side.

    Figure 7. Document and Visual Basic Editor side by side

    Split screen of document and Visual Basic Editor

  3. In the VBE, click anywhere within your macro. To run your macro, on the Run menu, click Run Sub/User Form or press F5.

  4. The setting to follow a hyperlink will be changed. Mouse over a hyperlink in the main Word window to see that the tooltip has changed.

  5. Re-run the macro to toggle the setting.

You can also run your macro within Word itself. On the View tab, in the Macros group, click the Macros button. Your ToggleHyperlinkCtrlClick macro will be listed in the Macros dialog. To run your macro, click the name of the macro, then click the Run button.

Creating a Button on the Quick Access Toolbar to Run Your Macro

To get one-click access to your macro, you can add a button to the Quick Access Toolbar. To do that, use the following procedure.

To create a button on the Quick Access Toolbar

  1. Right-click the Quick Access Toolbar and then click Customize Quick Access Toolbar on the shortcut menu.

  2. Under Customize the Quick Access Toolbar, in the Choose commands from list, select Macros.

  3. In the Customize Quick Access Toolbar list, select MyWordTools.dotm. (You must select MyWordTools.dotm so that Word will save the button on the Quick Access Toolbar in the MyWordTools.dotm file. Only then will the button be available when you copy that file to another computer.)

  4. Select the ToggleHyperlinkCtrlClick macro and then click Add.

  5. Click the Modify button to select a symbol and change the name to ToggleHyperlinkCtrlClick.

You can now run your macro at any time by clicking the new button on the Quick Access Toolbar.

Creating a Keyboard Shortcut to Run Your Macro

You can also create a keyboard shortcut to run your macro. To do that, use the following procedure.

To create a keyboard shortcut to run the macro

  1. Right-click the Quick Access Toolbar, and then click Customize the Ribbon on the shortcut menu. Next to Keyboard shortcuts, click the Customize button.

    The following image shows the Customize Keyboard dialog box

    Figure 8. Customize Keyboard dialog box

    Customize Keyboard dialog box

  2. In the Customize Keyboard dialog box (Figure 8), you must:

    1. In the Categories list, select Macros.

    2. In the Macros list, click your macro name.

    3. Click in the Press new shortcut key box, and type the keyboard shortcut that you want to use. I used Alt+H, which I can remember because this toggles the setting for Hyperlinks. The dialog box also tells me that this shortcut is currently unassigned, so I will not interfere with an existing keyboard shortcut.

    4. In the Save changes in list, select MyWordTools.dotm. (You must select MyWordTools.dotm so that Word will save the keyboard shortcut in the MyWordTools.dotm file. Only then will the button be available when you copy that file to another computer.)

    5. Click Assign.

To run your macro, press Alt+H.

Finishing Up

You have now created a new file to hold your macro (MyWordTools.dotm), added a Module (Module1), created your macro (known as ToggleHyperlinkCtrlClick), created a button on the Quick Access Toolbar to start the macro, and created a keyboard shortcut to start the macro. Now, save the MyWordTools.dotm file (you can do this in the VBE or from the main Word window).

Because you have finished with the VBE, close it and return to Word. To do that, in the VBE, click the File menu and then click Close and Return to Microsoft Word.

To text your macro, click your button on the Quick Access Toolbar. When you confirm that it is working, save and close the file.

Managing and Loading Add-ins

The plan was that this macro should be available regardless of what document that you are working on. However, if you create a new document (use CTRL+N) you will be unable to see your button on the Quick Access Toolbar. There is no way to start your macro.

To make the macro stored in MyWordTools.dotm available to any document that you have open, you must load MyWordTools.dotm as an add-in. (When a .dotm file is used as an add-in it is also known as a ‘global template’.) You can load a .dotm file as an add-in either manually or automatically:

  • To load a .dotm file as an add-in manually, close the.dotm file if it is currently open. On the Developer tab, click the AddIns button. In the Templates and Add-ins dialog, click Add, locate your .dotm file and then click Open.

  • To load a .dotm file as an add-in automatically, the .dotm file must be saved in the Word Startup folder. Quit and restart Word. Word will load your add-in automatically.

You can see what add-ins are currently loaded in Word. On the Developer tab, click the Add-Ins button.

Because you saved MyWordTools.dotm in the Word Startup folder, close and restart Word. Word will automatically load your MyWordTools.dotm as an add-in. You should see the button on the Quick Access Toolbar, and you can use your macro.

When MyWordTools.dotm is loaded as an add-in, you will not see any of the text you may have left in the main Word window in MyWordTools.dotm. Word makes no use of any content on the face of the document itself. Delete any text in the main Word window before you save a .dotm file that is used as an add-in.

It is important to differentiate between opening an add-in file (for example, by clicking File and then clicking Open) and loading an add-in (for example, by using the Add-Ins button on the Developer tab). Open a file when you want to edit it and test it. Load the file as an add-in when you want to use it.

Warning

Never load a file as an add-in if that file is currently open in Word. Never open and edit an add-in file if it is currently loaded as an add-in. This may result in unpredictable behavior.

Using Your Macro on Another Computer

To use your macro, you must have:

  • The macro code.

  • A button on the Quick Access toolbar that runs the macro.

  • The keyboard shortcut that runs the macro.

You saved all three in MyWordTools.dotm. So, to use your macro on another computer, or to share your macro, you just have to to copy MyWordTools.dotm to the Word Startup folder on another computer. When you start Word, Word will load MyWordTools.dotm as an add-in and your macro, the button and the keyboard shortcut will all be available.

Part 2: Writing More Complex Macros

The end-to-end example in Part 1 includes a simple one-line macro. Part 2 describes how to extend that basic end-to-end process to create more complex macros.

Adding Additional Macros to the MyWordTools.dotm File

The file that you created in Part 1, MyWordTools.dotm, now contains one module (Module1), and that module contains one macro (ToggleHyperlinkCtrlClick).

Do not edit a file while it is loaded as an add-in. To add additional macros to your file, you must:

  1. Unload the file as an add-in. To do that, on the Developer tab, click Add-Ins, and then click to clear the check box for your add-in and then click OK.

  2. Open the file for editing. To do that, click the File tab. Under Info, click Open. Locate the file, click the file, and then click Open.

When your file is open for editing, you can:

  • Add a macro to the existing module, Module1, by typing in the code window, or

  • Add a new module to the file, and type a new macro in the new module.

Which method that you use depends on how complex your macros are. If you only have several short macros, then it is common to put them all in one module. If you have many long macros, you may prefer to store them in separate modules and rename each module to indicate what macros the module contains.

When you have added a new macro to your file, you can test it, create a button for it on the Quick Access Toolbar, and create a keyboard shortcut for it, exactly as you did for your first macro.

Comments

Professional developers generally include comments in their code to explain what the code is intended to do.

You can add comments to your macros by preceding the text of the comment with a single apostrophe. By default, the VBE displays comments in green.

Writing Robust Code: A Macro to Sort Text

There are two things to consider if you share a macro with a colleague. First, the other person’s computer is almost definitely not set up identical to yours. Second, the other person is likely to be less forgiving of poor code than you are. So your code must be robust.

If a macro is robust then the user will not see inexplicable error messages and the macro will do what it is intended to do—no more and no less.

To demonstrate some issues in writing robust code, consider the following macro that is used to sort text.

It takes several mouse clicks to sort several paragraphs of text. If you must sort text frequently, it may be useful to have a single button to do a simple sort (and when you must do a more complex sort, the builtin button will still be available to you on the Home tab). This macro action is shown in the following code example.

    Sub SortText1()
    ' A macro to sort the selected text
         Selection.Sort
    End Sub

You can test this macro as you tested the previous one. Tile the Word and VBE windows side by side. In the main Word window, type several paragraphs of text and select them. In the VBE, run the macro by clicking in the macro code and pressing F5. Word will sort the paragraphs alphabetically.

Our SortText1 macro seems to work well. However, it is not robust. To see what can go wrong, insert a picture into your document. Make it a floating picture. To do that, select the picture. On the Format tab, under Picture Tools, in the Arrange group, click Position. Select any one of the With Text Wrapping page position options.

Select your picture, and then run the SortText1 macro. Because it does not make sense for Word to sort one floating picture, you will see an error message from Visual Basic. That is not a robust macro!

Our one line of code, Selection.Sort, only works correctly if you have selected ordinary text. Before you find a way to solve that problem, consider another problem.

Warning

If you click in your document without selecting any text and run the SortText1 macro, the whole document is sorted. At best, that is unexpected; at worst, it might corrupt data.

The following code example shows how to restrict the macro to sorting only when there are two or more paragraphs of selected text.

    Sub SortText2()
    ' A macro to sort the Selection if the user has selected more than one
    ' paragraph of text.
        If Selection.Paragraphs.Count > 1 Then
            Selection.Sort
        End If
    End Sub

Experiment running the SortText2 macro. Unlike SortText1, this macro will not display an error message if you select a picture and then run the macro. Also, it will not let you accidentally sort your whole document. To see what happens, use the following procedure to step through the code one line at a time.

To step through the VBA code

  1. Click in the main Word window, and select your picture.

  2. Click anywhere within the SortText2 macro.

  3. Press F8. Word will highlight the first line in the macro (Sub SortText2()).

  4. Press F8 repeatedly to step line by line through the code.

Using F8 to step through code is a common way to see what the code is doing, and to troubleshoot problem code. In this case, you see that, when a picture is selected, Word processes the If statement, but skips the Selection.Sort statement.

There are several important things to see in the new SortText2 macro:

  • You can use If and End If to control whether Word processes code or skips it.

  • The If line ends with the keyword Then.

  • Each If must have a corresponding End If.

  • This macro uses Selection two times. Selection.Paragraphs.Count provides information about what the user has selected. Selection.Sort sorts the selected text.

The following code example show how to extend this macro to provide information to the user by using the Else and MsgBox keywords.

    Sub SortText3()
        If Selection.Paragraphs.Count > 1 Then
            ' The user has selected more than one paragraph of text.
            ' Sort the selection.
            Selection.Sort
        Else
            ' Tell the user what to do.
            MsgBox "Please select two or more paragraphs and try again."
        End If
    End Sub

From this macro, you can see that:

  • You can use If…Then, Else and End If to control whether Word processes code or skips it.

  • Using an Else statement is optional. Each If statement may have zero or one Else statements.

  • If you use Else, you still need an End If.

  • The command displays a message to the user on the screen. Type the text of the message after the keyword MsgBox, and enclose it in double quotation marks. If you provide any text in a macro (such as the text of this message), you must enclose it in quotation marks ("). Without quotation marks, Word would try to find "Please" in the Word object model. Because Word does not know what "Please" means, the macro would cause an error message.

To see the problem, use the following procedure.

To test the SortText3 macro

  1. Create a button on the Quick Access Toolbar to start the SortText3 macro. Instruct Word to save the button in MyWordTools.dotm.

  2. Test your button to ensure that it runs the SortText3 macro.

  3. Save the MyWordTools.dotm file

  4. Quit and restart Word

  5. If a document is open, close it so that there is no document open.

  6. Test your button on the Quick Access Toolbar again.

You should see an error message. The error is occurring because the first line of the macro refers to the Selection. The add-in is loaded. If no document is open in the main Word window, then there is no Selection. Without a Selection, Word cannot run the code in your macro.

Make one more change to the macro to make it robust. Add a comment to the top of the macro. That is a good way to document your macro so anyone will know what the macro is intended to do.

Unload the add-in, and then open the file for editing. Replace your existing macro with the following code example.

    Sub SortText()
    ' A macro to sort the selected text, if the user has selected 
    ' more than one paragraph
    
        If Documents.Count > 0 Then
            ' The user has at least one document open.
            
            If Selection.Paragraphs.Count > 1 Then
                ' The user has selected more than one paragraph
                ' of text, so sort it.
                Selection.Sort
            Else
                ' Tell the user what to do.
                MsgBox "Please select two or more paragraphs and try again."
            End If
        End If
    End Sub

In this final version of SortText, this example used nested If…End If blocks. It is important to indent lines of code. Each If is matched to the correct End If.

A macro that is not robust can result in:

  • Error messages (for example, when the Selection object was used, but there was no document open, and therefore no Selection), or

  • Unwanted behavior (for example, when the Selection.Sort command unintentionally sorted the whole document).

Here are tips for writing robust macros.

  • If your macro refers to the Selection, create a test document and test your macro by running it after you select different parts of the document: just click so you have selected no text, move the curso to the top of the document or the bottom of the document, or select a single word, several paragraphs, a picture, part or all of a table, text in the header or footer, text in a footnote or endnote or comment, and so on.

  • Close your file, load it as an add-in and test your macro to ensure that the macro works if there is no document open. Use If Documents.Count > 0 to verify if a document is open.

Learning About the Word Object Model

The macros created to this point have used three important Word elements:

  • Options. This refers to the Options used to set up Word.

  • Documents. This refers to all the Documents currently open in Word. You can use the keyword ActiveDocument to refer to the currently-active document.

  • Selection. This refers to whatever the user has selected in the ActiveDocument. It might be one word, several paragraphs, a picture, or any other kind of content.

For each of these macros, the following lower-level elements were used:

These elements (Options, Documents, and Selection) are known as Objects, and together they are part of the Word object model.

An object model is a hierarchy. The hierarchy includes all the parts of Word that you might need a macro to control. For example, the ActiveDocument object refers to the currently-active document.

If your current document that is contained a table with at least 3 rows and at least 2 columns, then the following would display the text in the second cell in the third row of the first table in the active document.

    MsgBox ActiveDocument.Tables(1).Rows(3).Cells(2).Range.Text

A macro can manipulate an object (such as the Selection object or the ActiveDocument object). Actually, objects have two ways to manipulate them: methods and properties.

Methods are like verbs, they describe action. For example:

  • ActiveDocument.PrintPreview

  • ActiveDocument.AcceptAllRevisionsShown

Properties are like adjectives, they describe objects. For example:

  • MsgBox ActiveDocument.Paragraphs(1).Range.Text

  • ActiveDocument.Paragraphs(1).Range.Text = "New text for Paragraph 1"

In the first example here the macro is "reading" the Text property and displaying the text in a message box. In the second example, the macro is "writing" (or setting) the Text property. Running that line of code will change the existing text in the first paragraph to "New text for Paragraph 1".

In general, your macro can "read" a property or it can "write" a property. However, some properties are readonly. For example, the Documents object has a property named .Count. Consider the following:

  • MsgBox Documents.Count ' Reports the number of currentlyopen documents.

  • Documents.Count = 4 ' Does not work: .Count is a readonly property.

Writing Shortcut Code: A Macro to Toggle the Display of Text Boundaries

When I am editing a big document, I like to see the text boundaries in my document. When I am proofreading, I prefer to turn off text boundaries. I may turn the display of text boundaries on and off many times in a day. To do that, I click the File button, and under Help, I click Options. In the Word Options dialog, I click Advanced, and then under Show Document Content, I select (or clear) Show Text Boundaries and then click OK. Doing that sequence of mouse clicks repeatedly is frustrating. I would prefer to click one time to turn text boundaries on or off.

The following code example is a macro that is used to toggle the display of text boundaries.

    Sub ToggleTextBoundaries1()
    ActiveDocument.ActiveWindow.View.ShowTextBoundaries = Not ActiveDocument.ActiveWindow.View.ShowTextBoundaries
    End Sub

Word does not mind that the single line of code is so long, but it is much to type, and can be difficult for humans to read. To shorten the macro and make it easier to read, use the With keyword as shown in the following code example.

    Sub ToggleTextBoundaries2()
        With ActiveDocument.ActiveWindow.View
            .ShowTextBoundaries = Not .ShowTextBoundaries
        End With
    End Sub

Within the object model, you can "drill down" from one object to another using a period (".") between each item of the hierarchy. Because the period marks off a child object from its parent, you cannot start a line of code with a period—except when using the With keyword.

Each With must be paired to an End With statement. Between the With and End With, you can use a period to begin a shortcut.

    With ActiveDocument.ActiveWindow.View
            ' Between With and End With you can use 
            ' a period to begin shortcut code.
            ' The shortcut will refer to ActiveDocument.ActiveWindow.View.
        End With

For example, between this With and End With, the shortcut .ShowTextBoundaries refers to ActiveDocument.ActiveWindow.View.ShowTextBoundaries.

When you have code that refers to the same object several times, it will be less to type, and easier to read, if you use With and End With.

This is not yet a robust macro, but you can make a final solid version as shown in the following code example.

    Sub ToggleTextBoundaries()
        If Documents.Count > 0 Then
            With ActiveDocument.ActiveWindow.View
                .ShowTextBoundaries = Not .ShowTextBoundaries
            End With
        End If
    End Sub

In this final version of ToggleTextBoundaries, there is a With…End With block nested in an If…End If block. By indenting the lines, you ensure that each With is matched to its End With, and each If statement is matched to its End If statement.

Using With and the Selection Object: A Macro to Insert a Landscape Section

Here is a more complete example using the With keyword: a macro to insert a landscape section at the cursor.

This macro uses the With keyword with the Selection object (that is, With Selection). As you become more skilled in writing macros, you will find that you use the Selection object less and less, because it is often more effective to use a Range object. Studying this macro is a good way to learn how Word manages the Selection. With Word and the VBE tiled side by side, click within the macro and press F8 repeatedly to step through the macro line by line, to see what happens in the main Word window.

This macro also shows that, when you have many lines of text it is recommended that you break them up into logical ‘paragraphs,’ with comments to describe what the code is intended to do.

    Public Sub InsertLandscapeSectionHere()
    ' Purpose: Insert a landscape section at the insertion point, 
    ' and insert text to tell the user where the landscape section is.
        If Documents.Count > 0 Then
            ' The user has a document open, so insert a 
            ' landscape section.
            With Selection
                ' Do not accidentally over-write selected text
                .Collapse Direction:=wdCollapseStart
    
                ' Insert section breaks with blank paragraphs
                ' in the new section.
                .TypeParagraph
                .Style = ActiveDocument.Styles(wdStyleNormal)
                .InsertBreak Type:=wdSectionBreakNextPage
                .TypeParagraph
                .TypeParagraph
                .TypeParagraph
                .InsertBreak Type:=wdSectionBreakNextPage
                .MoveUp Unit:=wdLine, Count:=3
    
                ' Set the orientation of new section to landscape.
                .PageSetup.Orientation = wdOrientLandscape
    
                ' Provide guidance to the user.
                .TypeText Text:="Your landscape section starts here."
            End With
        Else
            ' Tell the user what to do.
            MsgBox "Please open a document and try again."
        End If
    End Sub

You will see two kinds of syntax in this macro:

  1. The first syntax is uses an equal sign (=):Selection.PageSetup.Orientation = wdOrientLandscape

  2. The second syntax uses a colon and an equal sign (=):Selection.InsertBreak Type:=wdSectionBreakNextPage.

For more information about the differences between these syntax types, see the article "Understanding Visual Basic Syntax" in the VBE Help.

Learning More About Word Macros and the Visual Basic Editor

The Visual Basic Editor (VBE) includes tools to help you write your own macros. The following is a list of things to consider:

  • The Word macro recorder is a powerful tool. If you want to write a macro, but do not know which parts of the Word object model that you must use, the macro recorder is the best way to find out. For more information, see Recording a Macro to Generate Code and How to modify a recorded macro.

  • When you type the name of an object in the Word object model (such as Selection or ActiveDocument), and then type a period (.),Word will show you a list of all the properties and methods of that object. For more information, see Getting to grips with VBA basics in 15 minutes.

  • The Immediate Window in the VBE can help you learn more about the Word object model and test simple macros. For more information, see Extending Word 2007, Excel 2007, and PowerPoint 2007 with a Single Line of VBA Code.

  • You can customize the menu and toolbars in the VBE. One useful customization is to create keyboard shortcuts for comments. To do this, right-click in open space near the menu or toolbars and select Customize. In the Customize dialog, on the Toolbars tab, select the Edit toolbar. Leave the Customize dialog box open. On the Edit toolbar, right-click the Comment block button, change the name to &Comment, then click Image and Text. Do the same to the Uncomment block button, renaming it as &Uncomment. You can now select several lines of code and use the keyboard shortcuts Alt+C and Alt+U to comment, or uncomment, the selected code.

  • The VBE includes a large amount of Help information. This will be your main source of information about the Word object model:

    • For general information, in the VBE, on the Help menu, click Microsoft Visual Basic for Applications Help. Be sure that you display the Table of Contents by clicking the little book icon in the toolbar of the client help viewer. It makes browsing the developer help much more intuitive. In particular, under Concepts, read the topics at Frequently Asked Visual Basic Questions.

    • For specific help about a keyword or an object from the Word object model (such as ActiveDocument), click in the word and press F1 to read help about that keyword or object.

Conclusion

Word macros can be long, complex, and powerful. You could write a macro to talk to an external database, perform calculations and return the result to Word. You can also write a macro in Word to control Excel, PowerPoint, or Outlook. Sometimes simple macros can be useful and save you time.

If your macro is to format text, it may be better to create a Style instead of writing a macro. If the macro is to control the layout of a document, it may be better to create a new template. Also, there may be a built-in command that you can add to the Quick Access Toolbar (when customizing the Quick Access Toolbar, in the Choose Commands From: list, click All Commands).

Have fun creating macros, but do not re-invent the wheel by writing a macro to do what Word can already do on its own.

Additional Resources

For more information, see the following resources:

About the Author

Shauna Kelly develops Word add-ins and templates to help people in government and business use Word more efficiently. She has been a Microsoft Word MVP since 2002.