error handling for find (.find) object

A

akh2103

Hello--does anyone know how to do error handling for the find object? I
am searching for certain variable text in a word document (the variable
is set from user input in a user form) and I want to generate an error
handling routine for cases when the user types in text that is not in
the document. So I need to know how to do an error handling routine
that checks to see if the find object exists and if it doesn't, I will
give them an error message and re-direct them to the user form. Any
help would be much appreciated. Thanks, Abe
 
J

Jay Freedman

It isn't really "error handling" because there isn't any error. There are
two ways to determine whether the requested text was found in the document.

(1) The property Selection.Find.Found or myRange.Find.Found will be True if
the requested text was found, and False if not.

(2) The Selection.Find.Execute or myRange.Find.Execute method returns a
boolean value that is the same as the .Found property.

Here are two code snippets to show how these are used. The "Else" clause is
often omitted because we don't want to do anything if the text wasn't found.

Sub foo1()
Selection.HomeKey wdStory
With Selection.Find
.Text = "hello"
.Execute
If .Found Then
Selection.Font.Bold = True
Else
MsgBox .Text & " was not found"
End If
End With
End Sub

Sub foo2()
Selection.HomeKey wdStory
With Selection.Find
.Text = "fox"
If .Execute Then
Selection.Font.Bold = True
Else
MsgBox .Text & " was not found"
End If
End With
End Sub

--
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