Marcel
Marcel

Reputation: 187

renaming Word styles with VBA

I have a batch of files (WinWord) which are already formatted, and I want to use the same names for logically matching styles everywhere.

Is there any way to rename a number of WinWord 2007 styles via VBA or can this be done only manually?

Thanks for taking time to think about my question. Marcel

Upvotes: 1

Views: 3521

Answers (2)

Aleksey F.
Aleksey F.

Reputation: 761

There is an important note on how to rename linked styles. I accidentally found this trick when renaming styles through the NameLocal of a style itself: Renaming also changed the character formatting of a style. For linked styles, one should use the NameLocal of the LinkStyle of a style being renamed. Here is a complete function to rename styles of both types. Debug is used to see what and how styles have been renamed.

Function rename_style(ByVal p_Styles As Styles, ByVal From_n As String, ByVal to_n As String) As Boolean
  Dim v_Style As Style
  On Error Resume Next
  Set v_Style = p_Styles(From_n)
  If Not v_Style Is Nothing Then
    If v_Style.Linked Then
      v_Style.LinkStyle.NameLocal = to_n
    Else
      v_Style.NameLocal = to_n
    End If
    Set v_Style = p_Styles(From_n)
    'Accessing through p_Styles to avoid the use of the localized name
    If v_Style Is Nothing Then
      Debug.Print From_n; " -> "; to_n; " failed"
      rename_style = False
    Else
      Debug.Print From_n; " -> "; to_n
      rename_style = True
    End If
  Else
    rename_style = False
    Debug.Print From_n; " skipped"
  End If
End Function

Upvotes: 1

Christina
Christina

Reputation: 1379

You should be able to change the names of user-defined styles by writing to their NameLocal properties. For instance:

ActiveDocument.Styles(3).NameLocal = "abbracadabra"

changes the name of the third style in the Styles collection to "abbracadabra". Exactly how you'd automate this depends on whether there's a logic to the name changes.

I don't think this will work for built-in styles (like Heading 1); instead you get an aliased style. In Word 2010, that ends up looking like "[old style name], [new style name]". I don't know a lot about those.

So, if you wanted to, for instance, append "-changed" to each style name you could do the following:

For Each aStyle in ActiveDocument.Styles
    If aStyle.BuiltIn = False Then aStyle.NameLocal = aStyle.NameLocal & "-changed"
Next aStyle

Upvotes: 0

Related Questions