Creating macros to work with formatting styles in Word 2002

Power User Corner

By Paul Cornell

Tired of trying to work with many different formatting styles at once in Word documents? Learn how to create three macros that help you manage Word document styles.

Applies to
Microsoft Word 2002

I'm an editor as well as a writer, and every month my coworkers send me several Microsoft Word documents that need to have particular formatting styles. It seems like each document has its own formatting styles. A style is the type of formatting used for a particular piece of content in a Word document. For instance, in one week my coworkers sent me 18 Word documents that needed to be styled in a certain way. This is a job for a macro!

In this column, I show you how to create three macros that help you manage Word document styles.

Listing document styles

To work with document styles, it's helpful to know which styles already exist in a document. The Styles and Formatting task pane in Word is helpful because it lists some available styles, but it is sometimes easier to list all of the styles for an open document in a separate document. In this first example, I tell you how to create and run a macro that lists all of the available styles in the Word document you have open:

  1. Start Microsoft Word and open the document you want a list of styles for.
  2. On the Tools menu, point to Macro, and then click Macros.
  3. In the Macros in drop-down box, click Normal.dot (global template).
  4. In the Macro name box, type ListStyles, and then click Create. The Microsoft Visual Basic® Editor opens.
  5. Locate the following code:

    Sub ListStyles()
    '
    ' ListStyles Macro
    ' Macro created {date} by {name}
    '

    End Sub
  6. Edit the code so that it looks like this:

    Sub ListStyles()
    '
    ' ListStyles Macro
    ' Macro created {date} by {name}
    '
    ' Purpose: Prints all styles in the active document
    ' to a new Word document.

    Dim strTitle As String
    Dim astrStyles() As String
    Dim objStyle As Style
    Dim objDocument As Word.Document
    Dim intCount As Integer

    ' Get the title of the active Word document.
    strTitle = _
    ActiveDocument.BuiltInDocumentProperties(wdPropertyTitle)

    intCount = 1

    ' Store, in memory, each style in the active document,
    ' including whether the style is in use.
    For Each objStyle In ActiveDocument.Styles

    ReDim Preserve astrStyles(intCount)

    If objStyle.InUse Then
    astrStyles(intCount) = objStyle & " (Style in Use)"
    Else
    astrStyles(intCount) = objStyle & " (Style Not in Use)"
    End If

    intCount = intCount + 1

    Next objStyle

    ' Create a new Word document to report the results.
    Set objDocument = Word.Documents.Add

    With objDocument.Range

    ' Report the results.
    .InsertAfter "Styles in " & strTitle & ":"
    .InsertParagraphAfter
    .Collapse Direction:=wdCollapseEnd

    For intCount = 1 To UBound(astrStyles)

    .InsertAfter astrStyles(intCount)
    .InsertParagraphAfter
    .Collapse Direction:=wdCollapseEnd

    Next intCount

    End With

    MsgBox Prompt:="Done!"

    End Sub
  7. On the File menu, click Save Normal.
  8. On the File menu, click Close and Return to Microsoft Word.
  9. Make sure your document is still open. If it isn't, reopen it.
  10. On the Tools menu, point to Macro, and then click Macros.
  11. In the list of macros, click ListStyles, and then click Run. A new Word document will be created, listing all available styles for the document.

 Note    If you try to run a macro and see a message stating that the macros in the project are disabled, see the article Changing Macro Security Settings for details on how to fix the problem.

Changing document styles

