2010-03-17 122 views
3

我在Excel VBA中構建數據訪問層,並且無法返回記錄集。我的類中的Execute()函數肯定是從數據庫中檢索一行,但似乎沒有返回任何東西。如何從函數返回記錄集

以下函數包含在名爲DataAccessLayer的類中。該類包含用於打開和關閉連接的函數Connect和Disconnect。


Public Function Execute(ByVal sqlQuery As String) As ADODB.recordset 
    Dim rs As ADODB.recordset 
    Set rs = New ADODB.recordset 
    Dim recordsAffected As Long 

    ' Make sure we're connected to the database. 
    If Connect Then 
     Set command = New ADODB.command 

     With command 
      .ActiveConnection = connection 
      .CommandText = sqlQuery 
      .CommandType = adCmdText 
     End With 

     'Set rs = command.Execute(recordsAffected) 
     'Set Execute = command.Execute(recordsAffected) 
     rs.Open command.Execute(recordsAffected) 
     rs.ActiveConnection = Nothing 
     Set Execute = rs 
     Set command = Nothing 
     Call Disconnect 
    End If 
End Function 

這是我在電子表格A1單元格中用於測試的公共函數。


Public Function Scott_Test() 
    Dim Database As New DataAccessLayer 
    'Dim rs As ADODB.recordset 
    'Set rs = CreateObject("ADODB.Recordset") 
    Set rs = New ADODB.recordset 

    Set rs = Database.Execute("SELECT item_desc_1 FROM imitmidx_sql WHERE item_no = '11001'") 
    'rs.Open Database.Execute("SELECT item_desc_1 FROM imitmidx_sql WHERE item_no = '11001'") 
    'rs.Open 

    ' This never displays. 
    MsgBox rs.EOF 

    If Not rs.EOF Then 
     ' This is displaying #VALUE! in cell A1. 
     Scott_Test = rs!item_desc_1 
     rs.Close 
    End If 

    rs.ActiveConnection = Nothing 
    Set rs = Nothing 
End Function 

我在做什麼錯?

回答

6

的問題是與設置的ActiveConnection =什麼。下面的代碼工作:

Public Function Execute(ByVal sqlQuery As String) As ADODB.recordset 
    Dim rs As ADODB.recordset 
    Set rs = New ADODB.recordset 
    Dim recordsAffected As Long 

    ' Make sure we are connected to the database. 
    If Connect Then 
     Set command = New ADODB.command 

     With command 
      .ActiveConnection = connection 
      .CommandText = sqlQuery 
      .CommandType = adCmdText 
     End With 

     rs.Open command.Execute(recordsAffected) 

     Set Execute = rs 
     Set command = Nothing 
     Call Disconnect 
    End If 
End Function
1
Set Execute = recordset 

創建一個指向記錄集的指針,在退出函數時關閉它。
這就是爲什麼它不能包含任何東西。

我也對您的變量名稱進行了重新定義,它們與possibe保留字(記錄集)相同。我通常使用rs或rsIn或rsWhateverYouWant ...

+0

我搬到了靠近調用函數,但它仍然無法正常工作。我還更改了變量名稱,讓您感覺更舒適。以上代碼示例已更新。 – Scott 2010-03-17 16:18:22

0

正如Patrick所說,記錄集是一個指針。 調用者'Scott_Test'應調用recordset.Close。

Execute方法不能打電話recordset.Close,但是我相信這是確定離開recordset.ActiveConnection =無

+0

我將近的移動到調用函數,但它仍然無法正常工作。以上代碼示例已更新。 – Scott 2010-03-17 16:17:51