关键字附近的语法错误'选择'使用VBA

时间:2011-12-04 05:19:25

标签: sql vba

  

可能重复:
  running sql statement from excel 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='" + 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'"

然而,在这一行,代码中断,给出错误“关键字'选择'附近的语法不正确”

任何想法?

1 个答案:

答案 0 :(得分:2)

您正在使用选项adCmdTable打开记录集,这意味着它将期望表名不是SQL查询。

使用选项adCmdText代替。


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