Sql 使用VBA时,关键字“Select”附近的语法不正确

Sql 使用VBA时,关键字“Select”附近的语法不正确,sql,vba,Sql,Vba,可能重复: 以下是引起问题的摘录: 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='" +

可能重复:

以下是引起问题的摘录:

   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
以下是运行时myquery字符串的示例:

"select * from batchinfo where datapath='111119-0021_excel short summary_111122191339.xlsx' 
   and analystname='none' and reportname='none' and batchstate='none'"
但是,在这一行,代码中断,在关键字“select”附近给出了错误的语法


有人知道吗?

您正在打开带有选项adCmdTable的记录集,这意味着它需要的是表名而不是SQL查询

改用adCmdText选项


另外,不要使用select*,指定要从查询返回的字段。这使得代码更加健壮。

现在就可以运行了。谢谢我还将测试缩小字段的健壮性!考虑使用级联运算符而不是+。