How To Sort Data in VBA in Microsoft Excel 2010

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
 
img1
 
Click on Developer tab

From Code group, select Visual Basic
 
img2
 
Click on Insert, and then Module
 
img3
 
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

 
img4
 
Press ALT + F8 shortcut key for opening Macro window & then select the macro.
 
img5
 
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.
 
img6
 
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)
 
img7
 
In this way, you can sort data easily using VBA code.

 

Leave a Reply

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

Terms and Conditions of use

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.