Find selected text

The following code finds instances of the word "Family" in a Word document. It selects and deletes instances. The code works fine, but I want to find all instances of only the selected words.

public void FindHighlightedText()
{
    const string filePath = "D:\\COM16_Duke Energy.doc";

    var word = new Microsoft.Office.Interop.Word.Application {Visible = true};
    var doc = word.Documents.Open(filePath);
    var range = doc.Range();

    range.Find.ClearFormatting();
    range.Find.Text = "Family";

    while (range.Find.Execute())
    {
          range.Select();
          range.Delete();
    }
    doc.Close();
    word.Quit(true, Type.Missing, Type.Missing);
}
+4
source share
1 answer

Set the Find.Highlight property to true.

Interop uses the same objects and methods that are available for VBA macros. You can find the actions, properties needed to complete the task by writing a macro with these steps and checking it.

Often, but not always, properties correspond to the user interface. If something is a property in the general Search field, this is probably a property in the interface Find.

, :

Selection.Find.ClearFormatting
Selection.Find.Highlight = True
With Selection.Find
    .Text = ""
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With

:

range.Find.ClearFormatting();
range.Find.Highlight=1;
...
while(range.Find.Execute())
{
    ...
}
+2

Source: https://habr.com/ru/post/1692770/


All Articles