在 For-Next 循环期间按顺序显示控件 vba

Display controls with order during For-Next loop vba

我有一个带有很多控件的 VBA 应用程序。 我想在 For-Next 循环中按阅读顺序访问控件。

' Parcours des contrôles de l'userform
For Each cCont In Me.Controls

   ' TypeName(cCont)
    MsgBox (cCont.Name)

Next cCont

实际上,我想我正在访问创建日期...

你知道我是否可以配置阅读顺序?

谢谢

一种方法是按 TabIndex 属性 对它们进行排序。将选项卡索引设置为所需的顺序,然后使用:

Private Sub test()

    Dim cCont As Control
    Dim i As Integer
    Dim maxIndex As Integer
    Dim controls As Object
    Dim key As Variant

    Set controls = CreateObject("Scripting.Dictionary")

    'Add controls to dictionary, key by tabindex property
    For Each cCont In Me.controls
        maxIndex = IIf(maxIndex < cCont.TabIndex, cCont.TabIndex, maxIndex)
        controls.Add cCont.TabIndex, cCont
    Next cCont

    'Get controls in order
    For i = 0 To maxIndex
        If controls.exists(i) Then
            MsgBox controls(i).Name
        End If
    Next i

End Sub

发布的代码是一个很好的解决方案,我通过这个小改动使它对我可行。我通过了用户表单,因为我使用了模块中的代码。我排除了 LabelCommandButtonImage 以使 Valon Miller 的代码对我有用,否则描述的运行时错误会runtime error '-2147352573 (800 200037': Member not found显示。

Private Sub test(frm As UserForm)
    Dim cCont As Control
    Dim i As Integer
    Dim maxIndex As Integer
    Dim controls As Object
    Dim key As Variant

    Set controls = CreateObject("Scripting.Dictionary")

    'Add controls to dictionary, key by tabindex property
    For Each cCont In frm.controls
      If TypeName(cCont) <> "Label" And _
         TypeName(cCont) <> "Image" And _
         TypeName(cCont) <> "CommandButton" Then
            maxIndex = IIf(maxIndex < cCont.TabIndex, cCont.TabIndex, maxIndex)
            controls.Add cCont.TabIndex, cCont
      End If
    Next cCont

    'Get controls in order
    For i = 0 To maxIndex
        If controls.exists(i) Then
          Debug.Print controls(i).Name & vbTab & i
            MsgBox controls(i).Name
        End If
    Next i

End Sub

-----------------------------------------

最初我需要一个解决方案来使 sql 语句的顺序与我的表单控件的顺序同步。我想这样做:

fld1 = recordset1.value
fld2 = recordset2.value
fld3 = recordset3.value

正在寻找一种解决方案来按顺序获取我的控件和我的 SQL 语句,例如 field1 -> recordset.value1。

因此,我没有使用 taborder 对控件进行排序,而是创建了控件数组。即

sub useControlArray()
    dim a as variant, rs as new recordset, strSQL as string
    strSQL = "select fld1, fld2, fld3 from table"
    rs.open strSQL, connection
    a = array("fld1", "fld2", "fld3")
    'This array would help like this:
    for i = lbound(a) to ubound(a)
        frm.controls(a(i)) = rs(i)
        debug.print frm.controls(a(i)) ' Form is a user form
    next i
end sub

这会将控件限制为使用与我的 SQL 语句中相同的顺序填充它们所需的控件数量,并且我不需要注意控件是否存在。

希望对您有所帮助。