Thread: [Solved] VBA highlight adjacent word
View Single Post
 
Old 09-01-2015, 04:08 PM
macrointraining macrointraining is offline Windows 7 64bit Office 2007
Novice
 
Join Date: Sep 2015
Posts: 1
macrointraining is on a distinguished road
Default VBA highlight adjacent word

Hi,

I am analyzing paragraphs from multiple documents with a VBA macro to highlight word listings from an array. I would also like each word adjacent (i.e., one word to the left, and one word to the right) to the original word in the paragraphs highlighted as well. The macro below works fine to highlight the words from the array, but am unable to figure out how to highlight the adjacent words in the paragraphs.

For example, for:
- **The nearest county has one current listing, while the next closest county has two listings.**

- The macro highlights *one* and *two*.
- The desired result would highlight *has one current* and *has two listings*.

Any help is appreciated.

Thanks.

Office 2007
Windows 7

Sub Highlight_Plus_Adjacent_Words()

Dim MyWords As Variant
Dim RngWords As Range
Dim i As Integer
Dim lngHCI As Long

lngHCI = Options.DefaultHighlightColorIndex
Options.DefaultHighlightColorIndex = wdYellow

MyWords = Split("one,two,three,four,five", ",")

For i = 0 To UBound(MyWords)
Set RngWords = Selection.Range
With RngWords.Find
.ClearFormatting
' the below works for the MyWords as listed with no adjacent words highlighted
.text = "<" & MyWords(i) & ">"
' the following did not work for .text to include one adjacent word on each side
' .text = "<*>" & "<" & MyWords(i) & ">" & "<*>"
' .text = "/([A-Za-z0-9.,-]+\s*){0,1}\" & MyWords(i) & "(\s|[,.!?])(\s*[A-Za-z0-9.,-]+){0,2}/"
.Forward = True
.Wrap = wdFindStop
.MatchWildcards = True
.MatchCase = False
.MatchAllWordForms = False
.Format = True
.MatchWholeWord = True
.Replacement.ClearFormatting
.Replacement.Highlight = True
.Replacement.text = "^&"
.Execute Replace:=wdReplaceAll
End With
Next i

End Sub
Reply With Quote