Saturday, August 16, 2025

Macro VBA script: Change format cross-reference with text pattern Example 6.X or 6.XX

Rule:
- Search only in text paragraphs.
- Match "Example 6.X" or "Example 6.XX".
- Change font → unbold + RGB blue.
- Skip if "Example 6.X" is the first word of the paragraph.

Sub ChangeCrossRefExampleFontColor()

    Dim para As Paragraph
    Dim rng As Range
    Dim firstWord As String
    
    For Each para In ActiveDocument.Paragraphs
        Set rng = para.Range
        
        ' Get the first word of the paragraph (without trailing space/punctuations)
        firstWord = Trim(Split(rng.Words(1).Text, " ")(0))
        
        With rng.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            
            ' Pattern: Example 6.X or Example 6.XX
            .Text = "Example 6.[0-9]{1,2}"
            .MatchWildcards = True
            
            ' Formatting
            .Replacement.Font.Bold = False
            .Replacement.Font.Color = RGB(0, 0, 255)
            
            ' Replace one by one inside this paragraph
            Do While .Execute(Replace:=wdReplaceOne)
                ' Check if found text = first word ? skip formatting
                If Trim(rng.Text) = firstWord Then
                    rng.Font.Bold = True ' revert any change
                    rng.Font.Color = wdColorAutomatic
                End If
                rng.Collapse wdCollapseEnd
            Loop
        End With
    Next para
    
    MsgBox "Formatting complete (excluding first word of each paragraph)!", vbInformation
End Sub

No comments:

Post a Comment