easy question

R

Ryan

When searching through a document for a specific word
using a macro, how do you stop the search before the end
of the document. (for example stop at the word "End")

Thanks
Ryan
 
J

Jay Freedman

Hi, Ryan,

When you're setting the parameters of the .Find object, such as .Text and
..Forward, also set

.Wrap = wdFindStop
 
R

Ryan

Jay,
Sorry, I am pretty new to VBA for Word so this may seem
like a stupid question:

In my code I already have .Wrap = wdFindStop but where do
I set it to stop at a specific word?

Thanks
Ryan
 
J

Jay Freedman

Hi, Ryan,

To expand a bit on Jonathan West's parallel answer to your question:

(1) You can't do this with Selection.Find. You must declare and set a Range
object, and use the Range object's .Find.

(2) To search from the beginning of the document to, say, the word "End"
that occurs somewhere in the document, you have to set the Range object so
that its Start and End are at those two places. You could do this by
bookmarking the place where you want to stop, or you could do a preliminary
Find to look for it.

Let's assume you have a bookmark named "end" that covers the word "End" in
the document. Then you could do this:

Dim MyRange As Range

Set MyRange = ActiveDocument.Range
MyRange.End = _
ActiveDocument.Bookmarks("end").Range.End

With MyRange.Find
.ClearFormatting
.Text = "find this"
.Wrap = wdFindStop
.Forward = True
.Format = False
If .Execute Then
MyRange.Select
Else
MsgBox "Not found"
End If
End With

If the text "find this" occurs in the document, but only after the "end"
bookmark, then this code would display the message box instead of searching
past the bookmark.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top