Search code examples
excelvbauserform

Validate that at least 1 checkbox is checked


I have search for the same question, and I saw a few of the similar post, however my Userform still can't work. I am new to VBA and Userform.

I have a total of 12 Checkboxes (12 Months), and I have to check that at least one of the CheckBox is checked.

Dim atLeastOneChecked As Boolean
atLeastOneChecked = False
Dim ctrlNCK As Control
For Each ctrlNCK In Controls
    If TypeName(ctrlNCK) = "chkMonth" Then
        If ctrlNCK.Value = True Then atLeastOneChecked = True
    End If
Next ctrlNCK

If Not atLeastOneChecked = True Then
    MsgBox "Month cannot be empty.", vbExclamation, "Input Data"
    Exit Sub
    End If

Solution

  • This is untested, but try:

    If Left(ctrlNCK.Name,8) = "chkMonth" Then
    

    I wouldn't ever expect the Type to be "chkMonth". This assumes that each relevant CheckBox name starts with "chkMonth".

    If you only ever want one, and only one, month chosen, I'd consider using OptionButtons in a Frame.