Vba sort columns in Excel
For example, I have Sales Data for Q1-2016 for different Salespersons as shown below. I would like to sort them in decreasing order of Sales using VBA.
To do it in Excel, here is the answer:
- Option Explicit
- Sub SortData()
- ActiveSheet.Sort.SortFields.Clear
- ActiveSheet.Sort.SortFields.Add Key:=Range("CY5:CY14"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
- With ActiveSheet.Sort
- .SetRange Range("CV4:CY14")
- .Header = xlYes
- .MatchCase = False
- .Orientation = xlTopToBottom
- .SortMethod = xlPinYin
- .Apply
- End With
- End Sub
Description:
a) Line 3 - Clear any existing sorting in ActiveSheet.
b) Line 4 - Define the Sort field (Sales value in Column CY) and Sort Order.
c) Line 6 - Define the Data range that needs to be sorted.
d) Line 7 - Since the Data range selected includes header, set ".Header" property to xlYes.
Result after Macro execution: