Loop till all have been replaced

G

Gary''s Student

The following code replaces the first ten instances of [Rxxx] with [R1],
[R2], ... up to [R10].

Sub refs()
Dim c As Integer
Dim d As Integer
d = 1
For c = 1 To 10
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "[Rxxx]"
.Replacement.Text = "[R" & d & "]"
End With
Selection.Find.Execute Replace:=wdReplaceOne
d = d + 1
Next
End Sub

I want the code to replace all the instances, but don't want to perform the
FOR loop forever.

What to do?
 
D

Dave Lett

Hi Gary,

I think that you're looking for something like the following:

Public Sub test2()
Dim iCounter As Integer
iCounter = 1
With Selection
.HomeKey Unit:=wdStory
With .Find
.ClearFormatting
.Text = "(\[R)*(\])"
.Wrap = wdFindStop
.MatchWildcards = True
With .Replacement
.ClearFormatting
.Text = "\1" & iCounter & "\2"
End With
Do While .Execute(Replace:=wdReplaceOne)
Selection.MoveRight
iCounter = iCounter + 1
Selection.Find.Replacement.Text = "\1" & iCounter & "\2"
Loop
End With
End With
End Sub

HTH,
Dave
 
G

Gary''s Student

Works great. I must study the WHILE loop.
Thank you
--
Gary's Student


Dave Lett said:
Hi Gary,

I think that you're looking for something like the following:

Public Sub test2()
Dim iCounter As Integer
iCounter = 1
With Selection
.HomeKey Unit:=wdStory
With .Find
.ClearFormatting
.Text = "(\[R)*(\])"
.Wrap = wdFindStop
.MatchWildcards = True
With .Replacement
.ClearFormatting
.Text = "\1" & iCounter & "\2"
End With
Do While .Execute(Replace:=wdReplaceOne)
Selection.MoveRight
iCounter = iCounter + 1
Selection.Find.Replacement.Text = "\1" & iCounter & "\2"
Loop
End With
End With
End Sub

HTH,
Dave

Gary''s Student said:
The following code replaces the first ten instances of [Rxxx] with [R1],
[R2], ... up to [R10].

Sub refs()
Dim c As Integer
Dim d As Integer
d = 1
For c = 1 To 10
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "[Rxxx]"
.Replacement.Text = "[R" & d & "]"
End With
Selection.Find.Execute Replace:=wdReplaceOne
d = d + 1
Next
End Sub

I want the code to replace all the instances, but don't want to perform the
FOR loop forever.

What to do?
 

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