Cycling through a series of check boxes in VBA

In Word 2010 VBA:

I have a user form with several check boxes, say CheckBox1 through CheckBox6.

For each check box, in the actual document, there will be two check boxes (Check1Yes and Check1No, for example). In each case, the "No" box will be selected by default.

If I select a particular check box on the user form - say CheckBox3 - then in the document, Check3Yes should be selected (X'd) and Check3No cleared.

The following code works fine, but I'd have to have an If for each check box on the user form (in actuality there are over 40 of them - not all visible at once, however).

If CheckBox3.Value = True Then
    ActiveDocument.FormFields("Check3Y").CheckBox.Value = True
    ActiveDocument.FormFields("Check3N").CheckBox.Value = False
End If

What I'd really like is a way to cycle through all the check boxes on the user form - maybe with a For loop. But since the check box identifiers (CheckBoxN) aren't in an array, I can't just increment using the array index.

I've tried string concatenation - something like:

For I =1 to 3

   If "CheckBox" & I & ".value" = True then

         ActiveDocument.FormFields("Check" & I & "Y").CheckBox.Value = True
         ActiveDocument.FormFields("Check" & I & "N").CheckBox.Value = False
End If

But this produces strange gagging sounds from VBA (actually, you get an: run-time error

Any suggestions would be most appreciated.

Thank you!

Use

Dim acontrol As Control

Dim i as Long

For i = 1 To 3
    For Each acontrol In Me.Controls
        If acontrol.Name = "CheckBox" & i Then
            If acontrol.Value = True Then
                ActiveDocument.FormFields("Check" & i & "Y").CheckBox.Value = True
                ActiveDocument.FormFields("Check" & i & "N").CheckBox.Value = False
            Else
                ActiveDocument.FormFields("Check" & i & "Y").CheckBox.Value = False
                ActiveDocument.FormFields("Check" & i & "N").CheckBox.Value = True
            End If
        End If
    Next acontrol
Next i

Hope this helps,
Doug Robbins - MVP Office Apps & Services (Word)
dougrobbinsmvp@gmail.com
It's time to replace ‘Diversity, Equity & Inclusion’ with ‘Excellence, Opportunity & Civility’ - V Ramaswamy

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated October 5, 2021 Views 1,790 Applies to: