Find and Highlight issue in word addin

后端 未结 1 1562
自闭症患者
自闭症患者 2021-01-26 11:19

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 hi

1条回答
  •  清歌不尽
    2021-01-26 11:36

    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
    

    0 讨论(0)
提交回复
热议问题