Group: microsoft.public.word.vba.general
From: "Greg Maxey"
Date: Friday, February 22, 2008 6:30 PM
Subject: Re: Word 2003 search macro

Alan,

If you must use Selection then use something like this:

Sub Scratchmacro()
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
If Selection.Find.Execute Then
Selection.Delete Unit:=wdCharacter, Count:=1
Else
MsgBox "String not found"
End If
End Sub

If you would rather use a range then use something like this:

Sub ScratchmacroII()
Dim oRng As Word.Range
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Text = "searchstring"
If .Execute
oRng.Delete
Else
MsgBox "String not found"
End If
End With
End Sub


--
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Greg Maxey - Word MVP

My web site http://gregmaxey.mvps.org
Word MVP web site http://word.mvps.org
~~~~~~~~~~~~~~~~~~~~~~~~~~~~



Alan Stancliff wrote:
> 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


Safety Articles | Usenet Groups | Usenet News | Bluegrass