Sql – Run SQL Statement in Access using VBA code

ms-accesssqlvba

I can't figure out what is wrong in this,
I'm collecting search criteria from a Form to use it in search.

The SQL line stored like this : (strWhere is the collected info from the Form)

SQLst = "SELECT Deposits.Fines, Deposits.[Deposit Value], Deposits.[Deposit Date], Deposits.Depositor, Info.Tower, Deposits.[Account Number] FROM Info, Deposits Where " & strWhere & ";"

The final SQL statement looks like this:

SELECT Deposits.Fines, Deposits.[Deposit Value], Deposits.[Deposit Date], Deposits.Depositor, Info.Tower, Deposits.[Account Number] FROM Info, Deposits Where ([Account Number] = "1234");

Now After I run the Line using this command (SQLst is the SQL Line up)

DoCmd.OpenQuery SQLst

I get this message:

enter image description here

Best Answer

Not DoCmd.OpenQuery SQLst, that is for saved queries, not SQL strings. You need:

' Best to use a separate instance, so you can get record counts etc.
Set db = CurrentDB

For action queries:

db.Execute SQLst, dbFailOnerror

For SELECT queries, you can either use a recordset or update or create a query.

Set rs = db.Openrecordset(SQLst)

' This query does not exist
Set qdf = db.CreateQueryDef("MyQuery", SQLst)

I doubt that the account number is text, so:

 ([Account Number] = 1234);

Quotes are used for text-type fields / columns, numbers are as is and dates are delimited with hash (#).