So for whatever reason, I'm having trouble getting my VBA code to loop through the form control checkboxes on a worksheet in order to have a 'select all' check box. I came across the following two different methods that supposedly work in doing this:
Method 1:
Sub SelectAll_Click()
Dim CB As CheckBox
For Each CB In ActiveSheet.CheckBoxes
If CB.Name = ActiveSheet.CheckBoxes("cbSiteAll").Name Then
MsgBox CB.Name & ": " & CB.Value, vbOKOnly
CB.Value = ActiveSheet.CheckBoxes("cbSiteAll").Value
Else
MsgBox CB.Name & ": " & CB.Value, vbOKOnly
End If
Next CB
End Sub
Method 2:
Sub SelectAll_Click()
Dim CB As Shape
Dim sh As Worksheet
Set sh = ActiveSheet
For Each CB In sh.Shapes
If CB.Type = msoFormControl Then
If CB.FormControlType = xlCheckBox Then
MsgBox CB.Name, vbOKOnly
If CB.Name <> Application.ActiveSheet.CheckBoxes("cbSiteAll").Name Then
CB.Value = Application.ActiveSheet.CheckBoxes("cbSiteAll").Value
MsgBox xCheckBox.Name & ": " & xCheckBox.Value, vbOKOnly
End If
End If
End If
Next CB
End Sub
The message boxes I entered to try and debug what was happening. For both of the above, the loop starts but the only message box I get relates to the box that I ticked to which I've assigned the macro. It does not appear to loop through any of the other checkboxes (although the validation for the checkbox works as the loop at least recognises the item ticked/unticked as a checkbox.
I have no idea why either of these are not working given the above and I've spent a fair bit of time looking for answers that address this specific issue and working through the logic to myself to no avail. Alas, I hand it over to the internet to see if they can help.
Thanks in advance.
CB.ValuetoApplication.ActiveSheet.CheckBoxes(CB.Name).Value, and (judging by your subroutine name) probably change"cbSiteAll"to"SelectAll". I don't use form controls often enough to know whether this is the easiest way to do it, but I do know that it worked for me.If CB.Name = ActiveSheet.CheckBoxes("cbSiteAll").Name ThentoIf CB.Name <> ActiveSheet.CheckBoxes("cbSiteAll").Name Then- you were only changing the value of the"cbSiteAll"checkbox to be itself.