在 word 插件中查找并突出显示问题

Find and Highlight issue in word addin

我曾经强调 'word' 使用这个 code.It 在 '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