Gaus Shaikh
Gaus Shaikh

Reputation: 11

Unique values in combo box in excel vba

I got the unique value in combo box1 and I want to add the unique values in combobox2 where combobox1 items is matching.

Eg: If I select the combobox1 test as "INDIA", it should so all the language in combobox2.

The data is saved in excel Product

Dim ws As Worksheet     
Dim rCell As Range

Set ws = Worksheets("Product")

'//Clear combobox   
ComboBox1.Clear

With CreateObject("Scripting.Dictionary")
    For Each rCell In ws.Range("A2", ws.Cells(Rows.Count, "A").End(xlUp))    
        If Not .exists(rCell.Value) Then     
            .Add rCell.Value, Nothing    
        End If   
    Next rCell

    ComboBox1.List = .keys  
End With

Upvotes: 0

Views: 15424

Answers (1)

Vasily
Vasily

Reputation: 5782

try this

'on userform initialization event fill combobox1 with unique items from "A"

Private Sub UserForm_Initialize()
    Dim ws As Worksheet, rCell As Range, Key
    Dim Dic As Object: Set Dic = CreateObject("Scripting.Dictionary")
    Set ws = Worksheets("Product")
    UserForm1.ComboBox1.Clear
    For Each rCell In ws.Range("A2", ws.Cells(Rows.Count, "A").End(xlUp))
        If Not Dic.exists(LCase(rCell.Value)) Then
            Dic.Add LCase(rCell.Value), Nothing
        End If
    Next rCell
    For Each Key In Dic
        UserForm1.ComboBox1.AddItem Key
    Next
End Sub

'on combobox1 click event fill combobox2 with unique items from column "B",
'where selected combobox1.value matched with cell value in column "A".
'you can change event to ComboBox1_Enter() or ComboBox1_Change() or
'another event depending on your needs

Private Sub ComboBox1_Click()
    Dim rCell As Range, Key
    Dim Dic As Object: Set Dic = CreateObject("Scripting.Dictionary")
    Set ws = Worksheets("Product")
    UserForm1.ComboBox2.Clear
    For Each rCell In ws.Range("A2", ws.Cells(Rows.Count, "A").End(xlUp))
        If rCell.Value = ComboBox1.Value Then
            If Not Dic.exists(LCase(rCell.Offset(, 1).Value)) Then
                Dic.Add LCase(rCell.Offset(, 1).Value), Nothing
            End If
        End If
    Next rCell
    For Each Key In Dic
        UserForm1.ComboBox2.AddItem Key
    Next
End Sub

output result

enter image description here

Upvotes: 5

Related Questions