I used to highlight the 'word' using this code.It is used inside a 'for each' loop which loops through collection of strings. But the issue is after the all the words are highlighted .. if we try to change any one word in the document all the highlight removed automatically.
word.Find find = rng.Find;
find.Wrap = word.WdFindWrap.wdFindContinue;
find.Font.UnderlineColor = word.WdColor.wdColorRed;
find.HitHighlight(
FindText: wd,
MatchCase: true,
TextColor:word.WdColor.wdColorRed,
MatchWholeWord: true,
HighlightColor: word.WdColor.wdColorLightYellow
);
By design, HitHighlight
only leaves the highlight until the document is edited - this is how the Find task pane works when the user does a non-Advanced Find.
If you want a permanent highlight, then you need to do this a bit differently, by using Replacement.Highlight = true
, as in the following example.
Word.Document doc = wdApp.ActiveDocument;
Word.Range rng = doc.Content;
Word.Find f = rng.Find;
object oTrue = true;
object missing = Type.Missing;
//Find and highlight
wdApp.Options.DefaultHighlightColorIndex = Word.WdColorIndex.wdPink;
f.ClearFormatting();
f.Replacement.Highlight = -1;
f.Text = "the";
f.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, Word.WdFindWrap.wdFindStop, ref oTrue, ref missing, Word.WdReplace.wdReplaceAll,
ref missing, ref missing, ref missing, ref missing);
VBA equivalent for interested VBA readers:
Sub FindXAndHighlight()
Dim rng As word.Range
Set rng = ActiveDocument.content
Options.DefaultHighlightColorIndex = wdPink
With rng.Find
.Replacement.Highlight = True
.Execute findText:="the", Replace:=wdReplaceAll
End With
End Sub
来源:https://stackoverflow.com/questions/50291072/find-and-highlight-issue-in-word-addin