Find and Highlight issue in word addin

坚强是说给别人听的谎言 提交于 2019-12-02 17:25:03

问题


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

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!