Skip to content

Excel VBA How to Sort Data

    How to Sort Data

    To sort data use the Sort method.

    expression .Sort(Key1, Order1, Key2, Type, Order2, Key3,Order3, Header, OrderCustom, _
    MatchCase, Orientation, SortMethod, DataOption1,DataOption2, DataOption3)

    Sort on a Single Column

    This code would sort the database above in ascending date order.

    Range("A1").CurrentRegion.Sortkey1:=Range("B1"), order1:=xlAscending, Header:=xlYes

    Or, if you have named your columns…

    Range("A1").CurrentRegion.Sortkey1:=Range("Date"), order1:=xlAscending, Header:=xlYes

    Sort on Up to Three Columns

    This code would sort the table by payment type and within payment type by date. You can sort by up to 3 columns as there or three available key parameters. Key 1 is the primary sort.

    Range("A1").CurrentRegion.Sort_
    key1:=Range("Pay_Type"),order1:=xlDescending, _
    key2:=Range("Date"),order2:=xlAscending, _
    Header:=xlYes

    Sort by More than Three Columns

    This code would sort PAY_TYPE, and within PAY_TYPE by STORE_ID, within STORE_ID by PRODUCT_ID and then within PRODUCT_ID by DATE. Note that the primary sort is the last sort applied in the code: so you list the sorts in reverse order of importance.

    Range("A1").CurrentRegion.Sort_
    key1:=Range("Date"),order1:=xlDescending, Header:=xlYes
    Range("A1").CurrentRegion.Sort_
    key1:=Range("Prod_ID"),order1:=xlDescending, Header:=xlYes
    Range("A1").CurrentRegion.Sort_
    key1:=Range("Store_ID"),order1:=xlDescending, Header:=xlYes
    Range("A1").CurrentRegion.Sort_
    key1:=Range("Pay_Type"),order1:=xlDescending, Header:=xlYes