View Single Post
 
Old 10-10-2024, 04:46 AM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,617
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

While Vika's suggestion will work, it is not really necessary. The issue is the collection "key" attribute is being used when it doesn't necessarily need to be. Also, the code as Graham wrote will also highlight partial text in other words. That may or not be suitable for your needs. E.g., This is a test. I can attest that if you highlight "test" and run the code that at"test" will also be highlighted. You might consider:

Code:
Sub MatchHighlight()
'Graham Mayor - https://www.gmayor.com - Last updated - 08 Oct 2024
Dim oDoc As Document
Dim oRng As Range
Dim oCol As Collection
Dim i As Integer
  Set oDoc = ActiveDocument
  Set oRng = oDoc.Range
  Set oCol = New Collection
  With oRng.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Highlight = True
    .MatchWholeWord = True '*** GKM mod
    Do While .Execute = True
      oCol.Add oRng.Text & "/" & oRng.HighlightColorIndex '*** GKM mod
      oRng.Collapse 0
    Loop
  End With
  For i = 1 To oCol.Count
    Set oRng = oDoc.Range
    With oRng.Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .MatchWholeWord = True '*** GKM mod
      .Text = Split(oCol(i), "/")(0)
      Do While .Execute = True
        oRng.HighlightColorIndex = Split(oCol(i), "/")(1)
        oRng.Collapse 0
      Loop
    End With
  Next i
lbl_Exit:
  Set oDoc = Nothing
  Set oRng = Nothing
  Set oCol = Nothing
  Exit Sub
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote