2015-05-12 40 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