halcyon27
halcyon27

Reputation: 169

Error ending For/Next loop through CheckBoxes

I have UserForm4 which contains CheckBox1...19 and also OptionButton1...3, along with TextBox1, CommandButton1, 2.

When OptionButton 1 = True I want to loop through all CheckBoxes and set each to True.

The error I get states "Cannot find object" and i = 21, n = 23. How are they getting that high, when I only have 19 CheckBoxes?

Thanks!

Private Sub OptionButton1_Click()

Dim ctrl As Control
Dim i As Integer
Dim n As Integer

n = 0

For Each ctrl In UserForm4.Controls
    If TypeOf ctrl Is MSForms.CheckBox Then
        n = n + 1
    End If
Next ctrl

For i = 1 To n
    If UserForm4.Controls("CheckBox" & i) = False Then
        UserForm4.Controls("CheckBox" & i) = True
    End If
Next i

End Sub

Upvotes: 0

Views: 108

Answers (1)

enderland
enderland

Reputation: 14185

Did you create more than 19 initially and delete some? Each VBA object has a unique name. Doing this the way you are doing it is likely to cause all sorts of problems.

For example, if you create 10 CheckBoxes and delete 8 of them, the remaining two might be named Checkbox8 and Checkbox9. So your loop will not hit them at all.

Also, why not do something like the following:

Private Sub OptionButton1_Click()

Dim ctrl As Control
Dim i As Integer
Dim n As Integer

n = 0

For Each ctrl In UserForm4.Controls
    'this will make your problem really obvious
    debug.print ctrl.name
    If TypeOf ctrl Is MSForms.CheckBox Then
        ctrl.value = True
    End If
Next ctrl


End Sub

Upvotes: 1

Related Questions