Search code examples
ms-accessvbams-access-2016

Selecting fields command gives error


I want to sort multiple fields in an access data base but being a newbie I took reference from MSDN program and first trying to sort on a single field. I'm getting error From syntax wrong on the following lines.

Set rst = dbs.OpenRecordset("SELECT ACT_CD, " _
& "SNO FROM Banks_Trnx_2018-2019" _
& "ORDER BY SNO DESC;")

The full program as follows.

 Option Compare Database

Sub OrderByX()

    Dim dbs As Database, rst As Recordset

    ' Modify this line to include the path to Northwind
    ' on your computer.
    Set dbs = OpenDatabase("E:\FY_2018-2019\Banks\Banks_Trnx_2018-2019.accdb")

    ' Select the last name and first name values from
    ' the Employees table, and sort them in descending
    ' order.
   Set rst = dbs.OpenRecordset("SELECT ACT_CD, " _
        & "SNO FROM Banks_Trnx_2018-2019" _
        & "ORDER BY SNO DESC;")
    ' Populate the Recordset.
    rst.MoveLast

    ' Call EnumFields to print recordset contents.
   ' EnumFields rst, 12

    dbs.Close

End Sub

I am clueless. Please help. As already mentioned I would like to sort on three fields (multiple fields) comprising of text and numerical fields which presently I can easily do by setting columns in proper order and selecting them together while sorting. Since it is a repetitive operation I am trying to develop VBA procedure for the same. Any pointer in the right direction shall be highly appreciated.


Solution

  • You should set your sql to a variable first - makes it a lot easier to troubleshoot - you'd be able to see you've left out some spaces between keywords and table

       Set rst = dbs.OpenRecordset("SELECT ACT_CD, " _
            & "SNO FROM [Banks_Trnx_2018-2019]" _
            & "ORDER BY SNO DESC;")
    

    Should be (with added brackets for table as suggested by @skkakkar)

       Set rst = dbs.OpenRecordset("SELECT ACT_CD, " _
            & "SNO FROM [Banks_Trnx_2018-2019] " _
            & "ORDER BY SNO DESC;")