Search code examples
sqlsortingms-access

Recordset.Sort method not sorting


First time I've used .Sort but from Googling the following should work, but the debug print output is not sorted.

Function SortByYear(ByVal z As DAO.Recordset) As String
 Dim mySortedRS As DAO.Recordset
 z.Sort = "Year"
 Set mySortedRS = z
    Do
        Debug.Print mySortedRS!Year
        mySortedRS.MoveNext
    Loop Until mySortedRS.EOF
Set mySortedRS = Nothing
End Function

Solution

  • When you

    Set mySortedRS = z
    

    you are not creating a new Recordset object, you are simply creating a new variable that points to the existing Recordset object. To create a new (sorted) Recordset you need to use

    Set mySortedRS = z.OpenRecordset
    

    For more information, see

    Recordset.Sort Property (DAO)