在word文档中查找范围内的匹配项

时间:2017-03-27 06:16:03

标签: c# ms-word office-interop

如果范围内有2个匹配项,有没有办法在指定范围内找到下一个匹配项。或者如果有任何方法可以获得所有比赛的列表。 目前我使用下面的互操作方法来查找匹配,但它只会突出显示第一个匹配。

bool found = foundRange.Find.Execute(ref oFindText, 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);

谢谢。

1 个答案:

答案 0 :(得分:1)

见内联评论:

 //Get any range you want
var range = app.ActiveDocument.StoryRanges[WdStoryType.wdMainTextStory];


var document = range.Document;

//We want the variable range to continue refering to the same Range at all times
var foundRange = range.Duplicate;

if (foundRange.Find.Execute("j", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, WdFindWrap.wdFindStop, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)) {
    Console.WriteLine("Found first");
    //After using .Execute(), FoundRange has been set to the found text
    Console.WriteLine(foundRange.Text);
}
else
{
    Console.WriteLine("Didn't find first");
}

//Set foundRange to start at the character after the last find and to end where the original range ends
foundRange = document.Range(foundRange.Start + 1, range.End);

//Repeat. Obviously you could use some kind of loop
if (foundRange.Find.Execute("j", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, WdFindWrap.wdFindStop, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing))
{
    Console.WriteLine("Found second");
    Console.WriteLine(foundRange.Text);
}
else
{
    Console.WriteLine("Didn't find second");
}

foundRange.Select(); //Just to verify. We don't need the selection object for anything