VBA:为什么Range.Find.Execute在Word文档中取消选择文本? [英] VBA: Why is Range.Find.Execute deselecting text in a Word doc?

查看:843
本文介绍了VBA:为什么Range.Find.Execute在Word文档中取消选择文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此VBA代码((子的初始部分)修改了Word文档中的可见选择?我没有修改任何选择.按照MSDN描述:

如果您已从Range对象转到Find对象,则 找到符合查找条件的文本时,选择不会更改, 但是Range对象被重新定义. (摘自:查找对象(Word) )

因此,以下代码应仅修改范围,而根本不影响选择...

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

这是文档的屏幕截图,其中选择了一些文本(我称之为可见选择):

之前的可见文本选择

但是用F8逐步执行代码可以看到,在.Execute行之后,文档中的可见选择消失了,文本背景仍然是全白的,根本没有选择,甚至没有插入点.

我尝试在代码中输入Replacement.ClearformattingReplace = ""行以尝试防止以前的查找/替换"发生干扰,但它不会改变任何内容... 有任何想法吗?

解决方案

我不确定为什么将MyRange设置为所选内容而不是所选内容的范围,但是Word可能认为这两个是同义的.试试

Set MyRange = Selection.Range.Duplicate

以使对MyRange的更改完全不会影响Selection.Range.

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?

解决方案

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.

这篇关于VBA:为什么Range.Find.Execute在Word文档中取消选择文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