excel - Excel VBA从工作表填充父子下拉源
问题描述
我有如下数据表和用户表单中的 2 个组合框,名称为 ComboBox1(parent) 和 ComboBox2(child)
Parent |Child
-------|------
A | 1
A | 2
A | 3
X | 100
X | 101
X | 102
使用下面的代码,我将不同的值带入了 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
我正在寻找根据父组合中的选定值填充子组合的帮助!
解决方案
我建议使用 aDictionary
来记住 ComboBox1 中的哪些条目已经存在,因为您可以轻松地使用dict.Exists(NewItem)
.
并且 ComboBox2 的数据需要在ComboBox1_Change
事件上自动重新初始化。
请注意,您应该使用更具描述性的变量名称s, r, nr, wr, v
是毫无意义的,而名称 like ComboRange1
orNewItem
对人类来说非常易读。让您的生活更轻松,并减少错误。
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
推荐阅读
- c - 为什么 strtok_r 在 '.'(peroid)而不是 ','(逗号)处断开字符串?
- c# - Unity:使用 Rigidbody2D 的 Drag 来减慢飞行角色的速度
- mysql - 如何在“清洁架构”中实现“SQL 事务”?
- tarantool - 在 tarantool 从站中优先读取与写入
- css - 如何在引导期间为 react.js 中的包导入 CSS 文件?
- python - 如何跟踪我从矩阵中随机选择的行的行索引?
- c# - 如何从 IDictionary 中获取价值
在 VisitMember 通话中? - python - Matplotlib xaxis.set_major_formatter 不理解年份
- robotframework - Robot Framework:为某个库设置日志记录级别
- python-3.x - 使用循环和函数创建多个数据框