To sort data in a range in ascending or descending order, use the Worksheet.Sort method. Note that this method has several overloads with serious advantages. You can specify the column by which to sort a multi-column range, sort by multiple columns, or use a custom comparer.
To sort data by multiple columns, follow the steps below.
Create the SortField object for each of the columns from which to sort. Specify the position of this column within the range using the SortField.ColumnOffset property and assign a comparer using the SortField.Comparer property. Instead of implementing your own comparer with the IComparer<T><CellValue,> interface, you can use one of the built-in comparers which are responsible for sort operations performed by end-users. There are two built-in comparers - Worksheet.Comparers.Ascending is used for sorting in ascending order; Worksheet.Comparers.Descending is used for sorting in descending order.
Create a list containing sort fields.
Call the Worksheet.Sort method with two parameters: the first is the CellRange to be sorted, the other is the list of sort fields.
Worksheet worksheet = workbook.Worksheets["SortSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Create sorting fields.
List<SortField> fields = new List<SortField>();
// First sorting field. First column (offset = 0) will be sorted using ascending order.
SortField sortField1 = new SortField();
sortField1.ColumnOffset = 0;
sortField1.Comparer = worksheet.Comparers.Ascending;
// Second sorting field. Second column (offset = 1) will be sorted using ascending order.
SortField sortField2 = new SortField();
sortField2.ColumnOffset = 1;
sortField2.Comparer = worksheet.Comparers.Ascending;
// Sort the range by sorting fields.
CellRange range = worksheet.Range["A3:F22"];
Dim worksheet As Worksheet = workbook.Worksheets("SortSample")
workbook.Worksheets.ActiveWorksheet = worksheet
' Create sorting fields.
Dim fields As New List(Of SortField)()
' First sorting field. First column (offset = 0) will be sorted using ascending order.
Dim sortField1 As New SortField()
sortField1.ColumnOffset = 0
sortField1.Comparer = worksheet.Comparers.Ascending
' Second sorting field. Second column (offset = 1) will be sorted using ascending order.
Dim sortField2 As New SortField()
sortField2.ColumnOffset = 1
sortField2.Comparer = worksheet.Comparers.Ascending
' Sort the range by sorting fields.
Dim range As CellRange = worksheet.Range("A3:F22")
The image below shows the result (the workbook is opened in Microsoft® Excel®). The cell range is sorted by the first and second columns in ascending order.
Was this page helpful?
Thanks for your feedback! Any other suggestions? Tell us here.