读取动态用户窗体复选框并填充数组

时间:2018-08-14 16:56:18

标签: excel vba userform

我有一个动态填充的用户窗体-

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

从代码段的最后一行可以看出,我还有一个命令按钮。

当我单击命令按钮时,我想用选中的复选框的Caption填充数组。

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

但是该数组未填充。我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

问题是这样的:

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

不带引号

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

FltrTpye必须是String而不是Double 但是有很多小错误,代码被重写:

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