Thread: [Solved] VBA highlight adjacent word
View Single Post
 
Old 09-02-2015, 01:48 AM
gmayor's Avatar
gmayor gmayor is offline Windows 7 64bit Office 2010 32bit
Expert
 
Join Date: Aug 2014
Posts: 4,144
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

The following should do the trick for selected text
Code:
Sub Highlight_Plus_Adjacent_Words()

Dim MyWords As Variant
Dim RngWords As Range
Dim oRng As Range
Dim i As Integer

    MyWords = Split("one,two,three,four,five", ",")
    Set oRng = Selection.Range
    For i = 0 To UBound(MyWords)
        Set RngWords = oRng
        With RngWords.Find
            Do While .Execute(FindText:=MyWords(i), MatchWholeWord:=True)
                With RngWords
                    .Start = .Previous.Words(1).Start
                    .End = .Next.Words(1).Next.Words(1).End
                    .MoveEndWhile Chr(32), wdBackward
                    .HighlightColorIndex = wdYellow
                    .Collapse 0
                    If .Start >= oRng.End Then Exit Do
                End With
            Loop
        End With
    Next i
lbl_Exit:
    Set oRng = Nothing
    Set RngWords = Nothing
    Exit Sub
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote