我在组合框1中得到了唯一值,我想在combobox2中添加唯一值,其中combobox1项是匹配的。
例如:如果我选择combobox1测试为“INDIA”,那么它应该是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
答案 0 :(得分:3)
试试这个
'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
输出结果