I’m trying to open a form with a SQL condition set up from items selected in a listbox. I keep getting an error Syntax error in query expression. Which I don’t understand because if I create a new query and use the strSQL code it opens as designed. But using it to open a form just produces errors.
Private Sub cmdViewDash_Click() Dim varItem As Variant Dim PCSGroup As String Dim strDepartments As String Dim strSQL As String strDepartments = "" For Each varItem In Me.listBox1.ItemsSelected strDepartments = strDepartments & ",'" & Me.listBox1.ItemData(varItem) & "'" Next varItem If Len(strDepartments) = 0 Then MsgBox ("empty list items") strDepartments = "Like '*'" Else strDepartments = Right(strDepartments, Len(strDepartments) - 1) strDepartments = "IN(" & strDepartments & ")" End If strSQL = "SELECT ProposalTracker3.* FROM ProposalTracker3 WHERE (((ProposalTracker3.[PLCS Group]) In ('ILS','Depot')));" DoCmd.OpenForm "Dashboard", , , strSQL End Sub
Advertisement
Answer
Only valid SQL WHERE
clauses are to be used for whereCondition argument of DoCmd.OpenForm not a full SELECT
query.
Consider concatenating the strDepartments into a proper WHERE
condition.
If Len(strDepartments) = 0 Then MsgBox ("empty list items") strDepartments = "Like '*'" Else strDepartments = Right(strDepartments, Len(strDepartments) - 1) strDepartments = "IN (" & strDepartments & ")" End If strWhere = "(((ProposalTracker3.[PLCS Group]) " & strDepartments & "))" DoCmd.OpenForm "Dashboard", , , strWhere)
Alternatively, open the form as is and dynamically adjust its RecordSource
:
strSQL = "SELECT ProposalTracker3.* FROM ProposalTracker3" & _ & " WHERE (((ProposalTracker3.[PLCS Group]) " & strDepartments & "));" DoCmd.OpenForm "Dashboard" Forms!Dashboard.Form.RecordSource = strSQL Forms!Dashboard.Form.Requery