您如何阻止word find.execute()进入无尽的循环?
我正在使用.NET和VSTO写一个单词加载项。我需要在所有文本的所有情况下搜索页脚。我正在使用Word的find.execute()循环,如下所示。当它与页脚中表单元格中的内容控件中的文本匹配时,它将进入无尽的循环。它不断回到相同的范围。
为什么此代码会导致无尽的循环?在这一点之后,我该如何告诉Word继续搜索?
using Word = Microsoft.Office.Interop.Word;
...
Word.Range range = headerFooter.Range;
Word.Find find = range.Find;
while (find.Execute(FindText: wildcard,
MatchWildcards: true,
Forward: true,
Wrap: Word.WdFindWrap.wdFindStop))
{
System.Diagnostics.Trace.TraceInformation(range.Start + ", " + range.End);
}
代码给出了这样的输出:
192, 206
192, 206
192, 206
我尝试将循环内部范围的范围缩小到以下内容,但它仍然永远循环回到原始范围。
{
System.Diagnostics.Trace.TraceInformation(range.Start + ", " + range.End);
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
}
我正在运行Word版本Microsoft®Word,用于Microsoft 365 MSO(版本2205 Build 16.0.15225.20028)32-bit 。
I am writing a Word add-in using .NET and VSTO. I need to search a footer for all instances of some text. I am looping with Word's Find.Execute() as shown below. It goes into an endless loop when it matches the text in a content control in a table cell in the footer. It keeps going back to the same range.
Why would this code cause an endless loop? How can I tell Word to continue searching after this point?
using Word = Microsoft.Office.Interop.Word;
...
Word.Range range = headerFooter.Range;
Word.Find find = range.Find;
while (find.Execute(FindText: wildcard,
MatchWildcards: true,
Forward: true,
Wrap: Word.WdFindWrap.wdFindStop))
{
System.Diagnostics.Trace.TraceInformation(range.Start + ", " + range.End);
}
The code gives output like this:
192, 206
192, 206
192, 206
I tried collapsing the range to the end of the match inside the loop as follows, but it still loops forever back to the original range.
{
System.Diagnostics.Trace.TraceInformation(range.Start + ", " + range.End);
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
}
I am running Word version Microsoft® Word for Microsoft 365 MSO (Version 2205 Build 16.0.15225.20028) 32-bit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在此特定实例中,我能够通过将范围推进到下一个表单元格的开头来解决问题。我基于此论坛主题的第二篇文章: https://www.msofficeforums.com/word-vba/40986-infinite-loop-when-finding-styles.html
这是在此实例中修复它的代码。它可能不会在每种情况下解决:
In this particular instance, I was able to fix the issue by advancing the range to the beginning of the next table cell. I based this on the second post in this forum thread: https://www.msofficeforums.com/word-vba/40986-infinite-loop-when-finding-styles.html
Here is the code that fixed it in this instance. It may not fix it in every situation: