Search code examples
excelvbauserform

Read Dynamic UserForm Checkboxes and Populate Array


I have a userform that I populate dynamically -

For Each J In Temp
    Set Cbx = UserForm1.Controls.Add("Forms.CheckBox.1")
    Cbx.Caption = J
    Cbx.Left = 15
    Cbx.Top = 15 + (17.5 * (Cntr - 1))
    Cntr = Cntr + 1
Next J

Cntr = 15 + (17.5 * (Cntr - 1)) + 50

UserForm1.CommandButton1.Top = Cntr - 35

I also have a command button as can be seen from the last line of the code snippet.

When I click the command button, I want to populate an array with the Caption of the checkboxes that are checked.

Private Sub CommandButton1_Click()
    Call Summary
End Sub

Sub Summary()

    Dim Num As Integer
    Dim I As Integer
    Dim FltrTypes() As Double

    Num = UserForm1.Controls.Count - 1

    ReDim Preserve FltrTypes(0)

    For I = 0 To (Num - 1)
        If Left(UserForm1.Controls(I).Name, 8) = "CheckBox" Then
            If UserForm1.Controls(I).Value = "True" Then
                FltrTypes(I) = UserForm1.Controls(I).Caption
            End If
        End If
    Next I

End Sub

But the array is not populating. Where am I going wrong?


Solution

  • the problem is this:

    If UserForm1.Controls(I).Value = "True" Then
    

    without quotes

    If UserForm1.Controls(I).Value = True Then
    

    FltrTpye must be String not Double however there are many little errors, the code rewritten:

    Dim Num As Integer
    Dim I As Integer
    Dim FltrTypes() As String
    Dim NFltrTypes As Long
    
    Num = UserForm1.Controls.Count - 1
    
    Erase FltrTypes
    NFltrTypes = 0
    For I = 0 To (Num - 1)
        If Left(UserForm1.Controls(I).Name, 8) = "CheckBox" Then
            If UserForm1.Controls(I).Value = True Then
                ReDim Preserve FltrTypes(NFltrTypes)
                NFltrTypes = NFltrTypes + 1
                FltrTypes(NFltrTypes - 1) = UserForm1.Controls(I).Caption
            End If
        End If
    Next I