根据数组索引值

时间:2018-03-08 16:41:41

标签: arrays excel-vba checkbox userform vba

我希望迭代一个数组并根据数组索引值更改userform复选框的可见性,即如果复选框标题等于数组索引值,则相应地设置复选框可见性。通过defualt,复选框的可见性为真,我想隐藏其标题值不出现在数组中的复选框。我遇到的问题是,尽管条件设置,所有复选框都可见。我检查了所有迭代变量和数组值的值,一切似乎都没问题。我担心我是在错误地初始化用户表单还是在错误的位置?任何帮助将不胜感激。

With XrayFile

'populates array with values in variable worksheet range

    Dim Xrayrange As Integer

    lastpos = Sheets(Ship).Cells(Rows.Count, "A").End(xlUp).Row - 1

    Xrayrange = lastpos - 6

    'create array with variable dimensions based on worksheet range

    ReDim X_ray_pos(Xrayrange) As String

    Dim j As Integer

    'iterate through worksheet range and set array index to cell value

    For j = LBound(X_ray_pos) To UBound(X_ray_pos)

        X_ray_pos(j) = Sheets(Ship).Range("A7").Offset(j).Value2

    Next j


    'userform1 is where the checkboxes are located.  I chose to initialize the userform here thinking that it would matter for the iteration and change of the default state of the checkboxes

    userform1.Show

    userform1.Hide

    Dim num As Variant

    Dim i As Long

    'iterates through checkboxes (named "CB1", "CB2" etc) and compares checkbox caption to array index value

    For i = 0 To 55

        Set c = Reject_list.Controls("CB" & i)

            For Each num In X_ray_pos

                If c.Caption Like num Then

                    c.Visible = True

                    Exit For

                Else

                    c.Visible = False

                End If
            Next num
    Next i

1 个答案:

答案 0 :(得分:0)

从这个错误的代码:

For Each num In X_ray_pos  

    For i = 0 To 55

        Set c = Reject_list.Controls("CB" & i)

                If c.Caption Like num Then

                    c.Visible = True

                Else

                    c.Visible = False

                End If
            Next i
    Next num

对此解决方案:

For i = 0 To 55

        Set c = Reject_list.Controls("CB" & i)

            For Each num In X_ray_pos

                If c.Caption Like num Then

                    c.Visible = True

                    Exit For

                Else

                    c.Visible = False

                End If
            Next num
    Next i