在文档中查找一个字符串并删除它之后的所有内容

人气:764 发布:2022-10-16 标签: range ms-word vba ms-office document

问题描述

I want to find a string in a word document and delete everything after it.

What is the best way to do this without using the Selection object?

解决方案

Use a Range object instead. Straight outta the Word 2003 help:

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

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:

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

874