Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

vba - Find a string in a document and delete everything after it

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...