如何使用UserForm CheckBox更改Word文档中的控件内容CheckBox?

How to use UserForm CheckBox to change Control Content CheckBox in Word Document?

我在 Word 文档中创建了一个带有复选框 'cbxYes' 和内容控件复选框 'docCbx'UserForm。我想勾选 UserForm 中的复选框 'cbxYes',然后更改 Word 文档中的内容控制复选框。 所以输入来自 UserForm 复选框,输出是 Content Control 复选框。

我已尝试多次搜索如何执行此操作,但找不到我需要的确切内容。大多数搜索都与 Excel 有关。老实说,我不知道自己在做什么。请。非常感谢正确的帮助。

Private Sub cbxYes_Click()

Dim oCC As ContentControl

If cbxYes.value = True Then
   cbxYes.value = "True"
   ActiveDocument.docCbx_Yes.value = True
Else
   cbxYes.value = "False"
   ActiveDocument.docCbx_Yes.value = False
End If

End Sub

我得到的错误是:

run-time error '438': Object doesn't support this property or method.

假设 "docCbx" 是您可以替换的内容控件的 标题

ActiveDocument.docCbx_Yes.value = True

来自

For Each oCC In  ActiveDocument.SelectContentControlsByTitle("docCbx")
  If (oCC.Type = wdContentControlCheckBox) Then 
    oCC.Checked = False
  End If
Next

和等效项,但使用 False,用于代码的其他分支。上面的代码将使用该名称更新 所有复选框类型 内容控件(名称在文档中不必是唯一的),但已标记为 "Contents cannot be edited" 的控件除外 -他们将保持不变。它通过什么都不做

来处理没有任何具有该名称的内容控件的情况。

如果 "docCbx" 是 Tag 的值,您将需要以下内容:

For Each oCC In  ActiveDocument.SelectContentControlsByTag("docCbx")
  If (oCC.Type = wdContentControlCheckBox) Then 
    oCC.Checked = False
  End If
Next

如果 docCbx 是其他东西,我建议您将 Titles and/or 标签提供给您的内容控件并使用上述方法。否则,您应该修改您的问题以准确说明您如何命名控件 "docCbx".

您收到错误是因为向文档添加内容控件不会创建文档的新成员 object,而向用户表单添加表单控件会创建表单的新成员 object. (事实上​​,文档确实有一种更像表单 object 的机制,但它已经被弃用了很长时间。)

问题中显示的代码适用于 ActiveX 复选框,而不是内容控件。 (只是为了让事情变得更复杂,Word 还有复选框 表单字段 需要另一种代码语法。)

无法通过 Document object 直接引用内容控件名称 - 必须通过 ContentControls collection 完成。可以在“属性”对话框中为内容控件分配 Title and/or 和 Tag

多个内容控件可以有相同的名称或标题,这使得代码有点复杂。查询 Document.ContentControls("Title") returns a collection(具有该标题的所有内容控件)。

如果您知道是哪一个,则可以使用 Item 方法直接选择它(而不是通过 collection),指定它是 n 内容控件(内容控件顺序的索引)。这通常在一个人知道只有一个人时使用。

另请注意,为了 "check" 或 "uncheck" 内容控制复选框,应使用 Checked 属性。所以:

Private Sub cbxYes_Click()

Dim oCC As ContentControl
Set oCC = ActiveDocument.SelectContentControlsByTitle("docCbx").Item(1)

If cbxYes.value = True Then
   'cbxYes.value = "True" not needed
   occ.Checked = True
Else
   'cbxYes.value = "False" not needed
   oCC.Checked = False
End If

End Sub