如何在 Microsoft Word 中使用 VBA 忽略早期的内容控制?

How do you ignore earlier content control using VBA in Microsoft Word?

我有一个 Word 模板,文档中间有一个复选框内容控件。单击此复选框后,它会使用 VBA 触发一些命令。但是,我在文档的前面部分也有纯文本内容控件和日期选择器内容控件,它们有助于为用户填写模板。选择这些框后,我不断收到错误消息 "Run-time error 6290 - This property is only available for check box content controls"。

我的问题 - 有没有什么方法可以忽略早期的内容控制框,只 运行 按下复选框时的代码?

我的代码现在看起来像这样:

Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
    If (ContentControl.Title = "Checkbox1" And ContentControl.Checked = True) Then
        *code in here*
    End If
End Sub

所以您会认为只有选中 Checkbox1 后才会触发代码...但较早的文本和日期字段给了我一个错误代码。有人知道怎么回事吗?

我不熟悉 "content control" 或 Word VBA,但在 Excel 中,为 .OnChange 事件编码时,确保单元格传递给 Sub 的是您要使用的(其中之一)。我假设这里也是如此。

我猜你的错误是在

ContentControl.Checked = True

你的 If 声明的一部分,所以试试这个:

Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
    If (ContentControl.Title = "Checkbox1") Then
      If ContentControl.Checked = True Then
        *code in here*
      End IF
    End If
End Sub

即,确保在测试复选框是否被选中之前查看复选框控件。

VBA 做有条件的捷径,所以它将评估 AND 条件中的所有语句,即使第一个是 False.