如何在VBA中制作三级层叠组合框

时间:2019-05-22 21:09:07

标签: excel vba combobox

我正在尝试创建三个级联组合框(第三个依赖于第二个,第二个依赖于第一个)。我找到了一种创建和填充前两个方法的方法,但是我正在为第三个方法苦苦挣扎。请注意,我想从头三,一,二,三的三列开始填充它们。

我使用了https://www.encodedna.com/excel/how-to-create-cascading-combo-box-in-excel-using-vba.htm此处列出的方法,该方法在前两个方法中效果很好。我试图为第三个组合框编写一个类似于第二个组合框的附加Sub,但是它不起作用

Private Sub cmbDue_Change()
    ' THE CHANGE EVENT OF THE SECOND COMBO TO POPULATE THE THIRD COMBO BOX.

    If Trim(cmbDue.Text) <> "" Then

        SetConn     ' SET THE CONNECTION TO THE DATABASE.

        ' SQL QUERY TO FETCH VALUE IN THIRD COLUMN BASED ON THE SELECTED CATEGORY.
        sQuery = "SELECT Three FROM [First$] WHERE " & _
            "Two = '" & cmbDue.Text & "' " & _
            "ORDER BY Three"

        cmbTre.Clear          ' CLEAR THE THIRD COMBOBOX.


        If rs.State = adStateOpen Then
            rs.Close
        End If

        rs.CursorLocation = adUseClient

        ' POPULATE CASCADING COMBO BOX WITH VALUES.
        rs.Open sQuery, myConn, adOpenKeyset, adLockOptimistic
        If rs.RecordCount > 0 Then
            Do While Not rs.EOF
                cmbTre.AddItem rs.Fields(0).Value
                rs.MoveNext
            Loop
        End If
    End If
End Sub

此行不起作用:

    rs.Open sQuery, myConn, adOpenKeyset, adLockOptimistic

...虽然它在第一个子菜单中工作正常,但可以填充第二个组合框。 我没有收到具体的错误消息,只是被要求调试。

我的理解是rs.open应该会打开,并且ADODB记录集应包含我的原始表,该表包含该子表创建的数据

Option Explicit

Public myConn As New ADODB.Connection
Public rs As New ADODB.Recordset
Public sQuery As String

' SET A CONNECTION.
Sub SetConn()
    If myConn.State = adStateOpen Then
        myConn.Close
    End If

    Dim sConnString As String
    sConnString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" & _
        "DBQ=" & ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name

    myConn.ConnectionString = sConnString
    myConn.Open         ' OPEN THE CONNECTION.
End Sub

“ sQuery”应运行上一个子集中的SQL查询集,以便在我的表“ rs”(ADODB记录集)上运行,而“ myConn”应仅连接到记录集。

但这不起作用。

0 个答案:

没有答案