2015-05-12 47 views
0

我想从combobox1中选择组合框2中的唯一值。Excel中的组合框中的唯一值VBA

Column A    Column B 
--------    -------- 
Girls     Hair 
Boys     Hair 
Veg     Water 
Non-Veg    Water 

一旦我选择combobox1女孩(从列中检索“A”在Excel中),它应该显示在Excel中列“B”而不是两次“头发”的独特价值。

+0

列A \t列B 女孩\t头发 男孩\t头发 素食\t水 非素食\t水 –

+0

只有一个值对于女孩,为什么你需要把它放在一个组合框? – Davesexcel

+0

这只是一个例子。一旦我从列'A'中选择女孩,我想在列'B'中的combox2中添加唯一值。 –

回答

0

这里是那种链接选择的基础:

这将在ComboBox1实现独特的价值观:

Private Sub UserForm_Initialize() 
Dim Ws As Worksheet, _ 
    Dic As Object, _ 
    rCell As Range, _ 
    Key 'As String 

Set Ws = Worksheets("Sheet1") 
Set Dic = CreateObject("Scripting.Dictionary") 
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 

“还有就是把不重复值ComboBox2的一部分时,它匹配与ComboBox1标准:

当您更改ComboBox1的值,它会启动该代码,所以你需要在T 刷新这里提供的值在ComboBox2与您自己的测试。

Private Sub ComboBox1_Change() 

Dim Ws As Worksheet, _ 
    Dic As Object, _ 
    rCell As Range, _ 
    Key 'As String 

Set Ws = Worksheets("Sheet1") 
Set Dic = CreateObject("Scripting.Dictionary") 
Me.ComboBox2.Clear 'Clear all previously added elements 
Me.ComboBox2.Value = vbNullString 'Set active value as an empty string 

'------Here is where you need to do your tests------- 
For Each rCell In Ws.Range("B2", Ws.Cells(Rows.Count, "B").End(xlUp)) 
    If rCell.Offset(0, -1) <> Me.ComboBox1.Value Then 
    Else 
     If Not Dic.exists(LCase(rCell.Value)) Then 
      Dic.Add LCase(rCell.Value), Nothing 
     End If 
    End If 
Next rCell 

For Each Key In Dic 
    UserForm1.ComboBox2.AddItem Key 
Next 
End Sub 

而对于第三个组合框代码:

Private Sub ComboBox2_Change() 

    Dim Ws As Worksheet, _ 
     Dic As Object, _ 
     rCell As Range, _ 
     Key 'As String 

    Set Ws = Worksheets("Sheet1") 
    Set Dic = CreateObject("Scripting.Dictionary") 
    Me.ComboBox3.Clear 'Clear all previously added elements 
    Me.ComboBox3.Value = vbNullString 'Set active value as an empty string 

    '------Here is where you need to do your tests------- 
    For Each rCell In Ws.Range("C2", Ws.Cells(Rows.Count, "C").End(xlUp)) 
     If rCell.Offset(0, -1) <> Me.ComboBox2.Value And rCell.Offset(0, -2) <> Me.ComboBox1.Value Then 
     Else 
      If Not Dic.exists(LCase(rCell.Value)) Then 
       Dic.Add LCase(rCell.Value), Nothing 
      End If 
     End If 
    Next rCell 

    For Each Key In Dic 
     UserForm1.ComboBox3.AddItem Key 
    Next 
    End Sub 
+0

非常感谢。它真的有用。我想根据combobox2的选择在'C'列中的combobox3中添加唯一值。我需要实现的所有更改 –

+0

我在上面的代码中用combobox2.value替换了combobox1.value,用“C”替换了“B2”,但它不起作用。请协助。 –

+0

请花时间阅读这些链接,并进入SO精神:http://stackoverflow.com/help/asking和http://stackoverflow.com/help/dont-ask 对于另一个级联组合框,只需将代码在ComboBox1_Change中放入ComboBox2_Change并将ComboBox2切换为ComboBox3并将ComboBox1切换为ComboBox2并将B2切换为C2将C和B切换为C “'它会工作。 **但严重的是,去阅读我分享的链接,特别是第二个** – R3uK