Possible Duplicate:
running sql statement from excel vba
Here’s the excerpt that’s causing the issue:
Dim myquery As String
Set cn = New ADODB.Connection
cn.Open ' Some connection that opens properly
myquery = "select * from batchinfo where datapath='" + dpath + "' and analystname='" + aname + "' and reportname='" + rname + "' and batchstate='" + bstate + "'"
' dpath, aname, rname, and bstate are declared earlier in the sub
rs.Open myquery, cn, adOpenKeyset, adLockOptimistic, adCmdTable
Here’s a sample of the myquery string at runtime :
"select * from batchinfo where datapath='111119-0021_excel short summary_111122191339.xlsx'
and analystname='none' and reportname='none' and batchstate='none'"
However, on this line, the code breaks, giving an error “Incorrect syntax near the keyword ‘select'”
Any ideas anyone?
You are opening the recordset with the option
adCmdTablewhich means that it will expect a table name not an SQL query.Use the option
adCmdTextinstead.Also, don’t use
select *, specify the fields that you want returned from the query. That makes the code more robust.