vba 如何在VBA中获取选定的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2074877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:13:37  来源:igfitidea点击:

How to get selected text in VBA

vbams-word

提问by Ethylparaben

I have a macro that changes the selected text, and I have it assigned to a button.

我有一个更改所选文本的宏,并将其分配给一个按钮。

It works perfectly when i run it directly from visual basic, but when I click the button, the button gets the focus and my text is no longer selected so the macro change the selected element to (button).

当我直接从visual basic运行它时它工作得很好,但是当我单击按钮时,按钮获得焦点并且不再选择我的文本,因此宏将所选元素更改为(按钮)。

How can I select the text and run the macro by clicking on the button and still have the text selected?

如何通过单击按钮选择文本并运行宏并仍然选择文本?

回答by Todd Main

The way to do this is to set the set the TakeFocusOnClickproperty of the CommandButton to False. Here are is the code I use.

这样做的方法是TakeFocusOnClick将 CommandButton的属性设置为False。这是我使用的代码。

Private Sub CommandButton1_Click()
    Dim Sel As Selection
    Set Sel = Application.Selection
    If Sel.Type <> wdSelectionIP Then
        MsgBox Sel.Text
    End If
End Sub

回答by Jay

Is the button embedded in the document? You may need to put it on a form that loads on top of the Word window or in a menu/toolbar, so that clicking it does not affect the selection in the document itself.

按钮是否嵌入在文档中?您可能需要将它放在加载在 Word 窗口顶部或菜单/工具栏中的表单上,以便单击它不会影响文档本身中的选择。

Edit:
I think you can use Application.Selection.Previousto get at what you need. You could use this to restore the selection after the click event, or to act upon that section of the document, or both.

编辑:
我认为你可以Application.Selection.Previous用来获得你需要的东西。您可以使用它来在单击事件之后恢复选择,或者对文档的该部分进行操作,或者两者兼而有之。

I assume that this is available in previous versions of Word, but have only confirmed its presence in 2007.

我认为这在早期版本的 Word 中可用,但仅在 2007 年才确认存在。

回答by David

You need to change TakeFocusOnClick to "False" in the Button Preferences.

您需要在按钮首选项中将 TakeFocusOnClick 更改为“False”。