VBA: Why is Range.Find.Execute deselecting text in a Word doc?

白昼怎懂夜的黑 提交于 2019-12-11 02:19:44

问题


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):

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:


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.



来源:https://stackoverflow.com/questions/27696257/vba-why-is-range-find-execute-deselecting-text-in-a-word-doc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!