excel 如何在vba用户窗体中循环列表框

klh5stk1  于 2023-02-14  发布在  其他
关注(0)|答案(2)|浏览(184)

我有一个VBA用户表单,有6个列表框。每个列表框包含同一行上另一个列表框中的相关数据,例如列表框1有一个帐户代码,列表框2有一个帐户名称等。当用户选择列表框中的一个项目时,我希望所有其他列表框都选择相应的行。我如何使用循环来实现这一点?

我知道我可以按照excelcise example显式地引用列表项,但是我觉得必须有一种方法来循环遍历可用的列表框,而不是按名称列出它们。

67up9zun

67up9zun1#

Private Sub CheckControls()

Dim contr As control

For Each contr In Controls
    If TypeName(contr) = "ListBox" Then
        Select Case contr.Name
            Case "ListBox1":
            Case "ListBox2":
            Case "ListBox3":
            'and so on....
        End Select
    End If
Next contr

End Sub
hmae6n7t

hmae6n7t2#

经过一点故障排除,我想我在控件集合中找到了答案。在每个列表框中,我调用一个过程,该过程采用现有列表框索引、topIndex(在使用滚动条时很有用)和它自己的名称。

Private Sub lbox_gl_account_Change()
  Call arrangeIndexOfLabels(Me.lbox_gl_account.listIndex, 
  Me.lbox_gl_account.topIndex, Me.ActiveControl.Name)
End Sub

arrangeIndexOfLabels过程循环访问集合中的所有控件,并且只影响类型为ListBox的控件。它更新除活动ListBox之外的所有ListBox的listIndex和topIndex。

'Change index location of other listbox items according to the selected one
Private Sub arrangeIndexOfLabels(lngListIndex As Long, lngTopIndex As Long, strActiveControl As String)
Dim ctrlItem As Control
For Each ctrlItem In Me.Controls
    If TypeName(ctrlItem) = "ListBox" Then
        'Only changing index position of other list boxes than selected
        If ctrlItem.Name <> strActiveControl Then
            ctrlItem.listIndex = lngListIndex
            ctrlItem.topIndex = lngTopIndex
        End If
    End If
Next ctrlItem

末端子组件

相关问题