Search code examples
vbatextms-wordreformatting

Find text and numbers Formatted: "Case: BE########" and format them, regardless of the number


I need to reformat hundreds of case numbers in a Word document. They all start with "Case: BE:" followed by eight numbers. I need to find ALL of the "Case: BE########" and get it to bold and underline each of them.

I tried recording a macro [because that's how I usually figure it out] But when I do that, I need to search for a particular case number because I don't know how to represent ANY number in the search string. When I search for and find one case number, it will only do one thing at a time, bold or underline. And the case number I searched for doesn't even show up in the macro.


Solution

    • Case: BE is a literal string.
    • [0-9] matches any digit from 0 to 9.
    • {8} specifies that the preceding character (in this case, digits) should be repeated exactly 8 times.

    Microsoft documentation:

    Find.Execute method (Word)

    Replacement.ClearFormatting method (Word)

    Selection.Find property (Word)

    Option Explicit
    Sub BoldAndUnderline()
        With Selection.Find
            .ClearFormatting
            .Text = "Case: BE[0-9]{8}"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = True
            .MatchCase = False
            .MatchWholeWord = False
            .MatchByte = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
            .Replacement.ClearFormatting
            With .Replacement.Font
                .Bold = True
                .Underline = wdUnderlineSingle
            End With
            .Execute Replace:=wdReplaceAll
        End With
    End Sub