Friday, July 4, 2025

VBA Word Bold and Blue the Previous paragraph of ChatGPT

In MS-Word document, to bold and blue color a paragraph if its next paragraph contains just one word ChatGPT. The condition is ChatGPT be the only word on a line.

Sub FormatPreviousParagraphBasedOnFind()

    Dim rng As Word.Range
    Dim found As Boolean

    ' Set the initial range to search in the entire document
    Set rng = ActiveDocument.Content
    found = True ' Initialize to true to enter the loop

    Do While found
        ' Reset find parameters for each iteration
        With rng.Find
            .ClearFormatting
            .Text = "ChatGPT" & Chr(13) ' Search for "ChatGPT" followed by a paragraph mark
            .Forward = True
            .Wrap = wdFindStop ' Stop at the end of the document
            .Format = False
            .MatchCase = True ' Case-sensitive match
            .MatchWholeWord = True ' Ensure it's the whole word
            .MatchWildcards = False
            .MatchFuzzy = False
            .MatchAllWordForms = False
        End With

        ' Execute the find operation
        found = rng.Find.Execute

        ' If "ChatGPT" is found and it's not the very first paragraph
        If found And Not rng.Paragraphs(1).Previous Is Nothing Then
            ' Get the previous paragraph
            Dim prevPara As Paragraph
            Set prevPara = rng.Paragraphs(1).Previous

            ' Apply bold and blue color to the previous paragraph
            With prevPara.Range.Font
                .Bold = True
                .Color = wdColorBlue
            End With

            ' Collapse the range to just after the found "ChatGPT" to continue searching from there
            rng.Collapse Direction:=wdCollapseEnd
        ElseIf found And rng.Paragraphs(1).Previous Is Nothing Then
            ' If "ChatGPT" is found in the first paragraph, there's no previous paragraph to format.
            ' Collapse the range to continue searching.
            rng.Collapse Direction:=wdCollapseEnd
        End If

        ' Important: Reset the range to the remainder of the document for the next search
        ' If not done, the search will keep finding the same instance of "ChatGPT"
        If rng.End >= ActiveDocument.Content.End Then
            found = False ' Stop if we've reached the end of the document
        End If

    Loop

    MsgBox "Formatting complete!", vbInformation

End Sub

No comments:

Post a Comment

Hot Topics