这是我第一次问一个问题在这里所以这里有云:Word加载搜索永远循环
我在寻找,有一个Word文档中文字“标题1”或“标题2”风格的名字。一旦找到,我将为该文本的开头和文档的结尾设置一个新的范围,并调用一个方法来查找该范围中的第一个表格,如果第二列中有文本,则在第一列中找到第一个表格。现在我的问题发生在我的代码找到完全匹配的第一条记录时。一切正常,但Find.Execute进入永久循环,并不断找到相同的文本。我希望它继续搜索,直到文档结束。这里是我的代码,并在此先感谢:
public void TextFind(object findText, string reqCode)
{
Document doc = Application.ActiveDocument;
Range docRange = doc.Sections[1].Range;
var intCount = 0;
docRange.SetRange(0, docRange.Characters.Count);
if (findText == null) throw new ArgumentNullException("findText");
docRange.Find.Execute(findText, Forward: true, Wrap: WdFindWrap.wdFindStop);
while (docRange.Find.Found)
{
intCount++;
Style style = docRange.get_Style();
var styleName = style.NameLocal;
if (styleName == "Heading 1" || styleName == "Heading 2")
{
var endRange = doc.Sections[1].Range;
var docRange2 = docRange;
docRange2.SetRange(docRange.Start, endRange.End);
ApplyNumberingToTable(docRange2, reqCode);
}
docRange.Find.Execute(findText, Forward: true, Wrap: WdFindWrap.wdFindStop);
}
MessageBox.Show(intCount.ToString());
}
的intCount
和MessageBox
是由我来诊断问题的一种尝试。
尝试二号包括了:
所以我仍然被卡住,我试图将搜索范围添加到列表中,并运行在列表中的foreach,但每次的范围内改变参考该范围在列表中也会更改。我不能为我的生活弄清楚t5o如何在我的while循环中实例化Range。以下是我的代码:
public void TextFind(object findText, string reqCode)
{
Document doc = Application.ActiveDocument;
Range docRange = doc.Sections[1].Range;
var intCount = 0;
if (findText == null) throw new ArgumentNullException("findText");
var rangelist = new List<Range>();
var i = 0;
while (docRange.Find.Execute(findText, Forward: true, Wrap: WdFindWrap.wdFindStop))
{
rangelist = new List<Range> {docRange};
intCount++;
}
foreach (var range in rangelist)
{
Style style = range.get_Style();
var styleName = style.NameLocal;
if (styleName != "Heading 1" && styleName != "Heading 2") continue;
var endRange = doc.Sections[1].Range;
range.SetRange(range.Start, endRange.End);
ApplyNumberingToTable(range, reqCode);
}
if (intCount == 0) return;
MessageBox.Show(rangelist.ToString());
}
仍在寻找解决方法。 谢谢,
我试过,但无济于事。循环中的find.execute会跳过第二个结果,在我的测试中,它使用标题1样式的字符串。如果我删除了find.execute,循环仍会挂起满足if语句的第一个结果。将存储在数组中工作的所有范围,然后调用数组中每个范围的ApplyNumberingToTable可能工作? – NutsPanther