连接VBA到Oracle时出现连接关闭错误



我在Excel电子表格中从VBA代码连接到Oracle DB时遇到错误。我运行的查询工作正常,但是当我试图关闭连接时,我得到以下错误:

运行时错误3265:在与请求的名称或序数对应的集合中找不到项。

下面是我的代码副本。错误发生在"cn.close"行。任何帮助将非常感激!

Sub GetData()
Dim cn As New ADODB.Connection 
comm As New ADODB.Command
rs As New ADODB.Recordset
On Error GoTo errhandler:
    cn.ConnectionString = "DSN=XXX;Uid=XXX;Password=XXX;"    
    cn.Open
    comm.CommandType = adCmdText
    comm.CommandText = "Select * from XXX where rownum < 10;"
    Set comm.ActiveConnection = cn
    rs.ActiveConnection = cn
    rs.Open comm
    Sheets("Sheet1").Range("a1").Offset(1, 0).CopyFromRecordset rs  'copy the records
    rs.Close
    cn.Close
errhandler:
    Debug.Print (Err.Description)
    Debug.Print "Error# " & cn.Errors(0).NativeError & ": " & cn.Errors(0).Description
Stop
End Sub

在cn之后没有什么可以阻止执行继续进入错误处理程序。关闭行,因此您的错误可能来自错误处理程序本身(因为处理程序试图引用一个不存在的Err对象)。

...     
rs.Close
cn.Close
Exit Sub   ' don't run into your error handler
errhandler:
  Debug.Print (Err.Description)
  Debug.Print "Error# " & cn.Errors(0).NativeError & _
              ": " & cn.Errors(0).Description 
  'Stop  'delete this - not needed here
End Sub 

最新更新