I do this kind of thing quite often. I have a form that allows users to select Clients, Campaigns, and Date range to filter a report. You can use the same logic even if your query is not used in a report.
The basic idea is to change the SQL where condition to include all selected items. For example, if client A and B are selected, the sql where clause would be: where client=’A’ or client=’B’. I use 2 queries for this. For example, qryMyQuery-SQL and qryMyQuery-Rpt. The first query would be my stable query that contains only a Where clause for date. The sql from this query is copied, modified and then used to change the sql in my report query. Also, I have 3 labels in the report header that list the date range and each selected item or <All> if no items were selected from the list box.
Private Sub Report_Open(Cancel As Integer)
On Error GoTo Bungled
Dim strTitle As String: strTitle = "Your Title"
Dim db As Database
Dim rs As Recordset
Dim strCampaign, strCampLbl, strClient, strClientLbl, strSQL As String
Dim ctl As Control
Dim varItem As Variant
Dim qd As QueryDef
Set db = CurrentDb()
DoCmd.OpenForm "frmReportCriteria", , , , , acDialog, "Same Date"
If Not IsLoaded("frmReportCriteria") Then
Cancel = True
End If
Set qd = CurrentDb.QueryDefs("ClientNetOfPOD-SQL")
strSQL = qd.SQL
qd.Close
strSQL = Left(strSQL, Len(strSQL) - 3) 'remove semi
Set ctl = Forms!frmReportCriteria.lstClient
If ctl.ItemsSelected.Count > 0 Then
strClient = " And (tblRevenue.Client ='"
If ctl.ItemsSelected.Count > 1 Then
strClientLbl = "Clients: "
Else: strClientLbl = "Client: "
End If
For Each varItem In ctl.ItemsSelected
strClient = strClient & ctl.ItemData(varItem) & "' OR tblRevenue.Client ='"
strClientLbl = strClientLbl & ctl.ItemData(varItem) & ", "
Next varItem
strClient = Left(strClient, Len(strClient) - 24) & ")"
Me.lblClient.Caption = Left(strClientLbl, Len(strClientLbl) - 2)
Else: Me.lblClient.Caption = "Clients: <All>"
End If
Set ctl = Forms!frmReportCriteria.lstCampaign
If ctl.ItemsSelected.Count > 0 Then
strCampaign = " And (tblRevenue.[Program Name] ='"
If ctl.ItemsSelected.Count > 1 Then
strCampLbl = "Campaigns: "
Else: strCampLbl = "Campaign: "
End If
For Each varItem In ctl.ItemsSelected
strCampaign = strCampaign & ctl.ItemData(varItem) & "' OR tblRevenue.[Program Name] ='"
strCampLbl = strCampLbl & ctl.ItemData(varItem) & ", "
Next varItem
strCampaign = Left(strCampaign, Len(strCampaign) - 32) & ")"
Me.lblCampaign.Caption = Left(strCampLbl, Len(strCampLbl) - 2)
Else: Me.lblCampaign.Caption = "Campaigns: <All>"
End If
Set qd = CurrentDb.QueryDefs("ClientNetOfPOD-Rpt")
qd.SQL = strSQL & strClient & strCampaign
qd.Close
Me.lblReportDte.Caption = "For Monday Week " & Forms!frmReportCriteria.BeginDate
Set ctl = Nothing
Abscond:
Exit Sub
Bungled:
DoCmd.Hourglass False
If Err.Number = 2450 Then
Cancel = True
Resume Abscond
Else
MsgBox Err.Number & ": " & Err.Description, vbCritical, strTitle
Resume Abscond
End If
End Sub