Hi all,
I'm having real trouble specifying the items selected in a multi select list as criteria in a query. I've tried loads of different code from various forums but so far nothing has worked.
I got the following code from the Microsoft knowledge base but when I run it the debugger highlights the DoCmd.OpenQuery line in yellow and says I cancelled the previous operation;
Private Sub Command4_Click()
Dim Q As DAO.QueryDef, DB As DAO.Database
Dim Criteria As String
Dim ctl As Control
Dim Itm As Variant
' Build a list of the selections.
Set ctl = Me![List0]
For Each Itm In ctl.ItemsSelected
If Len(Criteria) = 0 Then
Criteria = Chr(34) & ctl.ItemData(Itm) & Chr(34)
Else
Criteria = Criteria & "," & Chr(34) & ctl.ItemData(Itm) _
& Chr(34)
End If
Next Itm
If Len(Criteria) = 0 Then
Itm = MsgBox("You must select one or more items in the" & _
" list box!", 0, "No Selection Made")
Exit Sub
End If
' Modify the Query.
Set DB = CurrentDb()
Set Q = DB.QueryDefs("MultiSelect Criteria Example")
Q.SQL = "Select * From Orders Where [CustomerID] In(" & Criteria & _
");"
Q.Close
' Run the query.
DoCmd.OpenQuery "MultiSelect Criteria Example"
End Sub
Can anyone help me with this please?
As an alternative I wrote some code to produce an SQL WHERE clause in a text box on a form but I don't know how to get the query to refer to this to look for its criteria. Any ideas?
Thanks!
I'm having real trouble specifying the items selected in a multi select list as criteria in a query. I've tried loads of different code from various forums but so far nothing has worked.
I got the following code from the Microsoft knowledge base but when I run it the debugger highlights the DoCmd.OpenQuery line in yellow and says I cancelled the previous operation;
Private Sub Command4_Click()
Dim Q As DAO.QueryDef, DB As DAO.Database
Dim Criteria As String
Dim ctl As Control
Dim Itm As Variant
' Build a list of the selections.
Set ctl = Me![List0]
For Each Itm In ctl.ItemsSelected
If Len(Criteria) = 0 Then
Criteria = Chr(34) & ctl.ItemData(Itm) & Chr(34)
Else
Criteria = Criteria & "," & Chr(34) & ctl.ItemData(Itm) _
& Chr(34)
End If
Next Itm
If Len(Criteria) = 0 Then
Itm = MsgBox("You must select one or more items in the" & _
" list box!", 0, "No Selection Made")
Exit Sub
End If
' Modify the Query.
Set DB = CurrentDb()
Set Q = DB.QueryDefs("MultiSelect Criteria Example")
Q.SQL = "Select * From Orders Where [CustomerID] In(" & Criteria & _
");"
Q.Close
' Run the query.
DoCmd.OpenQuery "MultiSelect Criteria Example"
End Sub
Can anyone help me with this please?
As an alternative I wrote some code to produce an SQL WHERE clause in a text box on a form but I don't know how to get the query to refer to this to look for its criteria. Any ideas?
Thanks!