gpt4 book ai didi

excel - 如何从函数返回记录集

转载 作者:行者123 更新时间:2023-12-02 07:33:00 24 4
gpt4 key购买 nike

我正在 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

这是一个公共(public)函数,我在电子表格的单元格 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

我做错了什么?

最佳答案

问题在于设置 ActiveConnection = Nothing。以下代码有效:

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

关于excel - 如何从函数返回记录集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2463212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com