[英]Excel VBA to populate parent child drop down source from sheet
I have sheet with data like below and 2 combo boxes in user form with the names ComboBox1(parent) and ComboBox2(child)我有如下数据表和用户表单中的 2 个组合框,名称为 ComboBox1(parent) 和 ComboBox2(child)
Parent |Child
-------|------
A | 1
A | 2
A | 3
X | 100
X | 101
X | 102
With below code I took distinct values into Parent combo.使用下面的代码,我将不同的值带入了 Parent 组合中。
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
I am looking help to populate child combo based on selected value in Parent combo!我正在寻找帮助来根据父组合中的选定值填充子组合!
I recommend to use a Dictionary
to remember which entries in ComboBox1 already exists because you can easily test with dict.Exists(NewItem)
.我建议使用
Dictionary
来记住 ComboBox1 中的哪些条目已经存在,因为您可以轻松地使用dict.Exists(NewItem)
测试。
And the Data for ComboBox2 needs to automatically re-initialize on the ComboBox1_Change
event.并且 ComboBox2 的数据需要在
ComboBox1_Change
事件上自动重新初始化。
Note that you should use more descriptive variable names s, r, nr, wr, v
are pretty meaningless, while names like ComboRange1
or NewItem
are pretty good readable for humans.请注意,您应该使用更具描述性的变量名称
s, r, nr, wr, v
毫无意义,而像ComboRange1
或NewItem
这样的名称对人类来说可读性很好。 Makes your life much easier and results in less errors.使您的生活更轻松,并减少错误。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.