2011-07-25 107 views
0

從Excel電子表格中的VBA代碼連接到Oracle DB時遇到錯誤。我運行的查詢工作正常,但是當我嘗試關閉連接時,出現以下錯誤:在將VBA連接到Oracle時關閉連接時出錯

運行時錯誤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 
+0

嘗試在cn.Close行下面添加Exit Sub。並刪除「停止」:那裏不需要。 –

回答

1

沒有什麼要持續到cn.Close線後您的錯誤處理程序停止執行的,所以有可能你的錯誤是由錯誤處理程序本身來(因爲處理程序試圖引用不存在的錯誤目的)。

...  
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 
+0

確切地說;即使在沒有錯誤發生時,Kev的代碼仍在運行errHandler,因爲它缺少'Exit Sub'。 @Kev's,問題在於cn.Close之後運行的cn.Errors的引用(不確定這對你是否清楚,我只是對Tim的答案進行重新說明)。 –

+0

剛纔意識到我沒有回答這個問題。這是正確的。 – Kev