VBA Code to Sort Data

Here is a one line code for developer’s reference which can be used to sort data
'Sort data in ascending order on Column F (Created At)
Sheet1.Range("A1:G" & Sheet1.Cells.SpecialCells(xlCellTypeLastCell).Row).Sort Key1:=Sheet1.Range("F1"), Order1:=xlAscending, Header:=xlYes, DataOption1:=xlSortNormal

Before Sort:

35.1 Sort Data

After Sort:

35.2 Sort Data

 


 

If you are looking for a VBA code that can sort the data on multiple columns at the same time then below code may help you:
Public Sub SortByMultipleColumn()
    '
    'Clear old sort field
    Sheet1.Sort.SortFields.Clear
    'Add sort field on column D (Department ID)
    Sheet1.Sort.SortFields.Add Key:=Sheet1.Range("D2:D20"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    'Add sort field on column F (Created At)
    Sheet1.Sort.SortFields.Add Key:=Sheet1.Range("F2:F20"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With Sheet1.Sort
        .SetRange Range("A1:G20")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    '
End Sub

Before Sort:

35.3 Sort Data

After Sort:

35.4 Sort Data
Author:
Excelsirji.com was started with the thought of making people experience easy while working with Excel, data analytics, vba, automations etc.

Leave a Reply

Your email address will not be published. Required fields are marked *