vbams-accesslistboxopenform

Access VBA How can I filter a recordset based on the selections in a multi select list box?


I am trying to use the OpenForm function to filter based on the selections in a multi select list box. what is the correct syntax for this, or is there a better way to go about it? For the sake of example let's say:

List Box has options Ken, Mike, and Sandy.

Car has options Car1, Car2, and Car 3. All cars are owned by 1 or more people from that list box.

If someone from the list box is selected, I would like to open a form containing the cars owned by those people selected.

Thank you!


Solution

  • Ok So I figured out a way to do it:

    1. Create a string to hold a query
    2. Use a For loop to populate the string based on each item selected
    3. Put that string as a filter in the OpenForm command.

    Here is the specific code I used to to it. My example in the original post used Cars and People, but my actual context is different: Estimators and Division of Work are the filters. Let me know if you have any questions about it if you're someone who has the same question! Since it might be confusing without knowing more about what exactly I'm trying to accomplish.

    Dim strQuery As String
    Dim varItem As Variant
    'query filtering for estimators and division list box selections
    strQuery = ""
    If Me.EstimatorList.ItemsSelected.Count + Me.DivisionList.ItemsSelected.Count > 0 Then
        For Each varItem In Me.EstimatorList.ItemsSelected
            strQuery = strQuery + "[EstimatorID]=" & varItem + 1 & " OR "
        Next varItem
        If Me.EstimatorList.ItemsSelected.Count > 0 And Me.DivisionList.ItemsSelected.Count > 0 Then
            strQuery = Left(strQuery, Len(strQuery) - 4)
            strQuery = strQuery + " AND "
        End If
        For Each varItem In Me.DivisionList.ItemsSelected
            strQuery = strQuery + "[DivisionID]=" & varItem + 1 & " OR "
        Next varItem
        strQuery = Left(strQuery, Len(strQuery) - 4)
    End If