PDA

View Full Version : How to Toggle All Checkboxes in a VBA Userform in Word



johndavidson
11-22-2013, 04:05 AM
I have a userform with multiple checkboxes. It would be useful to have a "toggle checkboxes" cmd button, but is there an easy way to loop through all the checkboxes, toggling their values, without having to code each checkbox by name? The names of them all begin with chk*, otherwise the checkbox names are unique strings. A couple of them are locked, so their values would need to remain the same, but they could be unlocked at the start and set explicitly at the end.

Thanks

John Davidson

mrojas
11-22-2013, 05:06 AM
Here's one way of doing it.


' Clear All Form Controls (using name) Dim ctl As Object
For Each ctl In Me.Controls
If Left(ctl.Name, 3) = "chk" Then
ctl.Value = False
ElseIf Left(ctl.Name, 3) = "txt" Then
ctl.Text = ""
ElseIf Left(ctl.Name, 3) = "cbo" Then
ctl.Text = ""
ctl.Clear
End If
Next
:yes

macropod
11-22-2013, 05:21 AM
Perhaps:

For Each ctl In Me.Controls
With ctl
If .Name Like "chk*" Then
.Value = False
Else
Select Case .Name
Case "somename", "anothername"
.Value = False
Case Else
End Select
End If
End With
Next

johndavidson
11-22-2013, 07:15 AM
Thanks to you both. For the sake of my education, I tried both, and both work just fine.

gmaxey
11-22-2013, 12:43 PM
Another perhaps more universal method (the checkbox could be named anything):


Private Sub CommandButton1_Click()
Dim oCtr As Control
For Each oCtr In Me.Controls
If TypeName(oCtr) = "CheckBox" Then
oCtr.Value = Not oCtr.Value
End If
Next
End Sub

johndavidson
11-22-2013, 08:43 PM
Thanks Greg. That works a treat as well, and the code is even tighter! How can one ever learn all the possible VBA-Word syntax? Especially as very much a part-timer.

gmaxey
11-22-2013, 09:03 PM
IMHO, full or part timer, one can't.

macropod
11-22-2013, 11:12 PM
Another perhaps more universal method (the checkbox could be named anything)
But you still need to either avoid processing the 'locked' checkboxes, or re-set them. Perhaps change:
oCtr.Value = Not oCtr.Value
to:
If oCtr.Locked = False Then oCtr.Value = Not oCtr.Value