Excel VBA SQL错误,连接失败

时间:2018-05-15 01:02:32

标签: excel vba excel-vba ms-jet-ace

当我尝试在Excel电子表格中运行内部SQL查询时出现以下错误。

  

错误2147467259 - '执行'的方法对象' _Connection'失败。

此外,当我使用断点运行代码时,我可能会遇到自动化错误。我在Excel 2013(15.0.5023.1000)中查询。

With conn_obj
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=" & report_name & ";" & _
    "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    .Open
End With

On Error GoTo err_SQL
SQL = query

Set rs = conn_obj.Execute(SQL)  'error here

更新:我用上面的代码替换了上面的代码,我在

上收到错误
  

初始化字符串的格式不符合OLE DB规范。

Dim sSQLString As String
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String

Let DBPath = report_name 'Path here
Let sconnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBPath & ";Extended Properties='text;HDR=YES;';"

Conn.Open sconnect
sSQLString = query ' query here
mrs.Open sSQLString, Conn

1 个答案:

答案 0 :(得分:0)

你能尝试改变下面的

吗?
 "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"

  "Extended Properties='Excel 12.0 Xml;HDR=YES';"

如果不建议report_name等于。

或者尝试下面的内容:

    Dim sSQLString As String
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
Let DBPath = "" 'Path here
Let sconnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBPath & ";Extended Properties='text;HDR=YES;';"
Conn.Open sconnect
sSQLString = "" ' query here
mrs.Open sSQLString, Conn