Reputation: 334
I know the question title is not clear, so hopefully I can clarify:
Consider the following VBA script (written by M. Paige):
Sub rem_space()
Set myRange = ActiveDocument.Content
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
This will replace each instance of " :" with ":".
The problem is that I have an arbitrary amount of spaces, and have to run it multiple times to eliminate all instances of " :".
So, what is the best way to modify this VBA script to make it have to only run once, resulting in any number of arbitrary spaces before a colon being removed.
Should the VBA script be recursive?
Should I search the document to determine the most spaces before a colon and then run the VBA script that number of times?
Would running the VBA script within a for loop say, 100 times catch everything?
What is the easiest solution to implement?
Upvotes: 1
Views: 373
Reputation: 12768
This one duplicates a call to .Execute
, but doesn't rely on an infinite loop.
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
Do While .Found
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
Loop
End With
Or perhaps a Do...Loop While
loop instead.
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
Do
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
Loop While .Found
End With
Upvotes: 1
Reputation: 35318
Try this:
Sub rem_space()
Dim myRange As Range
Set myRange = ActiveDocument.Content
Do While True
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
If (Not .Execute(Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue)) Then Exit Do
End With
Loop
End Sub
It loops indefinitely with the Do While True
and then exits only when the call to .Execute
returns false.
Upvotes: 1