【发布时间】:2019-10-19 21:45:24
【问题描述】:
我正在创建一个使用多个 ComboBox 的 excel 用户表单。第一个 ComboBox 列出了表格第 1 列中的值,下面的 ComboBox' 列出了以下列中的值。从 ComboBox 2 开始,也只根据前面的框列出值。所有 ComboBox' 仅显示唯一值。
这是我正在使用的当前代码:
Option Explicit
Private Sub ComboBox1_Change()
Call cValues(ComboBox1.Value, ComboBox2, 2)
End Sub
Private Sub ComboBox2_Change()
Call cValues(ComboBox2.Value, ComboBox3, 3)
End Sub
Private Sub ComboBox3_Change()
Call cValues(ComboBox3.Value, ComboBox4, 4)
End Sub
Private Sub ComboBox4_Change()
Call cValues(ComboBox4.Value, ComboBox5, 5)
End Sub
Private Sub ComboBox5_Change()
Call cValues(ComboBox5.Value, ComboBox6, 6)
End Sub
Private Sub UserForm_Initialize()
Dim Rng As Range
Dim Dn As Range
Dim Dic As Object
With Sheets("Listuni")
Set Rng = .Range(.Range("A2"), .Range("A" & Rows.Count).End(xlUp))
End With
Set Dic = CreateObject("scripting.dictionary")
Dic.CompareMode = vbTextCompare
For Each Dn In Rng: Dic(Dn.Value) = Empty: Next
Me.ComboBox1.List = Application.Transpose(Dic.keys)
End Sub
Sub cValues(txt As String, Obj As Object, col As Integer)
Dim Dn As Range
Dim Rng As Range
Dim Dic As Object
With Sheets("Listuni")
Set Rng = .Range(.Cells(2, col), .Cells(Rows.Count, col).End(xlUp))
End With
Set Dic = CreateObject("Scripting.Dictionary")
Dic.CompareMode = 1
For Each Dn In Rng
If Dn.Offset(, -1).Value = txt Then
If Not Dic.exists(Dn.Value) Then
Dic(Dn.Value) = Empty
End If
End If
Next Dn
Obj.List = Application.Transpose(Dic.keys)
End Sub
当用户重新选择前面的 ComboBox 时,会出现我遇到的问题。不会清除后续框,而是保留所有现有选择。
每次重新选择前面的 ComboBox 时,我都在寻找一种方法来清除/默认后续 ComboBox 的值。例如,如果我在 ComboBox 1 和 2 中进行了选择,然后在 ComboBox 1 中更改了我的选择,我希望 ComboBox 2 清除而不是显示我之前的选择。请注意,用户表单在启动时的默认位置在任何 ComboBox 中都没有显示任何值。
我曾尝试使用 .clear 方法进行更改,但这总是挂在:
Obj.List = Application.Transpose(Dic.keys)
我怀疑这是因为清除在技术上是一种更改,因此它不能根据空值将值列表转置到其他框。
【问题讨论】:
标签: vba excel combobox userform