Search code examples
vbafor-loopvisibilityuserform

Change the visibility of UserForm elements via For loop


I have an array of constant size populated with ComboBoxes. When the user clicks on another UserForm element (a CheckBox in my case) the visibility each ComboBox in this array should change. When I run the below snippet of code, I get 424 Object Required error. I am most likely making a simple syntactic mistake, but any guidance on how to properly write this would be appreciated.

Private Sub MyCheckBox_Click()
    Dim CheckBoxStatus as Boolean: CheckBoxStatus = MyUserForm.MyCheckBox.Value

    Dim ComboBoxArray(0 To 4)
    ComboBoxArray(0) = MyUserForm.ComboBox1  ' This line repeated and modified for the other 4 array members
    
    If CheckBoxStatus Then
        For i = LBound(ComboBoxArray) To UBound(ComboBoxArray)
            CompetitorComboBoxes(i).Visible = True ' THIS IS WHERE THE ERROR IS THROWN
        Next i

    Else
        ' Appropriate else code to set the visibilities to False

End Sub

Solution

  • You need to Set object references so:

    Set ComboBoxArray(0) = MyUserForm.ComboBox1 
    

    Dim ComboBoxArray(0 To 4) creates an array with 5 elements not the 4 you would need for your 4 boxes so you should Dim ComboBoxArray(0 To 3) (or just Dim ComboBoxArray(3)) otherwise the last element will be empty and calling .Visible on it will fail.

    (I'm assuming CompetitorComboBoxes is a typo for ComboBoxArray)