C#:在Word中搜索文本并获取结果的范围
我可以通过以下方式在 Word 文件中查找文本:
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);
这会告诉我是否找到该文本。但我需要找到的文本片段的范围。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你有没有尝试过这个:
Have you tried this:
应该通过在其上执行 find 来更改范围对象。
因此,您可能会使用
range.Start
和range.End
来获取字符位置。参考
The range object should be changed by executing find on it.
So, likely you'd use
range.Start
andrange.End
to get the character positions.Reference
使用 find 方法获取单词的范围并格式化它。
Gets a range from word using find method and format it.
range.Find.Execute
如果找到,则返回true
,并将range
设置为找到的范围:请注意
range.Find.Execute<如果
range
已经与查找条件匹配(在第一个range.Find.Execute
之后),/code> 将搜索range
之后的范围。例如,此 VBA 宏将仅查找第二个“b”:
range.Find.Execute
returnstrue
if found, and setsrange
to the found range:Note that
range.Find.Execute
will search the range afterrange
ifrange
is already a match for the Find conditions (after the firstrange.Find.Execute
).For example, this VBA Macro will find only the second "b" :
可以这样解决:
还可以创建一个扩展方法:
Can be solved like this:
You can also create an extension method: