View Single Post
 
Old 10-08-2024, 12:31 AM
MUMS MUMS is offline Windows 8 Office 2016
Novice
 
Join Date: Jul 2023
Posts: 8
MUMS is on a distinguished road
Default A Word macro that highlights all other instances of words that are already highlighted

This code was generated using Copilot AI but it's so slow it doesn't terminate:


Code:
Sub HighlightUnhighlightedInstancesOfHighlightedWords()
    Dim doc As Document
    Dim rng As Range
    Dim findText As String
    Dim highlightColor As Long
    Dim tempRng As Range
    Dim startPos As Long

    Set doc = ActiveDocument

    ' Loop through each word in the document
    For Each rng In doc.Words
        If rng.HighlightColorIndex <> wdNoHighlight Then
            ' Store the highlighted word and its highlight color
            findText = Trim(rng.Text)
            highlightColor = rng.HighlightColorIndex

            ' Find all instances of the highlighted word
            Set tempRng = doc.Content
            With tempRng.Find
                .ClearFormatting
                .Text = findText
                .Format = True
                .MatchWholeWord = True
                .MatchCase = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Forward = True
                .Wrap = wdFindStop

                Do While .Execute
                    ' Check if the found instance is not already highlighted
                    If tempRng.HighlightColorIndex = wdNoHighlight Then
                        tempRng.HighlightColorIndex = highlightColor
                    End If
                    ' Move the range past the found instance
                    startPos = tempRng.End
                    tempRng.Collapse wdCollapseEnd
                    tempRng.Start = startPos
                    tempRng.End = doc.Content.End
                Loop
            End With
        End If
    Next rng
End Sub

Last edited by macropod; 10-08-2024 at 02:23 PM. Reason: Added code tags
Reply With Quote