filter a query based on multiple list boxes in a f

2019-07-04 02:18发布

问题:

I have an Access database with two tables: "contacts" and "country" These contain a number of fields in each.

I have a query, "Filter", that brings these two tables together.

I want to create a form with as many list boxes as there are fields in the query. A user can open the form and select multiple data from each list box - the row sources are tied back to the two tables above. Then on the click of a button the query would be displayed and filters would be applied dependent on the users selections in the list boxes. If nothing is selected then the query is displayed without filters. Similarly the user is not required to make selections from all the list boxes.

Any help would be much appreciated. I have lifted some code from other websites which has allowed me to apply filters for a single list box. The difficulty is expanding for multiple list boxes. Is this an absurd request??

PS I can post my existing code however I believe that this is now a 'red herring' and would be best starting fresh.

回答1:

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