我有一个带有5个复选框内容控件的Word文档-用于显示在进行pdf和/或打印时选择(或不选择)哪些选项。他们本身实际上不需要执行任何操作,在代码方面很明智。
我有一个用户窗体,其中包含5个复选框,它们与文档中的5个复选框相对应。用户可以选择任何,一个或所有这些用户窗体复选框,并且我希望Word文档内容控制复选框匹配。
为简单起见,我已将内容控制复选框命名为与用户窗体复选框相同,以期在代码正常工作后遍历代码。
打开用户窗体时,以下内容有效:
Private Sub UserForm_Initialize()
Dim x As Variant
Dim z As control
On Error GoTo quit
For Each x In Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE")
For Each z In Me.Controls
If z.Name = x And ActiveDocument.SelectContentControlsByTitle(x).Item(1).Checked = True Then z.Value = True
Next z
Next x
quit:
End Sub
这在技术上是可行的,但是有点笨拙,因为只有一个“ ChkA”或“ ChkB”等实例,但是此代码循环遍历每个复选框的每个名称,这意味着它在实际执行25次检查时它只需要做5。
但是,当尝试将复选框值从用户表单移回Word文档时,上面的“相同”代码(但相反)无效,即:
Private Sub cmdEnter_Click()
Dim x As Variant
Dim z As control
For Each x In Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE")
For Each z In Me.Controls
If z.Name = x And z.Value = True Then ActiveDocument.SelectContentControlsByTitle(x).Item(1).Checked = True
Next z
Next x
Unload Me
End Sub
这会在“对于每个z ...”行中给出类型不匹配错误。
我想做的是用变量名引用我的用户窗体复选框,以便我可以遍历它们,例如以下内容?
Dim x as Variant
Dim y as String
Dim z as control
x = Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE")
For i = 0 To 4
y = x(i)
Set z = Me.Controls(y)
ActiveDocument.FormFields(y).CheckBox.Value = z.Value
Set z = Nothing
Next i
还是类似的东西?
答案 0 :(得分:0)
对于那些感兴趣的人,我已经弄清楚了:
Option Explicit
Dim i As Integer
Dim x As Variant
Dim z As control
Private Sub UserForm_Initialize()
On Error Resume Next
x = Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE") 'names of both userform and content control checkboxes
For i = 0 To 4
Set z = Me.Controls(x(i))
If ActiveDocument.SelectContentControlsByTitle(x(i)).Item(1).Checked = True Then z.Value = True
Next i
Set z = Nothing
End Sub
Private Sub cmdEnter_Click()
On Error Resume Next
x = Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE") 'names of both userform and content control checkboxes
For i = 0 To 4
Set z = Me.Controls(x(i))
If z.Value = True Then
ActiveDocument.SelectContentControlsByTitle(x(i)).Item(1).Checked = True
Else
ActiveDocument.SelectContentControlsByTitle(x(i)).Item(1).Checked = False
End If
Next i
Set z = Nothing
Unload Me
End Sub
这现在可以完成我需要做的事情,并且可以按计划进行扩展。希望它对某人有用。
答案 1 :(得分:0)
由于文档中和用户窗体中的复选框具有对应的名称,因此无需使用数组。只需遍历UserForm上的控件,并使用控件名称来寻址内容控件。
Option Explicit
Dim ctl As MSForms.Control
Private Sub UserForm_Initialize()
For Each ctl In Me.Controls
If Left(ctl.Name, 3) = "Chk" Then
ctl.Value = ActiveDocument.SelectContentControlsByTitle(ctl.Name).Item(1).Checked
End If
Next ctl
End Sub
Private Sub cmdEnter_Click()
For Each ctl In Me.Controls
If Left(ctl.Name, 3) = "Chk" Then
ActiveDocument.SelectContentControlsByTitle(ctl.Name).Item(1).Checked = ctl.Value
End If
Next ctl
Unload Me
End Sub