Is there a way to write to/edit a otherwise read-only Recordset for the context of the form and work with the data?

前端 未结 1 652
温柔的废话
温柔的废话 2020-12-21 21:11

In my database there is a form that displays records filtered by an abbreviation you can choose from in a combo box. Now in some cases I will want to open another form with

1条回答
  •  醉梦人生
    2020-12-21 21:21

    You mix Values and References (stored in Variables) which causes you to accidently close your Forms-Recordset.

    Set cpRS = New ADODB.Recordsetcreates a Recordset-Object Instance and stores the Reference of the Instance in the variablecpRS.

    Set Me.RecordSet = cpRScopies the Reference fromcpRSto the Forms-RecordSet, which makes both point to the same Instance of the Recordset-Object. It doesn't create a copy of the Object (likeByRefin Function-Arguments in opposite toByVal)!

    NowcpRS.Closecloses the Recordset but this is the same as the Forms-Recordset, what leads to an empty form, because the Forms-Recordset is closed!

    Just skipcpRS.close(you can destroy the variable withcpRS = Nothingbecause that just destroys the Reference to the Instance stored incpRS, but the Instance is only destroyed if there is no Reference left that points to it, butMe.Recordsetstill contains the Reference!) to get your Form populated (if rest of code is correct which I haven't tested!).

    Example:

    Private Sub CloseCopyOfRecordsetReference()
    
    Dim rs1 As DAO.Recordset, rs2 As DAO.Recordset, rs3 As DAO.Recordset
    
    With CurrentDb
        Set rs1 = .OpenRecordset("SELECT * FROM MSysObjects")
        Set rs2 = rs1 'copy Reference
        Set rs3 = rs1 '2. copy Reference
    
        Set rs1 = Nothing 'this does not affect rs2,rs3
        Debug.Print "rs3.RecordCount: " & rs3.RecordCount
    
        rs2.Close ' this closes rs3 too!
        Debug.Print "rs3.RecordCount: " & rs3.RecordCount 'Error 3420 here as Recordset is closed
    End With
    
    End Sub
    

    0 讨论(0)
提交回复
热议问题