filter a query based on multiple list boxes in a form

北城以北 提交于 2019-12-01 21:51:52

My understanding is you have a form with unbound multi-select list boxes and you want to open a query in Datasheet View and have that query based on the list box selections.

That means you must examine the ItemsSelected collection of each list box and update the query's SQL property accordingly.

On my test form, which includes a multi-select list box named lstFname, selecting the names Jack, Dave, and Tim in the list box, then clicking the command button (cmdOpenQuery), creates this SELECT statement.

SELECT c.*
FROM Contacts AS c
WHERE c.fname IN ('Dave','Jack','Tim')

Then that statement is saved as the SQL property of a query named qrySearchForm. And finally that query is opened in Datasheet View.

However my example includes only one list box, and you have several. So you have more work ahead to extend this simple example.

Here is my form's code module ...

Option Compare Database
Option Explicit ' <- include this in ALL modules!

Private Sub cmdOpenQuery_Click()
    Const cstrQuery As String = "qrySearchForm"
    Dim strNames As String
    Dim strSelect As String
    Dim varItm As Variant

    strSelect = "SELECT c.*" & vbCrLf & "FROM Contacts AS c"

    For Each varItm In Me.lstFname.ItemsSelected
        strNames = strNames & ",'" & _
            Me.lstFname.ItemData(varItm) & "'"
    Next varItm
    If Len(strNames) > 0 Then
        strNames = Mid(strNames, 2) ' discard leading comma
        strSelect = strSelect & vbCrLf & _
            "WHERE c.fname IN (" & strNames & ")"
    End If

    Debug.Print strSelect
    CurrentDb.QueryDefs(cstrQuery).Sql = strSelect
    DoCmd.OpenQuery cstrQuery
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!