簡體   English   中英

Excel VBA中組合框中的唯一值

[英]Unique values in combobox in Excel VBA

從組合框1中選擇后,我想在組合框2中獲得唯一值。

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

一旦我在combobox1中選擇了Girls(從excel中的“ A”列檢索),它應該從“ B”列中顯示“ Hair”的唯一值,而不是excel中的兩倍。

這是這種鏈接選擇的基礎:

這將在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

'並且有一部分在與ComboBox1匹配條件時將唯一值放入ComboBox2中:

' 當您更改 ComboBox1 的值時 ,它將啟動該代碼,因此您需要使用自己的測試在那里刷新 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM