Applying data sorting concept on a Data in Microsoft excel using VBA — Excel VBA
Data Sorting is another concept that is very useful while working on the data. You may need to sort your data from A to Z or Z to A or numerically in ascending and descending order. In excel it’s very much simple you just need to use a simple hotkey that is alt+ds and it will pop the dialogue box in which you can set the sorting criteria.
But what if we want to sort the data using VBA codes. Let’s write some codes to sort the data using VBA codes.
Code:
Sub sortingg()
Range(“a1”).CurrentRegion.Sort key1:=Range(“a1”), order1:=xlDescending, Header:=xlYes
End Sub
Code explanation:
The current region is the concept to select the whole data. Sort is the keyword in VBA to do the sorting.
Then we need to provide the key. Key is basically the column basis on which we want to sort the data. Here we need to give the reference of the first cell so apply to sort on that column so we have given range(“a1”) because we want to sort the data based on the name column. Then you need to mention the order in the coding. Order means how you want to sort your data — Ascending or Descending. It works for both text and numerical data. If data is alphabetical then it will sort a to z or z to a and if it is numerical then it will work in ascending or descending order. In the last, you need to provide header information. If you want your data headers to be sorted up as well then mention “xlno” and if you want to exclude your headers from sorting then mention “xlyes”.
Output:
I hope I am able to make you understand the concept. If you need any clarification please drop a comment. Thank you! Happy Learning!
Previous Chapter — Next Chapter
Quick References
What is Offset & Resize in Excel VBA? How to use Offset and Resize in Excel VBA?
What is Option Explicit and Option Implicit In VBA? Why its is used?
What is UsedRange and How it is used in VBA? | VBA Codes | Learnitix
What is With Statement and how it is used in VBA? | VBA Codes | Learnitix
What is a for loop in Excel VBA? How do you write a for loop in VBA?
What is current Region and how it is used in excel VBA? | VBA Codes | Learnitix
What is if statement in VBA? What is if then else statement in VBA? Nested if in VBA