1

I am using the following code to find some strings in my document:

Application application = Addin.Application;
Document document = application.ActiveDocument;
Range rng = document.Content;

rng.Find.ClearFormatting();
rng.Find.Forward = true;
rng.Find.Text = findText;

while (rng.Find.Execute() && rng.Find.Found)
{
    //here: rng.Text == findText
    //however rng.Find.HitHighlight(findText, WdColor.wdColorAqua);
    //highlights all occurrences in the document, not in the current range
}

as the comments in the code state, I'd expect rng.Find.HitHighlight(findText, WdColor.wdColorAqua); to only work on the current range but instead it executes on the whole document.

Interestingly if I start from a different range this works as I would expect... ie.

Range rng = document.Content.Paragraphs.First.Range;
rng.Find.HitHighlight("video", WdColor.wdColorAqua);

will only HitHighlight the findText in the first paragraph.

This is inconsistent... Any ideas on how to perform HitHighlight only on the range selected using Find?

NOTE: I tried this in a NetOffice addin and I get the same behavior.

Leo
  • 5,013
  • 1
  • 28
  • 65
  • But didn't you set the range as the entire document `Range rng = document.Content;`? – Magnetron Mar 14 '19 at 13:05
  • @Magnetron - I did but then `rng.Find.Execute()` set the range to an instance found, hence the comment `//here: rng.Text == findText` moreover in debug I can see `rng.Start` and `rng.End` move along to each found instance at every iteration. – Leo Mar 14 '19 at 13:07
  • I have also tried to use a new range created using the old one like this `Addin.Application.ActiveDocument.Range(rng.Start, rng.End).Find.HitHighlight("video", WdColor.wdColorAqua);` but `HitHighlight` still runs on the whole document... – Leo Mar 14 '19 at 14:07

1 Answers1

1

It seems like the Find.HitHighlight method is not intended to be used at the same time as Find.Execute. It seems to use whatever range was present when you call Execute. If you don't call execute, it uses the current range.

Remarks

The HitHighlight method applies primarily to search highlighting in Office Outlook when Word is specified as the email editor. However, you can use this method on documents inside Word if you want to highlight found text. Otherwise, use the Execute method.

I suspect there is no way to do this except by iterating through each paragraph, which you already know about.

I realize this is not a complete answer but VSTO is not a popular tag and this may be the best you are going to get. Most questions go completely unanswered, and often without comments as well.

Chris
  • 3,400
  • 1
  • 27
  • 41