|
|
Title | Sort Excel data using more than three columns |
Keywords | Excel, Office, sort |
Categories | Office |
|
|
Excel only allows you to use three columns as sort keys. To sort using more than three columns as keys, sort using each column as a key individually in reverse order. In other words, to sort using columns A, B, C, and D, first sort using D, then using C, then using B, and finally using A.
The following code sorts the selected cells using all of their columns as keys.
|
|
' Sort the selected cells by column 1, column 2, etc.
Sub SortSelection()
' Sort using the columns in reverse order.
For c = Selection.Columns.Count To 1 Step -1
Selection.Sort _
Key1:=Selection.Columns.Item(c), _
Order1:=xlAscending, _
Header:=xlGuess, _
OrderCustom:=1, _
MatchCase:=False, _
Orientation:=xlTopToBottom
Next c
End Sub
|
|
You'll need to modify this code if you want some columns sorted descending, if you want to not use some selected columns as keys, etc.
The sample file also includes a subroutine to randomize a selected of cells to test with, and a routine that verifies that the selected cells are properly sorted.
|
|
|
|
|
|