如何通过单击Word中的ContentControl复选框来运行VBA脚本

时间:2019-02-20 09:58:33

标签: vba ms-word word-vba

我试图通过单击contentcontrol复选框来选中所有contentcontrol复选框。但是如何通过单击带有标签D1的复选框来设置事件以运行此脚本

If ActiveDocument.SelectContentControlsByTag("D1")(1).Checked = True Then
   ActiveDocument.SelectContentControlsByTag("D1_M1")(1).Checked = True
   ActiveDocument.SelectContentControlsByTag("D1_M2")(1).Checked = True
   ActiveDocument.SelectContentControlsByTag("D1_M3")(1).Checked = True
End If
If ActiveDocument.SelectContentControlsByTag("D1")(1).Checked = False Then
   ActiveDocument.SelectContentControlsByTag("D1_M1")(1).Checked = False
   ActiveDocument.SelectContentControlsByTag("D1_M2")(1).Checked = False
   ActiveDocument.SelectContentControlsByTag("D1_M3")(1).Checked = False
End If

2 个答案:

答案 0 :(得分:0)

您可以使用文档事件,

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
    If ContentControl.Title = "a1" Then

    End If
End Sub

或者您也可以像这样添加自定义事件处理程序。

在标准模块中具有以下内容。打开文档时,需要运行此代码。

Public cls_CustomEventHandler As clsCustomEventHandler

Sub SetUpDocumentContentEventHandler()

Set cls_CustomEventHandler = New clsCustomEventHandler

Set cls_CustomEventHandler.wdDocumnetToListenTo = ActiveDocument

End Sub

,然后使用以下代码创建一个类模块clsCustomEventHandler

Public WithEvents wdDocumnetToListenTo As Document

Private Sub wdDocumnetToListenTo_ContentControlOnExit( _
                                ByVal ContentControl As ContentControl, _
                                Cancel As Boolean)

If ContentControl.Title = "a1" Then

End If

End Sub

答案 1 :(得分:0)

尝试将以下内容添加到文档或其模板的“ ThisDocument”代码模块中:

Private Sub Document_ContentControlOnExit(ByVal CCtrl As ContentControl, Cancel As Boolean)
With CCtrl
  If .Title = "D1" Then
    For i = 1 To 3
      ActiveDocument.SelectContentControlsByTag("D1_M" & i)(1).Checked = .Checked
    Next
  End If
End With
End Sub