Keep this from going out of range?

E

Ed from AZ

I have code which is supposed to find instances of 2 or more spaces
and replace them with one space. It's supposed to work within a set
range, but it keeps going out of the range all the way to the end of
the document. How do I stop it at the end of the range?

Ed

With oRng.Find
.ClearFormatting
.Text = "[! ] {2,}[! ]"
.MatchWildcards = True
While .Execute
Select Case oRng.Characters.First.Text
Case Is = "."
oRng.Text = oRng.Characters.First & " " &
oRng.Characters.Last
Case Is = ":"
oRng.Text = oRng.Characters.First & " " &
oRng.Characters.Last
Case Is = "-"
oRng.Text = oRng.Characters.Last
Case Else
oRng.Text = oRng.Characters.First & " " & oRng.Characters.Last
End Select
oRng.Collapse Direction:=wdCollapseEnd
Wend
End With
 
J

Jay Freedman

Hi Ed,

That's a pain, isn't it? :-S It's one of a number of situations where VBA
behaves differently from the same operation in the UI.

Declare another Range object, say

Dim oContainRange As Range
Set oContainRange = Selection.Range

Then change the .Execute line to

While .Execute And oRng.InRange(oContainRange)

The second part of the condition will be false if oRg is outside
oContainRange.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 

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