Returning a recordset from a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jgoodnight
    New Member
    • Jun 2008
    • 12

    Returning a recordset from a function

    I have a function "ReturnDocument Rules" that returns a recordset. Everything works if I do not close the recordset and set it to nothing, but I know this is bad programming practice. If I do close the recordset and set it to nothing, obviously after I have set the function to the recordset, return value is still set to nothing.

    My code:

    Code:
    Public Function ReturnDocumentRules() As Recordset
        'Open DB and retrieve rules from Rules table that apply to selected document
        Dim db As Database, rs As Recordset
        Set db = OpenDatabase("H:\9000\9000.mdb")
        Set rs = db.OpenRecordset("SELECT rule FROM Rules WHERE docID=" & frm_mainMenu.cb_DocType.Value _
            & " ORDER BY docID", dbOpenSnapshot)
     
        Set ReturnDocumentRules = rs
     
        rs.Close
        db.Close
        Set rs = Nothing
        Set db = Nothing
     
    End Function
    How can I return this recordset and still properly close it in the function?
  • danp129
    Recognized Expert Contributor
    • Jul 2006
    • 323

    #2
    You should be able to return a disconnected recordset:
    4GuysFromRolla. com - Using Disconnected Recordsets

    Comment

    • mrmelvin
      New Member
      • Aug 2008
      • 4

      #3
      An additional option would be to declare class level variables in the general declaration of the class. Then use the those varables in your returndocumentr ules function. Then close the db and recordset after your done calling the function in you main calling code. For example:
      public class abc()
      Dim db As Database, rs As Recordset
      function ReturnDocumentR ules()
      db = x
      rs = y
      end function
      private sub button_click()
      returndocumentr ules()
      rs.close
      db.close
      end sub
      end class

      Comment

      • jgoodnight
        New Member
        • Jun 2008
        • 12

        #4
        Thanks Dan,

        The disconnected recordsets worked perfectly. In addition to that link, I read this and this to get it implemented.

        Comment

        • odedruts
          New Member
          • Jan 2010
          • 1

          #5
          can u post the code

          i m also stuck in this problem

          i cant close the record set
          thanks

          Comment

          Working...