2
votes

Why this VBA code ((initial part of a sub) modifies the visible selection in the Word document? I'm not modifying any selection. As per MSDN description:

"If you've gotten to the Find object from the Range object, the selection isn't changed when text matching the find criteria is found, but the Range object is redefined. (Taken from: Find Object (Word))

So the following code should just modify the Range, and not affect the selection at all...

Sub SelectTarget()
    Dim MyRange As Range
    Set MyRange = Selection.Range
    With MyRange.Find 'Searches for _AM or _PM  (_ is a space)
        .ClearFormatting
        .MatchWildcards = True
        .Text = " [AP]M"
        .Execute
    End With

This is a screenshot of a doc with some text selected (what I call the visible selection):

Visible text selection right before executing the <code>Range.Find</code> code

But executing the code step by step with F8 one can see that after the .Execute line, the visible selection in the document disappears and the text background remains all white with no selection at all, not even an insertion point.

I have tried entering Replacement.Clearformatting and Replace = ""lines in the code to try to prevent previous Find/Replace from interfering, but it doesn't change anything whatsoever... Any ideas?

1

1 Answers

1
votes

I'm not certain why it is setting MyRange to the selection rather than the selection's range, but perhaps Word considers those two to be synonymous. Try

Set MyRange = Selection.Range.Duplicate

so that changes to MyRange don't affect Selection.Range at all.