JLuc01
JLuc01

Reputation: 187

Highlight in yellow a word in a string (sentence)

I create a small word document from excel in vba. I would like to highlight in yellow a word in a sentence. Currently, it is what I am doing:

        wdDoc.Content.Paragraphs.Last.Range.Characters(60).Shading.BackgroundPatternColor = wdColorYellow

...which is good for one character, but not great for several characters. In my case, I am highlighted a word of 7 characters which is feasible by repeating this line above and changing the index.

But, I am curious and would like to know if there is a better way to do it. Thanks.

Upvotes: 0

Views: 164

Answers (1)

Variatus
Variatus

Reputation: 14373

I tested this little snippet. It determines the position of the 60th character of the past paragraph within the document and then sets a range starting from there.

Dim wdDoc As Document
Dim p As Long

Set wdDoc = ActiveDocument
p = wdDoc.Paragraphs.Last.Range.Characters(60).Start
wdDoc.Range(p, p + 7).Shading.BackgroundPatternColor = wdColorYellow

There should be an easier way to do this but I didn't find it.

Upvotes: 2

Related Questions