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