如何通过单击 Word 2010 复选框来运行 VBA 宏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21456090/
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
How to run a VBA Macro by clicking Word 2010 Checkbox?
提问by minastaros
I want to run a macro when I click a checkbox in Word 2010.
我想在Word 2010 中单击复选框时运行宏。
Note that I neither want the "Legacy Forms" checkbox nor the "ActiveX" ones!They do only work in some "protected document mode" and look ugly, but I want the new ones which can be selected and unselected just when you write the document, and which look much nicer to me.
请注意,我既不需要“旧表单”复选框,也不需要“ActiveX”复选框!它们只能在某些“受保护的文档模式”下工作并且看起来很丑,但我想要新的,它们可以在您编写文档时选择和取消选择,并且对我来说看起来更好。
I know, with the legacy forms, you can directly insert a Macro when entering the form element and one for leaving it, and you can catch the event in VBA like
我知道,对于遗留表单,您可以在进入表单元素时直接插入一个宏,并在离开它时插入一个宏,并且您可以在 VBA 中捕获事件,例如
Sub CheckboxXY_Click()
But that does not work with the Word 2010 checkboxes, even when I give them a description and a tag name.
但这不适用于 Word 2010 复选框,即使我为它们提供了描述和标签名称。
Repeat: these are the forms I want to use (just in case somebody would advise me to use the Legacy ones):
重复:这些是我想使用的表格(以防万一有人建议我使用旧版):
And that's how they look like in the document (with mouse hover):
这就是它们在文档中的样子(鼠标悬停):
I cannot believe that I was the first one who tried this...
我不敢相信我是第一个尝试这个的人......
回答by IAWeir
Make sure you go to the Document in your VBA Project and select "ContentControlOnEnter"
确保转到 VBA 项目中的文档并选择“ContentControlOnEnter”
You will have to specify which contentcontrol you want by using something like ContentControl.Title to specify which checkbox activates which part of your code as shown in the example below. (I also put in code to verify that the checkbox is checked in the example)
您必须使用 ContentControl.Title 之类的内容来指定您想要的内容控件,以指定哪个复选框激活代码的哪一部分,如下例所示。(我还输入了代码来验证示例中是否选中了复选框)
Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
If (ContentControl.Title = "Checkbox1" And ContentControl.Checked = True) Then
MsgBox "YAAY", vbOKOnly, "Test1"
End If
If (ContentControl.Title = "Checkbox2" And ContentControl.Checked = True) Then
MsgBox "BOOO", vbOKOnly, "Test2!"
End If
End Sub