C#: Searching a text in Word and getting the range of the result

Viewed 24165

I can find a text in a Word file via:

Word.Range range = wordApp.ActiveDocument.Content;
Word.Find find = range.Find;
find.Text = "xxx";
find.ClearFormatting();
find.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing);

This tells me if the text is found. But I need the range of the found text-piece.

5 Answers

Can be solved like this:

    /// <summary>
    /// Find all
    /// </summary>
    /// <param name="range"></param>
    /// <param name="findText">Find content</param>
    public static List<Range> FindAll(this Range range, string findText)
    {
        int start = range.Start;
        int end = range.End;

        List<Range> ranges = new List<Range>();

        range.Find.Execute(FindText: findText, MatchCase: true);
        while (range.Find.Found)
        {
            //The search will change the range, here is an out-of-range judgment
            if (range.Start > end)
                break;

            ranges.Add(range.Document.Range(range.Start, range.End));
            range.Find.Execute(FindText: findText, MatchCase: true);
        }

        //Restore the original range
        range.SetRange(start, end);
        return ranges;
    }

You can also create an extension method:

        /// <summary>
    /// 查找第一个
    /// </summary>
    /// <param name="range"></param>
    /// <param name="findText">查找内容</param>
    /// <returns>没有找到为空</returns>
    public static Range FindFirst(this Range range, string findText)
    {
        int start = range.Start;
        int end = range.End;

        bool isOk = range.Find.Execute(FindText: findText, MatchCase: true);
        if (isOk)
        {
            var newRange = range.Document.Range(range.Start, range.End);
            range.SetRange(start, end);
            return newRange;
        }
        else
            return null;
    }
Related