3

I'm attempting to retreive a resultset from a MS Access database using VBA for Excel. In the VBA code, I'm constructed a string equal to:

strSql = "SELECT * FROM Pricing WHERE Account In (''1234'', ''ABCD'') '; "

Note that there are 2 single quotes around the strings within the SQL statement. There is also a single quote before the semi-colon. If I'm not mistaken, this evaluates to:

SELECT * FROM Pricing WHERE Account In ('1234', 'ABCD') ;

This query works fine when run directly in MS Access. However, in Excel VBA, I keep getting the Run-time error:

Syntax error (missing operator) in query expression 'Account In (''1234'', ''ABCD'') '; '

Notice that this error actually cut off the first half of the SQL statement.

I've tried a few variations, using double-quotes, double double-quotes, no quotes, etc. etc.

Any advice?

Thanks.

4
  • 2
    There seems to be an un-matched quote right before your semi-colon. What if you remove that? What happens if you make the statement "SELECT * FROM Pricing WHERE Account In ('1234', 'ABCD');"? Commented Jan 11, 2016 at 18:59
  • 2
    Add Debug.Print strSql, run the code and see what it shows you in the Immediate window. Commented Jan 11, 2016 at 19:02
  • @HansUp This is really what solved it for me. Admittedly, I'm quite poor at debugging in Excel VBA. Thanks! Commented Jan 11, 2016 at 19:17
  • 2
    Good! If one of those target values actually included a single quote ... 3 o'clock for example ... you would need to double up that quote like this In ('abc', '3 o''clock') But more generally, always verify that the text of the SQL statement your code builds matches what you expect --- and that's where Debug.Print and the Immediate window can be useful. Commented Jan 11, 2016 at 19:27

2 Answers 2

3

In Excel VBA the string identifier is the " (double quote) character. You do not need to double the single quote characters for them to pass through to the database when enclosed by double quotes.

Try this:

strSql = "SELECT * FROM Pricing WHERE Account In ('1234', 'ABCD')"
Sign up to request clarification or add additional context in comments.

1 Comment

This works, if it also includes the semi-colon at the end.
-1

Please try it with this:

strSql = "SELECT * FROM Pricing WHERE Account In ('1234', 'ABCD')" 

3 Comments

Please do not post code-only answers. They are useless for future visitors.
Code only answers are unlikely to help future visitors. Please consider expanding your answer to include an explaination as to what you changed and why this code of yours works.
Thanks for this hint. I will do this in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.