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

Leave a Reply

avatar
VBA Code to Sum Cells by Color
EXCEL VBA TRICKS
VBA Code to Sum Cells by Color

Recently some of our subscribers have requested us to share a VBA code that can sum the cells by its color. To help our subscribers and developers, we are sharing 2 codes that be used to sum the cells with specific color and returns the total sum of the matching color cells

VBA Code to Delete File
EXCEL VBA TRICKS
VBA Code to Delete File

In this article we are going to show you how you can delete file or files using a single line of VBA code. 1. Delete a specific file from the folder, 2. Delete specific type of files from the folder, 3. Delete all files from the folder

VBA Code to Add Border to Excel Range
EXCEL VBA TRICKS
VBA Code to Add Border to Excel Range

Through formatting the cells, you can make your Excel data more beautiful and easier to understand. If you record a macro to add borders to Excel range, you will notice that it generates 30 plus lines of code for just a small work. Here we are sharing one line of code which does the same thing.

DO YOU WANT MORE UPDATE FROM US?

Enter your email address to follow this blog