【问题标题】:Access Vba - How to set the current record of a recordset to an other recordsetAccess Vba - 如何将记录集的当前记录设置为另一个记录集
【发布时间】:2018-11-16 23:08:39
【问题描述】:

我获取一个记录集

Do while not recset.eof 
Recset.movenext
Loop

并且想用vba将记录集的当前记录设置为另一个记录集

Set rec2 = rec1.????

我试过了

Set.Rec2 = recset.bookmark

但是没有成功! 我希望有一种方法可以轻松地将当前记录设置为其他记录集

感谢您的帮助

【问题讨论】:

    标签: ms-access vba recordset


    【解决方案1】:

    有很多选择,但如果不知道您的确切目标,就很难知道哪一个最适合您。

    一个选项是打开一个记录克隆:

    Set rec2 = rec1.RecordsetClone 'Open a clone
    rec2.Bookmark = rec1.Bookmark 'Move the clone to the same record
    

    在这种情况下,rec2 包含 所有 数据 rec1 具有,但设置为相同的记录。

    另一种选择是使用过滤器:

    rec1.Filter = "ID = " & rec1!ID 'Set a filter to the current record, assumes ID = primary key
    Set rec2 = rec1.OpenRecordset 'Set rec2 to the filtered result, rec1 is still unfiltered
    

    【讨论】:

    • 我需要将当前记录导出到excel文件中,希望不用过滤器也能做到这一点
    • 不,如果没有过滤器,则无法创建仅包含当前选定记录的记录集(除非您愿意创建第二个未绑定的 adodb 记录集)
    • 所以只有一个问题,使用 recordset.fields(i) 获取记录字段。感谢您的帮助。
    【解决方案2】:

    我的目标是将记录集的当前记录导出到 Excel 文件。正如 Eric 所写,不可能将当前记录设置为另一个记录集。

    但是 copyFromRecordset 具有非常有趣的属性可以解决我的问题,如下所示 CopyFromRecordset RecordSet , MaxRows , MaxColumns Full description here

    所以我测试了这段代码,效果很好

        Dim oRecSet As Recordset, oRecSetClone As Recordset
        Dim varBookmark As Variant
    
        Set objExcelApp = New Excel.Application
        objExcelApp.Visible = True
        Set wb = objExcelApp.Workbooks.Open("G:\Access\test.xlsx")
        Set ws = wb.Sheets(1)
    
    
        sSQL = "SELECT * FROM tbl"
        Set oRecSet = CurrentDb.OpenRecordset(sSQL)
        Set oRecSetClone = oRecSet.Clone
    
        Do While Not oRecSet.EOF
            Debug.Print i
            oRecSetClone.Bookmark = oRecSet.Bookmark
            ws.Range("A" & i).CopyFromRecordset oRecSetClone, 1
            oRecSet.MoveNext
        Loop
    
    End Sub
    

    只有一条评论

    我使用书签是因为我在应用 copyFromRecordSet rec,1 时发现了一个奇怪的行为。 执行此命令后,rec.movenext 会生成错误消息:Nbr 3021 - No current record

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2015-02-09
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多