How to sort (ORDER BY) a query (1 Viewer)

anb001

Registered User.
Local time
Today, 05:37
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.
 

jdraw

Super Moderator
Staff member
Local time
Yesterday, 23:37
Joined
Jan 23, 2006
Messages
15,423
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
 

projecttoday

Registered User.
Local time
Yesterday, 23:37
Joined
Jan 5, 2011
Messages
51
Forms have an order by property. If you're opening a form, you could set that instead.
 

anb001

Registered User.
Local time
Today, 05:37
Joined
Jul 5, 2004
Messages
197
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.
 

anb001

Registered User.
Local time
Today, 05:37
Joined
Jul 5, 2004
Messages
197
Ok. Will 'close' this post, and continue on report forum.
 

Pat Hartman

Super Moderator
Staff member
Local time
Yesterday, 23:37
Joined
Feb 19, 2002
Messages
43,774
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

Top Bottom