excel vba组合框中的唯一值

0 vba

我在组合框 1 中获得了唯一值,我想在组合框 1 项目匹配的组合框 2 中添加唯一值。

例如:如果我选择 combobox1 测试为“印度”,那么它应该是 combobox2 中的所有语言。

数据保存在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
Run Code Online (Sandbox Code Playgroud)

Vas*_*zha 5

尝试这个

'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
Run Code Online (Sandbox Code Playgroud)

输出结果

在此处输入图片说明