Forum Discussion

cking1333's avatar
cking1333
Copper Contributor
Aug 14, 2024
Solved

1 List with 2 dependent Combo boxes...is it possible?

Hi all,    Not sure if this ask is even possible but here goes...   I have a 2 column list. Column 1 contains different type of legislation (i.e. HTA, CAIA, TSSEA, etc.). Column 2 has charge desc...
  • djclements's avatar
    Aug 15, 2024

    cking1333 There's a few ways this can be accomplished. In the following example, I've used a structured Excel table on Sheet1 to hold the 2-column list, and I've named the two combo boxes cboType (parent) and cboOptions (dependent)...

     

    UserForm with Dependent ComboBox

     

    The code used in the module for UserForm1 was:

     

    Option Explicit
    
    Private Sub cmdCancel_Click()
        Unload Me
    End Sub
    
    Private Sub cboType_AfterUpdate()
        Dim arr As Variant, i As Long, str As String
        arr = Sheet1.ListObjects(1).DataBodyRange.Value
        str = Me.cboType.Value
        Me.cboOptions.Clear
        For i = LBound(arr, 1) To UBound(arr, 1)
            If arr(i, 1) = str Then
                Me.cboOptions.AddItem arr(i, 2)
            End If
        Next i
    End Sub
    
    Private Sub UserForm_Initialize()
        Dim dict As Object, arr As Variant, i As Long, str As String
        Set dict = CreateObject("Scripting.Dictionary")
        arr = Sheet1.ListObjects(1).DataBodyRange.Value
        For i = LBound(arr, 1) To UBound(arr, 1)
            str = arr(i, 1)
            If Not dict.Exists(str) Then
                dict.Add str, str
                Me.cboType.AddItem str
            End If
        Next i
        Set dict = Nothing
    End Sub

     

    When the user form is first initialized, the parent combo box is populated with the unique items from column 1. Each time the parent combo box is updated, the dependent combo box is cleared and re-populated with the matching options. Cheers!

Resources