Missing operator error in query on form controls

Posted on 2016-09-23
Last Modified: 2016-10-09
I'm trying to write a query to return the selections on combo boxes in a form, which will run on the click of a command button, but I'm getting the "Missing operator" error.  Here's my code.  Can you spot the error?

Private Sub cmdGetMenuItems_Click()
Dim s As String
Dim strBase As String          'From SELECT to WHERE
Dim ctl As Access.Control
Dim strSQL As String            'the rest of the SELECT statement
Dim qdf As DAO.QueryDef        

Set qdf = CurrentDb.QueryDefs("qryRecipeNameAndDish")    

strBase = "SELECT [Recipe_Name] FROM tblRecipes WHERE [Recipe_Name] IN("

With Me
  For Each ctl In .Controls
    If ctl.ControlType = acComboBox Then
        If Not IsNull(ctl.Value) Then
            strSQL = strSQL & "'" & ctl.Value & "', "
'            s = Left$(strSQL, Len(strSQL) - 2) & ")"
'            MsgBox s
        End If
    End If
End With

qdf.SQL = strBase & Left$(strSQL, Len(strSQL) - 2) & ")"  'Creates query  
DoCmd.OpenQuery "qryRecipeNameAndDish", acViewNormal
Exit Sub

TIA for any help.
Question by:Cindy Aitken
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
LVL 21
ID: 41813399
try adding a space between IN and (

before you assign strSQL add this:
MsgBox strSQL
debug.print strSQL 

Open in new window

the message box shows you what it is and then if you need to copy it, you can press Ctrl-G in the Immediate (debug) window and make a query with it.  I believe if you look, however, you will see what is wrong.  If you do not, paste in the SQL and let us look at it.

Author Comment

by:Cindy Aitken
ID: 41813409
Thank you, Crystal.

I added the space between IN and (, but I'm still getting the error.  Debug.Print and the MsgBox only show the results of the statement, not the statement for creating the query itself.  When I look at the SQL for the query, I see:

SELECT tblRecipes.[Recipe_Name]
FROM tblRecipes
WHERE (((tblRecipes.[Recipe_Name]) In ('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','')));

In Datasheet view, the query is empty, even though the FOR loop retrieves the correct selections from the combo boxes.  They just aren't making it into the Select statement.

I've only been using Access and VBA for the past couple of weeks, so I'm not experienced enough to spot the error.  That's why I'm asking for help.  I'm pretty sure this is a simple syntax error, but I could stare at it for a month without seeing it.
LVL 21

Assisted Solution

by:crystal (strive4peace) - Microsoft MVP, Access
crystal (strive4peace) - Microsoft MVP, Access earned 500 total points
ID: 41813443
it appears that none of the comboboxes you are looping through have any value except a zero-length string.  Do you SEE values?

instead of
 If Not IsNull(ctl.Value) Then
since your controls obviously are set to a zero-length string, test for:
 If len(trim(nz(ctl.Value,""))) >0 Then

instead of
Dim strSQL As String
do this:
Dim vSQL As variant

before the loop starts:
vSQL =null

in the loop:
vSQL  = (vSQL  + ",") & """" & ctl.Value & """"

when the loop is done:
if not isnull(vSQL) then
  'combine criteria with strBase
  strBase = strBase  & vSQL & ")"
   'change the SQL for the query, which must already exist -- I will leave this up to you ;)
end if

here is a general function I often include to change the SQL for a query. The query will be created if it does not yet exist:
'~~~~~~~~~~~~~~~~~~~~~~~~~~ MakeQuery
Function MakeQuery( _
   ByVal pQryName As String _
   , ByVal pSQL As String _
   , Optional pdb As DAO.Database _
   ) As Boolean
'crystal, strive4peace
'... 6-3-08, 130417, 160630
   'set up the error handler
   On Error GoTo Proc_Err
   'initialize the return value
   MakeQuery = False
   'dimension a database object variable
   Dim db As DAO.Database
   'initialize the db object
   If Not pdb Is Nothing Then
      'if a database object was passed, then use it
      Set db = pdb
      'otherwise, use the current database
      Set db = CurrentDb
   End If
'   uncomment next statement if desired
'   Debug.Print pQryName & " > " & pSql
   'use the database object
   With db
      'look up the query name in the MSysObjects table
      If Nz(DLookup("[Name]", "MSysObjects", _
               "[Name]='" & pQryName _
               & "' And [Type]=5"), "") = "" Then
         'if query does not exist, create the query
         .CreateQueryDef pQryName, pSQL
         'if query already exists, update the SQL
         'if query is open, close it
         On Error Resume Next
         DoCmd.Close acQuery, pQryName, acSaveNo
         On Error GoTo Proc_Err
         .QueryDefs(pQryName).SQL = pSQL
      End If
      'refresh the query collection
   End With 'db
   MakeQuery = True
   'exit code
   On Error Resume Next
   'release object variable
   Set db = Nothing
   Exit Function
   'error handler
   MsgBox Err.Description, , _
     "ERROR " & Err.Number & "  MakeQuery"
   Resume Proc_Exit
End Function

Open in new window

for information on error handling:

1. basic error handling code for VBA (3:48)
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.


Author Comment

by:Cindy Aitken
ID: 41813475

That's just it -- the combo boxes DO have values.  I inserted a Debug.Print statement in the loop to make sure the values were being picked up.  Here's the Debug.Print output reflecting the actual values in the combo boxes:

"Bacon and Eggs")
"Bacon and Eggs","Avocado BLT")
"Bacon and Eggs","Avocado BLT","Yogurt")
"Bacon and Eggs","Avocado BLT","Yogurt","Shepherd's Pie")
"Bacon and Eggs","Avocado BLT","Yogurt","Shepherd's Pie","Waldorf salad")
"Bacon and Eggs","Avocado BLT","Yogurt","Shepherd's Pie","Waldorf salad","Wild Rice with Veggies")
"Bacon and Eggs","Avocado BLT","Yogurt","Shepherd's Pie","Waldorf salad","Wild Rice with Veggies","Corn Salsa")

