Excel like a finance pro.
VBA · Ranges
Sorting in code
Sorts a range by a key column.
When to use it
Range.Sort orders a range by one to three key columns. The Header argument keeps the first row in place.
The code
- Code
Range("A1:D100").Sort Key1:=Range("B1"), Order1:=xlDescending, Header:=xlYes
Worked examples
Sort by one column
Range("A1:D100").Sort Key1:=Range("B1"), Order1:=xlDescending, Header:=xlYes → Sorted by column B, largest first
The one-liner.
Two keys
Range("A1:D100").Sort Key1:=Range("C1"), Order1:=xlAscending, Key2:=Range("B1"), Order2:=xlDescending, Header:=xlYes → By C, then by B within C
Two keys.
Sort a block
Range("A1").CurrentRegion.Sort Key1:=Range("A1"), Header:=xlYes → Sort whatever block is at A1
Size-independent.
Worth knowing
- The newer ws.Sort.SortFields interface supports color sorts and more keys but is verbose.
- Always pass Header explicitly.
- Sort a Table with ListObject.Sort.
Where it goes wrong
- Omitting Header lets Excel guess and sometimes sorts the header into the data.
- Keys outside the range error.
Related
Learn the moves here — or let Wauvel run them on your numbers.
Meet your AI CFO →One CFO-grade Excel tip a week
A short, practical email for finance operators — functions, shortcuts, and the moves that save an afternoon. Free, unsubscribe anytime.