Selection.Find

V

vbaNOOB

Hi,

Is it possible to add some custom function while running the selection.find??
E.g.
Every time I find the str "abcdefg" in the doc, I need to bookmark it and do
some
process. Can I use selection.find to achieve this?

Many Thanks
 
J

Jay Freedman

Hi,

Is it possible to add some custom function while running the selection.find??
E.g.
Every time I find the str "abcdefg" in the doc, I need to bookmark it and do
some
process. Can I use selection.find to achieve this?

Many Thanks

You can use a structure like this:

Sub Demo()
Dim oRg As Range
Set oRg = ActiveDocument.Range
With oRg.Find
.ClearFormatting
.Text = "stuff to find"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = False

Do While .Execute
' at this point, the range
' oRg contains the most
' recently found occurrence
' of the.Text string...
' do whatever you need to do
' for example:
MsgBox oRg.Text & " at " & oRg.Start

' prepare for next loop
oRg.Collapse wdCollapseEnd
Loop
End With
End Sub

I urge you very strongly not to use Selection.Find, because that moves
the cursor each time the find is successful. First, that means the
user sees the screen scrolling and flashing during the macro unless
you turn off screen updating, and you have to take special steps to
return the cursor to its original position when you're done. It also
drastically slows the macro because Word has to redraw the screen each
time the cursor moves. Using a Range object has none of those
drawbacks.

The 'Do While .Execute' statement relies on the fact that .Execute
returns the value True when it does find the search text, or the value
False if there are no more instances to find. Each time .Execute is
successful, the Range object is redefined to cover just the found
instance, and you can then work with it -- for example, insert a
bookmark there, or change its formatting, or copy it to another
document, whatever. Just put it in the macro instead of the MsgBox
statement.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 

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