How to sort (ORDER BY) a query

anb001

Registered User.
Local time
Today, 18:13
Joined
Jul 5, 2004
Messages
197
I have a query, which look like this:

Code:
SELECT tblSJAHeader.Department, tblSJAHeader.SJANumber, tblSJAHeader.SJATitle FROM tblSJAHeader
ORDER BY tblSJAHeader.xxxxxxxxxxx;

The ORDER BY part should be according to a selection in a combo box, meaning if "Department" is selected, then query should be "ORDER BY tblSJAHeader.Department", if "SJANumber" is selected, then "ORDER BY tblSJAHeader.SJANumber" etc.

Is it possible to change the query to reflect above?

Thanks.
 
Yes, but you need some vba.
An option would be to have 3 queries - one for each possible sort order.

Then have a Combo with value list
Department, SJANumber, SJATitle

Depending on which selection is made, use a Select Case statement to execute the appropriate query.

see http://www.techonthenet.com/access/functions/advanced/case.php
 
Forms have an order by property. If you're opening a form, you could set that instead.
 
It is actually a report, by I assume it should still work with the ORDER BY property.

This is what I have created, but there is no sorting done.

Code:
Private Sub cmdPrintList_Click()
Dim strListOrder As Integer

strListOrder = Me.cboListOrder.Value

Select Case strListOrder
            
    Case 1
       DoCmd.OpenReport "rptListSJA", acPreview
        Reports!rptListSJA.OrderBy = "SJATitle"
    Case 2
        DoCmd.OpenReport "rptListSJA", acPreview
        Reports!rptListSJA.OrderBy = "SJANumber"
    Case 3
        DoCmd.OpenReport "rptListSJA", acPreview
        Reports!rptListSJA.OrderBy = "Department"
End Select
    
End Sub

If I leave out the second line in each case statement, and write direvtly in the Order By property for the report before I run it, then it is sorting, so I assume it is the second line which is wrong somehow.
 
Ok. Will 'close' this post, and continue on report forum.
 
FYI - Access is smarter than us and so completely rewrites the query you use as the RecordSource for a report and ignores any column not bound to a control on the report and also ignores any order by clause since that is also defined by the report.
 

Users who are viewing this thread

Back
Top Bottom