Now that you know which document styles are available, you may want to change some of them to different document styles. In my next example, I show you how to create and run a macro that changes multiple document styles in an open Word document.

  1. Start Microsoft Word and open a document you want to change styles in.
  2. Start Microsoft Excel 2002 and create a new Excel workbook.
  3. In cell A1, type the name of a style you want to change in the open Word document. Then, in cell B1, type the name of the new style you want to change it to. Repeat the process for each style you want to change: in column A, type the name of the existing style, and, in column B, type the name of the new style. Here's an example.

    Excel Worksheet for Renaming Styles
  4. When you're finished, save and close the Excel workbook.
  5. Go back to Word. On the Tools menu, point to Macro, and then click Macros.
  6. In the Macros in list, click Normal.dot (global template).
  7. In the Macro name list, type ChangeDocumentStyles, and then click Create. The Visual Basic Editor opens.
  8. Locate the following code:

    Sub ChangeDocumentStyles()
    '
    ' ChangeDocumentStyles Macro
    ' Macro created {date} by {name}
    '

    End Sub
  9. Edit the code so that it looks like this:

    Sub ChangeDocumentStyles()
    '
    ' ChangeDocumentStyles Macro
    ' Macro created {date} by {name}
    '
    ' Purpose: Changes all document styles based on data
    ' provided in a style change file authored in Microsoft Excel.
    Dim objFileDlg As Office.FileDialog
    Dim xlApp As Excel.Application
    Dim objWB As Excel.Workbook
    Dim objWS As Excel.Worksheet
    Dim objRngOld As Excel.Range
    Dim objRngNew As Excel.Range

    On Error GoTo ChangeDocumentStyles_Err

    ' User instructs macro where the Excel style change file is.
    Set objFileDlg = Application.FileDialog(FileDialogType:=msoFileDialogOpen)

    With objFileDlg

    .AllowMultiSelect = False
    .Title = "Select Style Change File"
    .Filters.Clear
    .Filters.Add _
    Description:="Style Change Files (*.xls)", Extensions:="*.xls"

    ' "-1" means the user clicked the "Open" button in the file dialog box.
    If .Show = -1 Then

    ' Open the first worksheet in the Excel workbook and start with cell A1.
    Set xlApp = New Excel.Application
    Set objWB = xlApp.Workbooks.Open(FileName:=objFileDlg.SelectedItems(1))
    Set objWS = objWB.Worksheets.Item(1)
    Set objRngOld = objWS.Range(Cell1:="A1")

    ' If the cell is empty, we're done.
    Do While Not objRngOld.Value = ""

    ' Use the active Word document.
    With ActiveDocument.Content.Find
    ' Find style in column A.
    .Style = ActiveDocument.Styles(objRngOld.Value)
    ' Replace with style in column B.
    Set objRngNew = objRngOld.Offset(ColumnOffset:=1)
    .Replacement.Style = ActiveDocument.Styles(objRngNew.Value)
    .Execute Replace:=wdReplaceAll
    ' Go to column A in the next row.
    Set objRngOld = objRngNew.Offset(RowOffset:=1, ColumnOffset:=-1)
    End With

    Loop

    End If

    End With

    ChangeDocumentStyles_Exit:

    ' We're done.
    MsgBox Prompt:="Done!"
    Exit Sub

    ' In case of an error, go here.
    ChangeDocumentStyles_Err:

    Select Case Err.Number
    Case 5941 ' Unknown style.
    MsgBox Prompt:="Can't find one or more styles to replace. " & _
    "Check the styles in column B of your style change sheet. " & _
    "Program execution stopped."
    Case 62
    Resume Next
    Case Else ' Unknown error.
    MsgBox Prompt:="Error " & Err.Number & _
    " in ChangeDocumentStyles macro: " & Err.Description
    End Select

    GoTo ChangeDocumentStyles_Exit

    End Sub
  10. On the Tools menu, click References. The References - Normal dialog box appears.
  11. In the Available References list, check the Microsoft Excel 10.0 Object Library box, and then click OK.
  12. On the File menu, click Save Normal.
  13. On the File menu, click Close and Return to Microsoft Word.
  14. Make sure your Word document is still open. If not, reopen it.
  15. On the Tools menu in Word, point to Macro, and then click Macros. The Macros dialog box appears.
  16. In the list of macros, click ChangeDocumentStyles, and then click Run. The Select Style Change File dialog box appears.
  17. Click the file you created in step 2, and then click Open.

Deleting unused custom styles

In addition to built-in Word document styles such as Heading 1 and Normal, users can create their own custom document styles. However, it can be frustrating to have people create custom styles and then forget to actually use them in their documents! Unused custom document styles can unnecessarily increase your final document size. In my final example, I show you how to create and run a macro that deletes all of the unused custom styles in an open Word document.

 Note   Built-in document styles cannot be deleted.

  1. Start Microsoft Word and open the document you want to list styles for.
  2. On the Tools menu, point to Macro, and then click Macros.
  3. In the Macros in list, click Normal.dot (global template).
  4. In the Macro name list, type DeleteUnusedCustomStyles, and then click Create. The Visual Basic Editor opens.
  5. Locate the following code:

    Sub DeleteUnusedCustomStyles()
    '
    ' ChangeDocumentStyles Macro
    ' Macro created {date} by {name}
    '

    End Sub
  6. Edit the code so that it looks like this:

    Sub DeleteUnusedCustomStyles()
    '
    ' ChangeDocumentStyles Macro
    ' Macro created {date} by {name}
    '
    ' Purpose: Deletes all unused custom styles in the
    ' active Word document. Built-in styles cannot
    ' be deleted.

    Dim objStyle As Word.Style

    For Each objStyle In ActiveDocument.Styles

    ' If the custom style is not in use, delete it.
    If objStyle.BuiltIn = False And _
    objStyle.InUse = False Then
    objStyle.Delete
    End If

    intCount = intCount + 1

    Next objStyle

    MsgBox "Unused custom styles in the active document deleted."

    End Sub
  7. On the File menu, click Save Normal.
  8. On the File menu, click Close and Return to Microsoft Word.
  9. Make sure your document is still open. If it isn't, reopen it.
  10. On the Tools menu, point to Macro, and then click Macros.
  11. In the list of macros, click DeleteUnusedCustomStyles, and then click Run. All of the unused custom styles in the active Word document are deleted.

Keep sending that e-mail!

I look forward to receiving your e-mail messages at pwruser@microsoft.com. I really want this to be your column, so please send me your comments and favorite handcrafted Office solutions. Remember, I will not be able to feature every Office solution that I receive, I will not have the time to respond to all of your e-mail, and I am not a technical support representative. But I may feature your solution in an upcoming column.


About the author

Paul Cornell works for the Office Help team. In addition to writing the Office Power User Corner column, Paul writes the Office Talk column on the Microsoft Developer Network (MSDN). He is the author of the book Accessing and Analyzing Data with Microsoft Excel.

If you like this column and want to hear about more fun and useful Office offerings, sign up for our newsletter.