这是我的第一个问题,欢迎提出建设性批评!我正在尝试从 Excel VBA 查询 Access 数据库并将返回信息放入 Excel 范围中。我收到此错误:
Error Message: "Run-time error '3709' The connection cannot be used to perform this operation. It is either closed or invalid in this context."
代码:
Sub Importfromaccess()
Path = "C:\Users\myUser\Desktop\Database1.accdb"
Set cn = CreateObject("ADODB.connection")
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"
Set rs1 = CreateObject("ADODB.recordset")
rs1.activeconnection = cn
Dim strSQL As New ADODB.Command
strSQL.CommandText = "SELECT * FROM Tooling WHERE TID=BD0001"
strSQL.CommandType = adCmdText
Set rs1 = strSQL.Execute ' This is the line the error occurs on
Sheets("Calc").Range("K1").CopyFromRecordset rs1
End Sub
我已启用以下引用:
- Visual Basic 应用程序,
- Microsoft Excel 16.0 对象库,
- OLE 自动化,
- Microsoft Office 16.0 对象库,
- Microsoft Access 16.0 对象库,
- Microsoft ActiveX 数据对象 2.0 库,
我尝试放置该行:
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"
就在错误行之前并收到此错误:
Run-time error '3705': Operation is not allowed when the object is open.
有人知道我的问题是什么吗?
最佳答案
首先(与您的错误无关),除非您需要支持使用 Windows 2000 或更早版本的客户端,否则您应该引用最高的 Microsoft ActiveX 数据对象版本而不是 2.0。如果您仅使用 ADODB 与数据库交互,则根本不需要 Microsoft Access 16.0 对象库。
其次,如果您已有引用,请不要创建如下所示的后期绑定(bind)对象:
Set cn = CreateObject("ADODB.connection")
尽早添加引用会绑定(bind)类型,因此显式声明它们并使用 New
实例化它们:
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
您的连接字符串应该没问题 - 您遇到问题的地方是这两行:
Set rs1 = CreateObject("ADODB.recordset") rs1.activeconnection = cn
执行ADODB.Command
将返回Recordset
,而不是相反。完全删除这两行。您需要在构建 ADODB.Command
时使用它,而不是将连接附加到 Recordset
:
Dim strSQL As New ADODB.Command
strSQL.ActiveConnection = cn '<---Insert this.
strSQL.CommandText = "SELECT * FROM Table1"
strSQL.CommandType = adCmdText
另外,去掉那里的匈牙利符号 - 它太令人困惑了。 ADODB 命令不是 String
,那么为什么要将其命名为 strFoo
?
您还需要自行清理 - 使用完记录集和连接后,不要让它们保持打开状态。完成后调用 .Close
。
最后,您的 SQL 语句很可能不正确 - 您可能需要将 TID
用单引号括起来 ('
):
"SELECT * FROM Tooling WHERE TID='BD0001'"
它应该看起来更接近这个:
Sub Importfromaccess()
Dim Path As String
Path = "C:\Users\myUser\Desktop\Database1.accdb"
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"
Dim query As New ADODB.Command
query.ActiveConnection = cn
query.CommandText = "SELECT * FROM Tooling WHERE TID='BD0001'"
query.CommandType = adCmdText
Dim rs1 As ADODB.Recordset
Set rs1 = query.Execute ' This is the line the error occurs on
Sheets("Calc").Range("K1").CopyFromRecordset rs1
'CLEAN UP AFTER YOURSELF:
rs1.Close
cn.Close
End Sub
关于vba - SQL Excel VBA 运行时错误 3709 无效连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41304529/