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

时间:2018-09-19 12:03:07

标签: excel vba for-loop controls

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

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

   ' TypeName(cCont)
    MsgBox (cCont.Name)

Next cCont

实际上,我认为我要在创建日期访问...

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

谢谢

1 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是按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