无法访问DAO Recordset中的记录

时间:2017-01-09 12:19:33

标签: vba access recordset

我正在Access中创建一个数据库,并使用VBA实现一个功能,根据其他模板中的值,将多个INSERT查询运行到多个表中。表。

在流程的某个时刻,我正在检索SELECT查询的结果,并将查询结果用作INSERT中的参数。

我使用Access查询构建器构建并测试了查询,因此我知道查询按预期运行。

我正在使用DAO库与数据库连接并运行我的查询。

我有下面的函数,它将后一个函数返回的记录集转换为集合集合。 在下面的函数中遇到了一个问题,我返回的记录集显然包含零记录。这导致它抛出“无当前记录”。该行' records.MoveLast'中的例外情况。 我应该看到的,我从查询中得知,是一个包含2条记录的Recordset,每条记录有5个字段。

Private Function RecordsetToCollection(records As RecordSet) As Collection

Dim recordCollection As New Collection
Dim i As Integer

'Go to first record?
'Exception thrown here
records.MoveLast
records.MoveFirst

'Check if current record position before first record
If Not records.BOF Then

    'While not after last record
    While Not records.EOF

        'Collection to hold field values
        Dim fieldCollection As New Collection

        'Loop through fields
        For i = 0 To records.Fields.Count - 1

            'Add to collection
            fieldCollection.Add records.Fields(i).Value

        Next i

        'Add field collection to record collection
        recordCollection.Add fieldCollection

        Set fieldCollection = Nothing

        'Go to next record
        records.MoveNext

    Wend

End If

'Return collection
Set RecordsetToCollection = recordCollection

End Function

使用以下函数检索输入此函数的记录集:

Private Function GetTemplateDeliverables(TemplateProjectActivityID As Integer) As Collection
'Get Template Deliverables recordset from tbl_TemplateDeliverables using given ProjectActivityID

'Open query
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("qry_GetTemplateDeliverables")

'Add parameters
qdf.Parameters("Project Activity ID") = ProjectActivityID

'Get return recordset
Dim rst As RecordSet
Set rst = qdf.OpenRecordset()

Dim recordCollection As New Collection
Set recordCollection = RecordsetToCollection(rst)

'Get ProjectActivityID from recordset
Set GetTemplateDeliverables = recordCollection

'Clean up
qdf.Close
Set qdf = Nothing
Set rst = Nothing

End Function

有没有人建议为什么会这样?

我无法理解为什么这不起作用,因为我已经有功能来检索工作正常的记录集,唯一的区别是在那些函数中每个记录只有1个字段,而这有5个领域,但我不能想到为什么这会是一个问题。

非常感谢任何帮助!

(P.S。关于如何改进我的代码的任何提示也会有所帮助。)

0 个答案:

没有答案