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

时间:2016-12-23 16:06:07

标签: excel vba excel-vba

这是我的第一个问题,欢迎提出建设性的批评!我试图从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 Data Objects 2.0 Library,
  7. 我试过放线:

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

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

      

    运行时错误'3705':对象为时不允许操作   开。

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

3 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:1)

您已import Foundation import Firebase import FirebaseAuth import FirebaseStorage class Datasevice{ static let datasevice=Datasevice() private var _BASE_REF = FIRDatabase.database().reference() var BASE_REF:FIRDatabaseReference{ return _BASE_REF } var storageRef: FIRStorageReference { return FIRStorage.storage().reference() } var fileUrl:String! func SignUp(username:String,email:String,password:String,data:NSData){ FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user,Error)in if let Error=Error{ print(Error.localizedDescription) return } let changeRequest = user!.profileChangeRequest() changeRequest.displayName = username // userName is Gandalf changeRequest.commitChanges(){ (error) in if let error = error { print(error.localizedDescription) return } } let filePath = "profileImage/\(user!.uid)" let metadata = FIRStorageMetadata() metadata.contentType="image/jpeg" self.storageRef.child(filePath).put(data as Data, metadata: metadata,completion :{(metadata,Error) in if let Error=Error{ print(Error.localizedDescription) return } self.fileUrl = metadata?.downloadURLs![0].absoluteString let changeRequestPhoto = user!.profileChangeRequest() changeRequestPhoto.photoURL = NSURL(string: self.fileUrl) as URL? changeRequestPhoto.commitChanges(completion: { (error) in if let error = error { print(error.localizedDescription) return } else { print("profile update") } }) let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.login() }) }) } }

如何尝试更像:

Set rs1

答案 2 :(得分:0)

经过一番彻底的重新安排后,我想我已经弄明白了。我对修复问题的更改感到惊讶,但以下代码有效:

Dim con As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As New ADODB.Command

cmd.CommandText = "SELECT * FROM Tooling WHERE TID='BD0001'"
con.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\myUser\Desktop\Database1.accdb;"

cmd.ActiveConnection = con

Set rs = cmd.Execute

Sheets("Calc").Range("K1").CopyFromRecordset rs

rs.Close
con.Close

最终错误修正了:

cmd.CommandText = "SELECT * FROM Tooling WHERE TID='BD0001'"

此行以前不包括BD0001周围的单引号。

我还在Command对象中添加了一个ActiveConnection。

编辑:这是最简单的工作版本,我可以为所有乐于助人的人提供礼貌!