Dynamic Sort Query BUT with ASC/DESC

Amedean 21 Reputation points
2021-12-11T17:12:01.197+00:00

Original post I made but technically a different question.
https://learn.microsoft.com/en-us/answers/questions/652130/access-database-dynamic-sort-query.html

With the below code in an SQL query I can use a tempvar to identify the proper ORDER BY criteria. But my new problem is, what if I want to sort by DESC? I have been unable to get this to work dynamically below:

ORDER BY IIf([TempVars]![tpvFavoriteList1]="TitleAsc", [qryArchive].[ObjectName] & ASC, [qryArchive].[ObjectName] & DESC);  

It treats the ASC and DESC as parameters that I have to type with a prompt and it doesnt matter anyways because it treats it as a string value. How can I dynamically add the ASC and DESC?

Microsoft 365 and Office | Access | Development
0 comments No comments
{count} votes

Accepted answer
  1. Ken Sheridan 2,851 Reputation points
    2021-12-15T02:10:12.343+00:00

    An alternative solution would be to assign an SQL statement to the control's RowSource property in code in the form's module, e.g. in its Open event procedure, e.g.

    Me.lstContacts.RowSource = _
       "SELECT ContactID, FirstName & "" "" & LastName " & _
       "FROM Contacts " & _
       "ORDER BY LastName  " & IIF([TempVars]![NameOfVariable]="TitleAsc"
    

    , "ASC", "DESC")

    Set the list box's ColumnWidths property to 0 to hide the fist column.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Gustav 717 Reputation points MVP
    2021-12-14T12:28:34.407+00:00

    You can't. Just like field names and table names, this must be literal.

    1 person found this answer helpful.
    0 comments No comments

  2. Amedean 21 Reputation points
    2021-12-14T14:07:26.533+00:00

    I was forced to create two queries to address this issue. One is for ASC and the other for DESC sorting. Other than that, I can use the IFF() to sort by any other fields dynamically. Used VBA to switch between queries in a listbox. It accomplishes what I was looking for but the code is very cumbersome.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.