In this article, you will learn how to sort data using VBA code.
Data sorting is a daily activity which is required to perform to make data easier to understand.
Let us take an example:
We have Sales Report & we need to sort by Sales numbers
Click on Developer tab
From Code group, select Visual Basic
Click on Insert, and then Module
This will create a new module.
Enter the following code in the Module
Sub Sortdata_ascending()
Sheets(1).Range("a1:b" & Range("a1").End(xlDown).Row).Sort _
key1:=Sheets(1).Range("b:b"), order1:=xlAscending, Header:=xlYes
End Sub
Press ALT + F8 shortcut key for opening Macro window & then select the macro.
Alternatively, you can press F5 to run the code in VBA screen.
The above code will sort the data in ascending order by Sales values.
To sort data in descending order by Sales value (the highest Sales will be listed at top & then goes down), we will use the following VBA code:
Sub Sortdata_descending()
Sheets(1).Range("a1:b" & Range("a1").End(xlDown).Row).Sort _
key1:=Sheets(1).Range("b:b"), order1:=xlDescending, Header:=xlYes
End Sub
After executing the macro, we will get the following result (Sales in Largest to Smallest)
In this way, you can sort data easily using VBA code.
The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.