Monday, August 11, 2025

Macro VBA Script: Change font color of pattern-text 'Figure 6.XX' and 'Figure 6.X', where X is number, and located in text-paragraph

Sub ChangeCrossRefFigureFontColor()
    Dim doc As Document
    Dim para As Paragraph
    Dim paraRange As Range
    
    Set doc = ActiveDocument
    
    ' Loop through each paragraph in the document
    For Each para In doc.Paragraphs
        Set paraRange = para.Range
        
        ' Only process paragraphs outside of tables
        If paraRange.Information(wdWithInTable) = False Then
            With paraRange.Find
                .ClearFormatting
                .Text = "Figure 6\.[0-9]{1,2}"
                .MatchWildcards = True
                .Replacement.ClearFormatting
                .Replacement.Font.Color = RGB(0, 0, 230) ' Light blue
                
                ' Loop until all matches in paragraph are handled
                Do While .Execute(Replace:=wdReplaceOne) = True
                    paraRange.Font.Color = RGB(0, 0, 230)
                    ' Move start to after last found item
                    paraRange.Collapse Direction:=wdCollapseEnd
                Loop
            End With
        End If
    Next para
End Sub

No comments:

Post a Comment