首页 > 解决方案 > Excel VBA SQL 错误,连接失败

问题描述

当我尝试在 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

标签: vbaexcelms-jet-ace

解决方案


你能试着改变下面

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

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

如果不建议报告名称等于什么。

或者尝试以下方法:

    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

推荐阅读