View Single Post
 
Old 11-07-2016, 09:30 AM
Robert K S Robert K S is offline Windows 7 64bit Office 2007
Novice
 
Join Date: Jul 2016
Location: Cleveland, Ohio
Posts: 10
Robert K S is on a distinguished road
Default Workarounds for the find "dynamic" range bug in VBA?

I have a script in which I want to do a bunch of "find-and-replace"s on a range defined by a selection in Microsoft Word. Something like in the code snippet below. The problem is, after the first find & replace the selection range changes and the new second find & replace call operates on portions outside the user-defined selection made before running the script. (Discussion of this bug here.)

Are there any workarounds for this issue? For example, is there any way to store the selection range endpoint values, update them with changed values (since the effective range may have changed with any replacements made), and then use the changed range values as the new find & replace range?

Code:
With Selection.Range.Find ' Replace "OLD" with "NEWTHING"
    .MatchCase = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Text = "OLD"
    .Replacement.Text = "NEWTHING"
    .Execute Replace:=wdReplaceAll
End With
With Selection.Range.Find ' Replace "REPLACEME" with "THEREPLACEMENT"
    .MatchCase = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Text = "REPLACEME"
    .Replacement.Text = "THEREPLACEMENT"
    .Execute Replace:=wdReplaceAll
End With
Reply With Quote