Go Premium for a chance to win a PS4. Enter to Win


Missing operator error in query on form controls

Posted on 2016-09-23
Medium Priority
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 23
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 23

Assisted Solution

by:crystal (strive4peace) - Microsoft MVP, Access
crystal (strive4peace) - Microsoft MVP, Access earned 2000 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 is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.


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 49

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

Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Instead of error trapping or hard-coding for non-updateable fields when using QODBC, let VBA automatically disable them when forms open. This way, users can view but not change the data. Part 1 explained how to use schema tables to do this. Part 2 h…
Explore the ways to Unlock VBA Project Password Excel 2010 & 2013 documents. Go through the article and perform the steps carefully to remove VBA Excel .xls file.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

927 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