0

我有包含 CheckBox1...19 和 OptionButton1...3 的 UserForm4,以及 TextBox1、CommandButton1、2。

当 OptionButton 1 = True 时,我想遍历所有 CheckBox 并将每个复选框设置为 True。

我得到的错误状态是“找不到对象”并且 i = 21,n = 23。当我只有 19 个复选框时,它们是如何变得如此之高的?

谢谢!

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
4

1 回答 1

1

您是否最初创建了 19 个以上并删除了一些?每个 VBA 对象都有一个唯一的名称。以您的方式执行此操作可能会导致各种问题。

例如,如果您创建 10 个 CheckBox 并删除其中的 8 个,则其余两个可能被命名为 Checkbox8 和 Checkbox9。所以你的循环根本不会击中它们。

另外,为什么不执行以下操作:

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
于 2013-09-23T20:09:54.193 回答