vba 在文档中查找字符串并删除其后的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/497624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find a string in a document and delete everything after it
提问by user51498
I want to find a string in a word document and delete everything after it.
我想在word文档中找到一个字符串并删除它之后的所有内容。
What is the best way to do this without using the Selection
object?
在不使用Selection
对象的情况下执行此操作的最佳方法是什么?
回答by barrowc
Use a Range
object instead. Straight outta the Word 2003 help:
改用一个Range
对象。直接脱离 Word 2003 帮助:
If you've gotten to the Find object from the Range object, the selection isn't changed when text matching the find criteria is found, but the Range object is redefined. The following example locates the first occurrence of the word "blue" in the active document. If "blue" is found in the document, myRange is redefined
如果您已从 Range 对象进入 Find 对象,则在找到与查找条件匹配的文本时不会更改选择,但会重新定义 Range 对象。下面的示例定位活动文档中第一次出现的单词“blue”。如果在文档中找到“blue”,则重新定义 myRange
Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="blue", _
Forward:=True
If myRange.Find.Found = True Then
Now use the SetRange
method of that Range
object to make the start of the range be the next character after the end of the string you searched for and make the end of the range be the end of the document:
现在使用该对象的SetRange
方法Range
使范围的开头成为您搜索的字符串结尾之后的下一个字符,并使范围的结尾成为文档的结尾:
myRange.SetRange (myRange.End + 1), ActiveDocument.Content.End
(TODO: You'll need to deal with the case when your string is the last thing in the document)
(待办事项:当您的字符串是文档中的最后一个内容时,您需要处理这种情况)
To delete the contents:
要删除内容:
myRange.Delete