On Fri, 22 Feb 2008 15:26:42 -0800, Alan Stancliff
>Hi all,
>
>In Word 2003, it is possible to write a VBA macro that searches for a
>string, positions the cursor at the string found, deletes the string,
>leaving the cursor where the string had been located. Such code might
>look like this:
>
> Selection.Find.ClearFormatting
> With Selection.Find
> .Text = "searchstring"
> .Replacement.Text = ""
> .Forward = True
> .Wrap = wdFindContinue
> .Format = False
> .MatchCase = False
> .MatchWholeWord = False
> .MatchWildcards = False
> .MatchSoundsLike = False
> .MatchAllWordForms = False
> End With
> Selection.Find.Execute
> Selection.Delete Unit:=wdCharacter, Count:=1
>
>However, if the string is not found, the macro deletes the character the
>cursor is resting on at the beginning of the search.
>
>What I want to know is if there is a way to test if the string is not
>found, so that another action can be taken.
>
>Such code might look like this:
>
> Selection.Find.ClearFormatting
>' on not found, go to label NoSuchStringExists
> With Selection.Find
> .Text = "searchstring"
> .Replacement.Text = ""
> .Forward = True
> .Wrap = wdFindContinue
> .Format = False
> .MatchCase = False
> .MatchWholeWord = False
> .MatchWildcards = False
> .MatchSoundsLike = False
> .MatchAllWordForms = False
> End With
> Selection.Find.Execute
> Selection.Delete Unit:=wdCharacter, Count:=1
> Exit Sub
>
>NoSuchStringExists:
> MsgBox "Sorry, I could not find this string"
>
>Regards,
>
>Alan Stancliff
The .Execute method returns a boolean result, True if it found what you asked
for and False if not. So you can write the end of the macro like this:
If Selection.Find.Execute Then
Selection.Delete Unit:=wdCharacter, Count:=1
Else
MsgBox "Sorry, I could not find this string"
End If
By the bye, I don't understand why you have Unit:=wdCharacter, Count:=1 in the
Delete statement.
--
Regards,
Jay Freedman
Microsoft Word MVP FAQ: http://word.mvps.org
Email cannot be acknowledged; please post all follow-ups to the newsgroup so all may benefit.