lundi 23 septembre 2019

Controlling Content Control Checkboxes Using Userform Checkboxes

I have a word document with 5 check box content controls - these are used to show which options have been selected (or not) when the document is pdf'd and/or printed. They themselves don't actually need to 'do' anything, code wise.

I have a userform which has 5 checkboxes, which corresepond to the 5 check boxes within the document. The user can select any, none, or all of these userform checkboxes, and I want the word document content control check boxes to match.

For the sake of simplicity I have named the content control checkboxes the same as the userform checkboxes, in a hope to loop through the code once I get it working.

The following works when opening the userform:

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

This does technically work, but is a little ineligent, since there is only one instance of "ChkA", or "ChkB", etc, but this code loops through each name for each checkbox, meaning it's performing 25 checks when really it only needs to be doing 5.

However, when trying to move the checkbox values from the userform back into the word document, the 'same' code above (but reversed) doesn't work, i.e.:

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

This gives a type mismatch error on the "For Each z ..." line.

What I want to be able to do is refer to my userform checkboxes with a variable name, so that I can loop through them, something like the following maybe?

    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

or something like that?




Aucun commentaire:

Enregistrer un commentaire