Excel VBA填充工作表中的父子下拉源

时间:2018-10-24 11:45:26

标签: excel vba excel-vba

我有一个包含以下数据的工作表,以及两个用户名分别为ComboBox1(父级)和ComboBox2(子级)的组合框

Parent |Child
-------|------
  A    |   1
  A    |   2
  A    |   3
  X    |   100
  X    |   101
  X    |   102

使用以下代码,我将不同的值带入了“父级”组合。

Dim s As String, r As Integer, nr As Integer, wr, v
Set wr = Sheet1.Range("A1:A10")
nr = wr.Rows.Count
With ComboBox1
 .Clear
 For r = 1 To nr
  v = wr(r, 1)
  If InStr(s, v & ",") = 0 Then
   s = s & v & ","
   .AddItem (v)
  End If
 Next
End With

我正在寻找帮助,以根据“父级”组合中的选定值填充子级组合!

1 个答案:

答案 0 :(得分:0)

我建议使用Dictionary来记住ComboBox1中的哪些条目已经存在,因为您可以轻松地使用dict.Exists(NewItem)进行测试。

ComboBox2的数据需要在ComboBox1_Change事件上自动重新初始化。

请注意,您应该使用更具描述性的变量名s, r, nr, wr, v毫无意义,而ComboRange1NewItem之类的名称对于人类来说则很好读。使您的生活更加轻松,并减少错误。

Option Explicit

Sub InitComboBox1()
    Dim ComboRange1 As Range
    Set ComboRange1 = Sheet1.Range("A1", Sheet1.Cells(Rows.Count, "A").End(xlUp))

    ComboBox1.Clear

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")

    Dim i As Long
    For i = 1 To ComboRange1.Rows.Count
        Dim NewItem As String
        NewItem = ComboRange1.Cells(i, 1).Text

        If Not dict.Exists(NewItem) Then
            dict.Add NewItem, 0
            ComboBox1.AddItem NewItem
        End If
    Next i
End Sub

Private Sub ComboBox1_Change()
    Dim ComboRange2 As Range
    Set ComboRange2 = Sheet1.Range("A1", Sheet1.Cells(Rows.Count, "A").End(xlUp)).Resize(ColumnSize:=2)

    ComboBox2.Clear

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")

    Dim i As Long
    For i = 1 To ComboRange2.Rows.Count
        If ComboRange2.Cells(i, 1).Text = ComboBox1.Value Then
            Dim NewItem As String
            NewItem = ComboRange2.Cells(i, 2).Text

            If Not dict.Exists(NewItem) Then
                dict.Add NewItem, 0
                ComboBox2.AddItem NewItem
            End If
        End If
    Next i
End Sub