How can i change the "order by" property in an ms-access form using vba code

I have a form which displays data by date. i have a request to add logic to change the display order to "by amount". I want to use the same form and simply change the "Order by" property of the form prior to executing/invoking the form.
Who is Participating?
Dale FyeCommented:
I generally do this by:

1.  placing a combo (cbo_Order_By) in the form header, and entering the fields I want the user to be able to order by in that combo box.  Then, use the AfterUpdate event of the combo to update the Forms OrderBy property.  You could even add an option for ascending or descending.

Private Sub cbo_OrderBy_AfterUpdate

    if me.cbo_OrderBy & "" <> "" Then
        me.OrderBy = me.OrderBy = me.cbo_OrderBy
        me.OrderByOn = true
        me.OrderByOn = false
    end If

End Sub

Open in new window

2.  Put code in the click event of the forms column headers which calls a subroutine that sets the OrderBy property the same as above.

3.  Use my custom sorting form, which gives me the ability to sort by multiple columns, ascending or descending.  You define the columns you want to sort by and pass those to a subroutine which opens a form.  Read the article
Rey Obrero (Capricorn1)Commented:
use a query against the table with Order By clause on the Amount field as the Record Source of the form.
After refreshing the page, I see Rey was quicker to's by two cents with the additional thought of editing the form property ...
If the form is based on a pre-existing query, you can edit that query (in SQL View) to have the order by clause use 'byamount' field.

You also can set the 'Order By' property on the form itself, in Design View on the Data tab you enter the field name 'byamount'.
HansAtPaceAuthor Commented:
ALL, Thanks for your help. I have implemented code similar to Dale Frye's whereby I set the property "orderby" value depending on a response from the user on the main form. The only issue I found with that was that OrderBy value must apparently be set on the form which actually displays the data using the me.orderby property. Attempting to set the value for the OrderBy property from the main form did not accomplish the feat using  [forms].[formname].orderby .

Thank you all!
Dale FyeCommented:
You didn't mention the form/subform format.

In order to implement that from the main form, you would use:

me![subformControlName].Form.OrderBy = me.cbo_OrderBy
me.[subformControlName].Form.OrderByOn = true
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.