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
  • 5
  • 4
LVL 19
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 19

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)

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 46

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?
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

LVL 19
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 19
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 19
ID: 41835857
the code for null propogation, which solved the issue, was given in #41813443

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Today's users almost expect this to happen in all search boxes. After all, if their favourite search engine juggles with tens of thousand keywords while they type, and suggests matching phrases on the fly, why shouldn't they expect the same from you…
Introduction The Visual Basic for Applications (VBA) language is at the heart of every application that you write. It is your key to taking Access beyond the world of wizards into a world where anything is possible. This article introduces you to…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

932 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now