如何从函数返回记录集

时间:2010-03-17 14:51:50

标签: excel-vba ado recordset vba excel

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

我做错了什么?

3 个答案:

答案 0 :(得分:6)

问题在于设置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

答案 1 :(得分:1)

Set Execute = recordset

创建一个指向记录集的指针,在退出函数时关闭该指针 这就是为什么它不能包含任何东西。

我也对您的变量名称感兴趣,这些变量名称与可能的保留字(记录集)相同。我通常使用rs或rsIn或rsWhateverYouWant ...

答案 2 :(得分:0)

如Patrick所述,记录集是一个指针。 呼叫者'Scott_Test'应该调用recordset.Close而不是。

Execute方法无法调用recordset.Close,但我相信可以保留记录集.ActiveConnection = Nothing