Search code examples
excelvba

Code help for Excel VBA for-loop which checks if multiple ListBoxes have values?


I have a Userform (Userform1) which has 4 listboxes (ListBox1 through 4) which all have entries in them. The form-user selects the entry in the list, and then hits a CommandButton (CommandButton_1). The VBA Macro then writes the value from each Listbox into cells on an excel log sheet. The code to populate the listboxes with items and to write the results into the spreadsheet are working.

However, I would like to be able to check to ensure that all the listboxes have a selection. They must always all be filled in prior to writing the data, or else we lose data integrity during later analysis.

I have figured out how to check if an individual listbox has no selection, but I'd like to generalize it to be able to account for any number of listboxes. So far I have tried:

'Attempt 1

     For Each Control In Me.Controls
         If Controls.Name Like "Listbox*" Then
             If Controls.Value <> "" Then
                 Else: MsgBox ("You must select a value for every list.")
                 GoTo ERROR_ENDSUB
             End If
         End If
     Next

A1 gave me error 438: Obect doesn't support this property or Method (If Controls.Name line).

'Attempt 2

     Dim sh as Worksheet
     Set sh = ThisWorkbook.Sheets("Downtime")
     For i = 1 To 4
         If "sh.listbox" & i & ".value" <> "" Then
             Else: MsgBox ("You must select a value for every list.")
             GoTo ERROR_ENDSUB
         End If
     Next

A2 just doesn't function, I can leave the lists empty and it still writes data with no Msgbox.

'Attempt 3
    
    Dim LB as ListBox
    For i = 1 To 4
        Set LB = ListBoxes("Listbox" & i)
        If LB.Value <> "" Then
            Else: MsgBox ("You must select a value for every list.")
            GoTo ERROR_ENDSUB
        End If
    Next

A3 gave a compile error: Sub or function not defined (highlighted Listboxes()).

Please forgive me if I'm not 100% familiar with the VBA Object model of functions/methods. I'm a chemical engineer who got a reputation for being good at excel (the formula side of things), and my company has been giving me larger and larger spreadsheet-automation tasks. Eventually they got too big, and now I've been trying for the past week or so to pick up VBA with no prior coding experience.


Solution

  • For example:

    Private Sub UserForm_Activate()
        Dim con As Control
        For Each con In Me.Controls
            If TypeName(con) = "ListBox" Then
                Debug.Print "Found listbox: " & con.Name
            End If
        Next con
    End Sub