This method is used to dynamically sort any particular columns in Microsoft Excel through VBA program. It depends on which columns you want to consider for sorting function and what specific cell you want to use as key or reference for sorting the data.
Range object represents a cell, row, column, selection of cells containing more than one blocks of cells.
Specifies the first sort field, either as a range name (String) or Range object; determines the values to be sorted.
Determines the sort order for the values specified in Key1.
Second sort field; cannot be used when sorting a pivot table.
Specified which elements are to be sorted.
Determines the sort order for the values specified in Key2.
Third sort field; cannot be used when sorting a pivot table.
Determines the sort order for the values specified in Key3.
Specifies whether the first row contains header information. xlNo is the default value; specify xlGuess if you want Excel to attempt to determine the header.
Specifies a one-based integer offset into the list of custom sort orders.
Set to True to perform a case-sensitive sort, False to perform non-case sensitive sort; cannot be used with pivot tables.
Specifies if the sort should be in acending or decending order.
Specifies the sort method.
Specifies how to sort text in the range specified in Key1; does not apply to pivot table sorting.
Specifies how to sort text in the range specified in Key2; does not apply to pivot table sorting.
Specifies how to sort text in the range specified in Key3; does not apply to pivot table sorting.
The following code will sort the data based on column labeled “Agent". Please see figure below for the result before and after executing the sort method:
Dim oneRange As Range
Dim aCell As Range
Set sortRange = Range("F10:H15")
Set keyCell = Range("G10")
sortRange.Sort Key1:=keyCell, Order1:=xlAscending, Header:=xlYes
Before sort method is executedAfter sort method is executed (Highlighted in yellow indicates that the “Agent" column has been sorted)
Another example below shows how to sort a column by color index:
Dim iCount As Integer
‘Set the color index of column “F" from row 3 to 7 to column “H" row 3 to 7.
For iCount = 3 To 7
Cells(iCount, 8) = _
‘Apply the sort key defined as column H3 where the color index was stored
Columns("F:I").Sort key1:=Range("H3"), _
Before sort method is executed
After sort method is executed (The following figure shows the corresponding color index and the result after execution)
Depending on the data that you want to sort with different conditions, the sort method is always useful for dynamic manipulation.