check all checkboxes

This doesn't seem to be working for me...what am I missing?

        Dim ctl As CheckBox
        For Each ctl In Controls
           ctl.Checked = True
LVL 67
Who is Participating?
Mike TomlinsonMiddle School Assistant TeacherCommented:
Dim cb As CheckBox
Dim ctl As Control
For Each ctl In Me.Controls
    If TypeOf ctl Is CheckBox Then
        cb = CType(ctl, CheckBox)
        cb.Checked = True
    End If

*** BUT *** this will only hit checkboxes directly contained by the FORM itself.  If the checkboxes are contained in another control (panel, groupboxes, etc) then you would need a recursive algorithm to find all of them.
sirbountyAuthor Commented:
ksir - can ya explain what we're doing here?  I'm not very familiar with ctype...does that statement convert the control to a checkbox before proceeding?  Why doesn't the fact that I've established ctl as a checkbox work?  Shouldn't the loop go through all checkboxes, since ctl isn't declared as a generic control? : \
Mike TomlinsonMiddle School Assistant TeacherCommented:
When you use Me.Controls, you iterate ALL controls directly contained by the form.  What if you have controls on your form that are not CheckBoxes?  This would cause an error since your code would attempt to convert say a TextBox to a CheckBox in your For...Next loop!

You are correct about the CType() function.  It is converting the "ctl" variable to a CheckBox if it passed the "TypeOf ctl Is CheckBox" test (which returns True if "ctl" is a CheckBox).
sirbountyAuthor Commented:
The way I read it was
Declare a variable as a checkbox control.  Now loop through all of those 'type' controls, not 'all' controls.
I guess it sort of makes sense, I just presumed that by declaring the ctl as a specific checkbox that that would/should limit the iteration to those types of controls only...
Thanx for the follow.
Mike TomlinsonMiddle School Assistant TeacherCommented:
Don't feel bad, your assumption is a pretty common one and the type of code you posted comes up on EE quite a bit.  =)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.