SQL Excel VBA运行时错误3709无效的连接

用户7322614

这是我的第一个问题,欢迎建设性的批评!我正在尝试从excel vba查询访问数据库,并将返回信息放入Excel范围。我收到此错误:

错误消息:“运行时错误'3709'该连接不能用于执行此操作。在此情况下该连接已关闭或无效。”

码:

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

我启用了以下参考:

  1. Visual Basic for Applications,
  2. Microsoft Excel 16.0对象库,
  3. OLE自动化,
  4. Microsoft Office 16.0对象库,
  5. Microsoft Access 16.0对象库,
  6. Microsoft ActiveX数据对象2.0库,

我尝试放置以下行:

cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"

在错误行之前并收到此错误:

运行时错误“ 3705”:打开对象时不允许进行操作。

有人知道我的问题是什么吗?

共产国际

首先(与错误无关),除非需要支持使用Windows 2000或更早版本的客户端,否则应引用最高的Microsoft ActiveX Data Objects版本而不是2.0。如果仅使用ADODB与数据库进行交互,则根本不需要Microsoft Access 16.0对象库。

其次,如果您已经有了reference,请不要创建像这样的后期绑定对象:

Set cn = CreateObject("ADODB.connection")

尽早添加引用将绑定类型,因此显式声明它们并使用实例化它们New

Dim cn As ADODB.Connection
Set cn = New ADODB.Connection

您的连接字符串应该很好-您遇到问题的是以下两行:

    Set rs1 = CreateObject("ADODB.recordset")

    rs1.activeconnection = cn

执行ADODB.Command将返回Recordset,而不是相反。完全删除这两行。Recordset您无需在建立连接时将连接附加到,而需要在构建时使用它ADODB.Command

    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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章