首页 > 解决方案 > 尝试使用 VBA 查询访问数据库时出现自动化错误

问题描述

我在代码中做了以下 ADODB 对象声明。

Dim OConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim fld As ADODB.Field
Set OConn = New ADODB.Connection
Set rs = New ADODB.Recordset

我想使用以下代码从 MS Access 数据库文件中的表中读取并生成记录集 rs。

'Get the table name from the search results.
tableName = ThisWorkbook.Sheets("PLC Module Data").Cells(2, 9).Value

'Set the SQL string.
strSql = "SELECT Code, Points, Type, Description, Rating " & _
"FROM " & tableName

'Set the connection string and open the connection to the Access DB.
OConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=Q:\AutoCAD Improvements\PLC IO Utility Docs\PLC IO Spreadsheet     
App\PLC IO App\ace_plc.mdb"

OConn.Open

'Open the recordset and error out if nothing is returned
Set rs = OConn.Execute(strSql)
If rs.EOF Then
    MsgBox "No matching records found."
    rs.Close
    OConn.Close
    Exit Sub
End If

我已经检查了 Access 文件本身中的查询语句,它工作正常。我总是得到错误

运行时错误'-2147217900 (80040e14)':自动化错误

在线上,

Set rs = OConn.Execute(strSql)

如果有人可以查看我的代码并确定为什么会发生这种情况,将不胜感激。我在网上看过类似的例子,看起来这应该是正确的。

标签: sqlexcelvbams-accessadodb

解决方案


我在 tableName 字符串周围添加了括号,它现在可以工作了。感谢所有的反馈。

'Set the SQL string.
strSql = "SELECT Code, Points, Type, Description, Rating " & _
"FROM [" & tableName & "]"

推荐阅读