VBA级联依赖组合框

时间:2019-10-19 14:20:59

标签: vba combobox

您的第一个问题(请对我轻松!大声笑!)-我搜索了这个论坛和其他论坛,但找不到真正解决我问题的方法。我发现了这篇文章-有很大帮助:

Clear cascading ComboBox on reselection

但是问题是,第4个组合框似乎并没有限制数据-这允许选择无效的组合(这会引起问题!)。

我的源数据-非常类似于链接到上方的示例,即5列,标题和数据位于其下方。我希望组合框选择基本上起到过滤器的作用。

我的代码在下面-谁能帮忙或告知我哪里出问题了??:

Option Explicit

Private ws  As Worksheet
Private d   As Object

Private Sub UserForm_Initialize()
    Dim cel As Range, txt As String, rng As Range

    Set ws = Worksheets("JOBCODESEARCH")
    Set d = CreateObject("Scripting.Dictionary"): d.CompareMode = vbTextCompare

    Set rng = ws.Range(ws.Cells(2, 1), ws.Cells(ws.Rows.Count, 1).End(xlUp))

    For Each cel In rng: d(cel.Value) = Empty: Next
    ComboBox1.List = Application.Transpose(d.keys)
End Sub

Private Function setList(ByVal txt As String, ByRef cmb As ComboBox) As Object
    Dim xID As Long, rng As Range, cel As Range, x As Control

    xID = Right(cmb.Name, 1)
    For Each x In Me.Controls
        If TypeName(x) = "ComboBox" Then If Val(Right(x.Name, 1)) > xID - 1 Then x.Clear
    Next

    Set rng = ws.Range(ws.Cells(2, xID), ws.Cells(ws.Rows.Count, xID).End(xlUp))

    d.RemoveAll
    For Each cel In rng
        If cel.Offset(, -1) = txt Then
            If Not d.exists(cel.Value) Then
                d(cel.Value) = Empty
            End If
        End If
    Next
    If d.Count > 0 Then cmb.List = Application.Transpose(d.keys) Else cmb.Clear
End Function

Private Sub ComboBox1_Change()
    setList ComboBox1.Value, ComboBox2
End Sub
Private Sub ComboBox2_Change()
    setList ComboBox2.Value, ComboBox3
End Sub
Private Sub ComboBox3_Change()
    setList ComboBox3.Value, ComboBox4
End Sub
Private Sub ComboBox4_Change()
    setList ComboBox4.Value, ComboBox5
End Sub
rivate Sub ComboBox5_Change()
    setList ComboBox5.Value, ComboBox6
End Sub

0 个答案:

没有答案