Word Macro Replace gets out of selection

S

Sverk

Hi,
The macro below was recorded in Word 2003.
It contains three Replace operations, all performed on the same selection
that was made before the recording.
But when I Run the recorded macro on a new selection it gets out of the
selection and runs thorugh the whole document.
Stepping through it, I find that the first Replace (removes commas) works
OK, it stays within the selection, but the next Replace (replace paragraph
marks with commas) gets done to the whole document, and so does the third one.
The selection looks ok after the first (and second) Replace.
Seems one needs to insert something before the next Replace that redirects
it to the selection again.
But what?
Please help,
Sverk
CODE --------------------------------------------
Sub AuthorString()
'
' AuthorString Macro
' Macro recorded 4/19/2007 by Sverker Runeson
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = ","
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = ","
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "^w"
.Replacement.Text = " "
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
 
G

Greg Maxey

Your best bet is to avoid recorded macros when possible:

Sub ScratchMacro()
Dim oRng As Word.Range
Set oRng = Selection.Range
With oRng.Find
.Text = ","
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll
.Text = "^p"
.Replacement.Text = ","
.Execute Replace:=wdReplaceAll
.Text = "^w"
.Replacement.Text = " "
.Execute Replace:=wdReplaceAll
End With
End Sub

..
 

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