循环通过Userform的单列

时间:2015-03-24 19:32:30

标签: vba userform

我在VBA中使用过userforms并了解了一些循环遍历所有控件的技巧。但是,我遇到了这个问题,并且需要一种方法来读取行的值并根据“Area”“Shift”的值将列推理到数组中的。这两列的可能值如图所示。

基本上我需要的是像

For Each ctl In Me.Controls
    If somectl.Value = "Kitting" And otherctl.Value = "1" Then
        ReDim Preserve somearray(i)
        somearray(i) = ctl.Value
    End If
Next ctl

enter image description here

1 个答案:

答案 0 :(得分:2)

如果您已设法标准化您的命名,您可以这样做:

Private Sub CommandButton1_Click()
    Dim i As Integer
    Dim areaCB As MSForms.ComboBox
    Dim shiftCB As MSForms.ComboBox
    Dim reasonCB  As MSForms.ComboBox
    Dim somearray

    For i = 1 To 3 ' 3 or more depending on how may you have in your form
        Set areaCB = Me.Controls("areadd" & i)
        Set shiftCB = Me.Controls("shiftdd" & i)
        Set reasonCB = Me.Controls("reasondd" & i)

        If areaCB.Value = "Kitting" _
        And shiftCB.Value = "1" Then
            If IsArray(somearray) Then
                ReDim Preserve somearray(UBound(somearray) + 1)
                somearray(UBound(somearray)) = reasonCB.Value
            Else
                somearray = Array(reasonCB.Value)
            End If
        End If
    Next
End Sub

例如,在 areadd1 中, 1 是行号。
相应地,右边的 ComboBox shiftdd1 ,依此类推。
这只是为了给你一个想法。修改它以满足您的需求。