It appears to be falling apart when the values collected by the  loop are added to the end of the Select statement.  I followed your instructions, and the query's SQL statement now ends after the From clause.  Somehow, the Where clause and all those quotes and commas have been stripped off:

SELECT tblRecipes.[Recipe_Name]
FROM tblRecipes;

The revised code is below.  Thank you for taking the time to look it over and help me track down the mistake.  

Private Sub cmdGetMenuItems_Click()
Dim s As String                               'Used with Debug.Print
Dim strBase As String                   'Select clauses
Dim ctl As Access.Control
Dim vSQL As Variant
   'Dim strSQL As String                  'Previously held the output of the loop
Dim qdf As DAO.QueryDef        

Set qdf = CurrentDb.QueryDefs("qryRecipeNameAndDish")    
strBase = "SELECT [Recipe_Name] FROM tblRecipes WHERE [Recipe_Name] IN ("
vSQL = Null

With Me
  For Each ctl In .Controls
    If ctl.ControlType = acComboBox Then
        If Not IsNull(ctl.Value) Then
            vSQL = (vSQL + ",") & """" & ctl.Value & """"
            s = Left$(vSQL, Len(vSQL)) & ")"
            Debug.Print s
        End If
    End If
End With

If Not IsNull(vSQL) Then
    qdf.SQL = strBase & Left$(vSQL, Len(vSQL) - 2) & ")"
End If
LVL 48

Expert Comment

by:Martin Liss
ID: 41813767
Could there be something in one of the names that causes Access to think that it's the end of the statement? What is the last item that shows up in the query string?
LVL 21
ID: 41813862
there are too many closing )

instead of Dim ctl As Access.Control
Dim ctl As Control

Accepted Solution

Cindy Aitken earned 0 total points
ID: 41813867
Crystal and Martin,

I managed to resolve the problem by changing the line:
    qdf.SQL = strBase & Left$(vSQL, Len(vSQL) - 2) & ")"
   qdf.SQL = strBase & vSQL & ")"

Guess Len was stripping off something important. :)

Thanks so much for your help!
LVL 21
ID: 41813871
you're welcome ~ happy to help

Glad you got it!

the beauty of null propagation (using a variant to construct the Where parts) is that you don't have to worry about adjusting the where clause afterward.

if the variable is initialized to Null, then in the loop, this:
vSQL  = (vSQL  + ",") & """" & ctl.Value & """"
means to only add a comma if vSQL is not null.
+ will make everything in the parentheses Null if anything is Null.
& concatenates Nulls.
I also used double quote instead of single quote in case one of the values may have a single quote. Inside a quoted string with double quotes, use 2 of them to get 1 of them

Author Comment

by:Cindy Aitken
ID: 41814341
Thank you, Crystal!  That's good information to know. :)  I was wondering about the double quotes, but it makes sense now.
LVL 21
ID: 41835857
the code for null propogation, which solved the issue, was given in #41813443

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s been over a month into 2017, and there is already a sophisticated Gmail phishing email making it rounds. New techniques and tactics, have given hackers a way to authentically impersonate your contacts.How it Works The attack works by targeti…
The Windows Phone Theme Colours is a tight, powerful, and well balanced palette. This tiny Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing WithEvents, one of Access' hidden gems.
In Microsoft Access, learn how to use Dlookup and other domain aggregate functions and one method of specifying a string value within a string. Specify the first argument, which is the expression to be returned: Specify the second argument, which …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question