VBA Code to Sort Data

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:

VBA Code to sort data

After Sort:

VBA Code to 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:

VBA Code to Sort Data

After Sort:

VBA Code to Sort Data

Download Practice File

You can also practice this through our practice files. Click on the below link to download the practice file.

Recommended Articles

Similar Posts

Leave a Reply

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