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.
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.