Search code examples
excelvbaformsuserform

How to loop through listboxes in a vba user form


I have a VBA user form with 6 list boxes. Each list box contains related data in another list box on the same row e.g. list box 1 has an account code and list box 2 has an account name, etc. When a user selects an item within a listbox I want all other listboxes to select a corresponding row. How can I achieve this using a loop?

enter image description here

I know I can explicitly reference the list items as per excelcise example but I feel there must be a way to loop through available listboxes instead of listing them by name.


Solution

  • 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