Re: Restrict Find&Repalce to Selected Text



Jay,

"Trash." That is a little harse :-)

There is a eastern proverb. "Sometimes even experienced monkeys fall out of
the tree."

JGM, thanks for you suggestion.
--
Greg Maxey/Word MVP
See:
http://gregmaxey.mvps.org/word_tips.htm
For some helpful tips using Word.

Jay Freedman wrote:
> Hi Greg,
>
> You're right, my code is trash. I know I had it working last night,
> but after I posted it I threw away the file, so I don't know what I
> did. :(
>
> Anyway, you and Jean-Guy and Helmut have all come up with working
> versions. For clarity of understanding -- that is, absence of "magic"
> -- I prefer Jean-Guy's version.
>
>
> Greg Maxey wrote:
>> Jay,
>>
>> My test of the code you posted isn't working.
>>
>> I typed:
>>
>> Now is the time for all good men.
>>
>> Now is the time for all good men.
>>
>> Then selected the first.
>>
>> Running
>>
>> Sub FRinSelectionOnly()
>> Dim oRg As Range
>> Set oRg = Selection.Range
>> With oRg.Find
>> .Format = False
>> .Forward = True
>> .Wrap = wdFindContinue
>> .MatchWildcards = False
>> .Text = "time"
>> .Replacement.Text = "hour"
>> Do While .Execute(Replace:=wdReplaceOne) And
>> oRg.InRange(Selection.Range) Loop
>> End With
>> End Sub
>>
>> Resulted in "time" being replaced by "hour" in both the selected and
>> non-selected sentences.
>>
>> I changed your code a bit to:
>>
>> Sub FRinSelectionOnly1()
>> Dim oRg As Range
>> Set oRg = Selection.Range
>> With oRg.Find
>> .Format = False
>> .Forward = True
>> .Wrap = wdFindStop
>> .MatchWildcards = False
>> .Text = "time"
>> .Replacement.Text = "hour"
>> Do While .Execute(Replace:=wdReplaceAll)
>> Loop
>> End With
>>
>> Using wdFindStop vice wdFindContinue resulted in only the first (and
>> selected) sentence being altered.
>>
>>
>>
>> Jay Freedman wrote:
>>> On Thu, 21 Apr 2005 20:58:22 -0400, "TT" <tomtatham@xxxxxxxxxxx>
>>> wrote:
>>>
>>>> I would like to write a macro to do multiple Find/replace
>>>> operations but I want the operations confined to a block of text
>>>> selected by
>>>> the user. Can anyone point me to an example or sketch the approach?
>>>>
>>>> Thanks!
>>>>
>>>
>>> The key to this is to use a Range object to do the search in a loop,
>>> and check each iteration of the loop to make sure the range is still
>>> within the selected area:
>>>
>>> Sub foo()
>>> Dim oRg As Range
>>>
>>> Set oRg = Selection.Range
>>> With oRg.Find
>>> .Format = False
>>> .Forward = True
>>> .Wrap = wdFindContinue
>>> .MatchWildcards = False
>>> .Text = "dolor"
>>> .Replacement.Text = "dollar"
>>>
>>> Do While .Execute(Replace:=wdReplaceOne) _
>>> And oRg.InRange(Selection.Range)
>>> ' InRange is true if oRg is inside Selection.Range
>>> Loop
>>> End With
>>> End Sub


.



Relevant Pages