vbams-wordword-style

How to include BackgroundPatternColor or HighlightColor in a Word Style definition?


Since the Highlight color palette in Ms-Office/Word is very limited, in some Word documents we use BackgroundPatternColor to give the background color of the text.

Question:
I would like to define a custom Style as a spinoff of the Normal Style, that includes a custom background color.
In the Style definition dialogue I did not find any option where I can include the bgcolor of the selection. Any ideas?

Note: The only option close to that is the so called Border>Shading>Fill Color, but that always spans to the full line/paragraph, cannot be applied to less.


Solution

  • You can change the background color, but if you don't want it coloring the entire paragraph then you must create a character style and set the color for its .Font property.

    (Note: you could also create a so-called "linked" style, that can be use for both paragraph and font formatting, but these are generally frowned upon in professional documentation circles.)

    Here's an example

    Sub ChangeStyleColor()
        Dim styl As word.style
        Dim stylName As String
        Dim color As word.WdColor
    
        stylName = "fontBlueBackground"
        color = wdColorAqua
    
        ' the style might not exist - if not, create it
        On Error Resume Next
        Set styl = ActiveDocument.styles(stylName)
        On Error GoTo 0
    
        If styl Is Nothing Then
            Set styl = ActiveDocument.styles.Add(stylName, word.WdStyleType.wdStyleTypeCharacter)
            styl.BaseStyle = word.WdBuiltinStyle.wdStyleDefaultParagraphFont
        End If
    
        CharStyleBackgroundColor styl, color
    
    End Sub
    
    Sub CharStyleBackgroundColor(styl As word.style, color As word.WdColor)
        styl.Font.Shading.BackgroundPatternColor = color
    End Sub