查找并突出显示单词addin中的问题

我曾经使用这个代码突出显示’word’。它用在’for each’循环中,循环遍历字符串集合。 但问题是在突出显示所有单词之后..如果我们尝试更改文档中的任何一个单词,则所有高亮显示都会自动删除。

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 ); 

按照设计, HitHighlight只保留高亮显示直到编辑文档 – 这是查找任务窗格在用户执行非高级查找时的工作方式。

如果你想要一个永久性的高光,那么你需要通过使用Replacement.Highlight = true来做一些不同的操作,如下例所示。

 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相当于感兴趣的VBA读者:

 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