SQLTeam.com | Weblogs | Forums

SQL Select query in VBA


#1

Hi, I have a question about VBA syntax when running a SELECT query
from a table in SQL Server. I am running the query in VBA using the
script below.

    .Source = "SELECT " & _
                "Field1 , " & _
                "Field2, " & _
                "Field3, " & _
               "FROM table " & _
                "WHERE Condition1 = " & condition AND "Condition2 = " & condition & _
                "ORDER BY Field4;"

The above script with two conditions is giving me a "Run-time error '13' Type Mismatch" error.

However, the script below with just one condition works fine.

    .Source = "SELECT " & _
                "Field1 , " & _
                "Field2, " & _
                "Field3, " & _
               "FROM table " & _
                "WHERE Condition1 = " & condition & _
                "ORDER BY Field4;"

Question is what is the correct syntax for the first script above in order to run with multiple conditions?

Thanks in advance.


#2

You have one of your double-quotes in the wrong place. Change it to

"WHERE Condition1 = " & condition " AND Condition2 = " & condition & _

Also, if the condition that follows the "Condition2 = " & is a literal string, you will need to add single quotes around condition.

Another thing I noticed is that you have a comma after Field3 in the select list. That should have generated a syntax error. I am assuming that that is an error that happened when you copied over for posting.