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
You mix Values and References (stored in Variables) which causes you to accidently close your Forms-Recordset.
Set cpRS = New ADODB.Recordset
creates a Recordset-Object Instance and stores the Reference of the Instance in the variablecpRS
.
Set Me.RecordSet = cpRS
copies the Reference fromcpRS
to the Forms-RecordSet, which makes both point to the same Instance of the Recordset-Object. It doesn't create a copy of the Object (likeByRef
in Function-Arguments in opposite toByVal
)!
NowcpRS.Close
closes 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 = Nothing
because 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.Recordset
still 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