Sort Method

Applies To

Range Object.

Description

Syntax 1: Sorts the range, or sorts the current region if the range contains only one cell.

Syntax 2: Sorts a PivotTable; see the argument list for more information.

Syntax 1

object.Sort(key1, order1, key2, order2, key3, order3, header, orderCustom, matchCase, orientation)

Syntax 2

object.Sort(key1, order1, type, orderCustom, orientation)

object

Required. The Range object.

key1

Optional. The first sort field, as text (a pivot field or range name) or a Range object ("Dept" or Cells(1, 1), for example).

order1

Optional. If xlAscending or omitted, key1 is sorted in ascending order. If xlDescending, key1 is sorted in descending order.

key2

Optional. The second sort field, as text (a pivot field or range name) or a Range object. If omitted, there is no second sort field. Not used when sorting PivotTables.

type

Optional. Only used when sorting PivotTables. Specifies which elements are sorted, either xlSortValues or xlSortLabels.

order2

Optional. Sort order for key2 (xlAscending or xlDescending); if omitted, xlAscending is assumed. Not used when sorting PivotTables.

key3

Optional. The third sort field, as text (a range name) or a Range object. If omitted, there is no third sort field. Not used when sorting PivotTables.

order3

Optional. Sort order for key3 (xlAscending or xlDescending); if omitted, xlAscending is assumed. Not used when sorting PivotTables.

header

Optional. If xlYes, the first row contains headers (it is not sorted). If xlNo or omitted, no headers exist (the entire range is sorted). If xlGuess, Microsoft Excel guesses if there is a header, and where it is if there is one. Not used when sorting PivotTables.

orderCustom

Optional. One-based integer offset into the list of custom sort orders. If omitted, one (Normal) is used.

matchCase

Optional. If True, the sort is case sensitive. If False, the sort is not case sensitive. Not used when sorting PivotTables.

orientation

Optional. If xlTopToBottom or omitted, the sort is done from top to bottom (sort rows). If xlLeftToRight, the sort is done from left to right (sort columns).

Example

This example sorts the range A1:C20 on Sheet1, using cell A1 as the first sort key and cell B1 as the second sort key. The sort is done in ascending order by row, and there are no headers.


Worksheets("Sheet1").Range("A1:C20").Sort _
    key1:=Worksheets("Sheet1").Range("A1"), _
    key2:=Worksheets("Sheet1").Range("B1")

This example sorts the current region that contains cell A1 on Sheet1, sorting by the data in the first column and automatically using a header row if one exists. The Sort method determines the current region automatically.


Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Columns("A"), _
    header:=xlGuess