Sort data and remove duplicates with VBA
Put a list in order by name, by region and sales, or by customer number: with Range.Sort it takes one line of code. This lesson covers the arguments you need and how to get rid of duplicate entries.
In short: Range("A1:C" & lastRow).Sort Key1:=Range("C1"), Order1:=xlDescending, Header:=xlYes sorts the table by column C, largest value first, and leaves the header in row 1.
What you need to know: finding the last row and deleting rows.
Try it right now
Sort the phone list by last name. Make sure first name and extension stay with the last name.
Task Sort the phone list alphabetically by last name (A to Z), keeping the header at the top. Write the macro SortList using Range.Sort. The list will grow later.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Last name | First name | Extension | |
| 2 | Walsh | Liam | 214 | |
| 3 | Baker | Emma | 305 | |
| 4 | Johnson | Mia | 118 | |
| 5 | Clarke | Olivia | 220 | |
| 6 | Patel | Ravi | 307 | |
| 7 | Hughes | Grace | 131 |
How Range.Sort works
Range("A1:C" & lastRow).Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
| Argument | Meaning | In the example |
|---|---|---|
Range before .Sort | All columns that belong together. Only these rows are rearranged. | A1:C down to the last row |
Key1 | A cell in the column to sort by. | Range("A1"), so column A |
Order1 | xlAscending (A to Z, smallest number first) or xlDescending. | ascending |
Key2, Order2, Key3, Order3 | Second and third key. They only decide where the previous key is equal. | not used |
Header | xlYes: the first row is a header and stays on top. According to Microsoft, xlNo is the default. xlGuess lets Excel decide. | xlYes |
The range has to cover the whole table. Sort only column A and the last names end up in a new order while the first names stay in the old one. The data no longer matches, and after a macro, Ctrl+Z will not bring it back.
As in Excel, an ascending sort puts numbers before text, and empty cells go to the end. Dates are numbers to Excel, so they sort chronologically.
Sorting by several columns
Region first, then sales within each region: for that, Sort gets a second key with its own order. Key2 only matters for rows that are equal in Key1.
Range("A1:C" & lastRow).Sort Key1:=Range("B1"), Order1:=xlAscending, _
Key2:=Range("C1"), Order2:=xlDescending, Header:=xlYes
Task Sort the sales list by region (A to Z) and, within each region, by sales with the largest at the top. The header stays in row 1. Write the macro SortByRegion.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Rep | Region | Sales | |
| 2 | Emma Clarke | South | 18,400 | |
| 3 | Jake Turner | North | 22,150 | |
| 4 | Mia Johnson | West | 9,800 | |
| 5 | Ravi Patel | North | 31,200 | |
| 6 | Olivia Brown | South | 26,900 | |
| 7 | Liam Walsh | East | 15,300 | |
| 8 | Grace Hughes | West | 17,650 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Removing duplicates
Excel has a method for this. The example from the Microsoft documentation removes rows that match in the first two columns and keeps the header:
Range("A1:C100").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
Columns lists the columns of the range that must be equal for a row to count as a duplicate. The first row with those values stays; the others go and the list closes up.
The second way needs no special method and is easy to follow: sort so that equal entries sit together, then delete backwards every row that matches the row above. It combines what you learned in this lesson and the last one, and it is how you solve the exercise:
Task The customer list comes from two exports, and some customers appear twice. The macro CleanCustomers sorts the list by customer number (ascending, with header), then deletes every row whose customer number equals the one in the row above, and finally reports the number of customers exactly like this: "5 customers" (with the right number).
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Customer no | Name | City | |
| 2 | 1004 | Harris & Sons | Bristol | |
| 3 | 1002 | Peters Motors | Denver | |
| 4 | 1003 | Green Dental | Boston | |
| 5 | 1002 | Peters Motors | Denver | |
| 6 | 1001 | Carter Bakery | Leeds | |
| 7 | 1005 | Lakeside Hotel | Keswick | |
| 8 | 1001 | Carter Bakery | Leeds |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
In real Excel
In the ribbon, the same thing lives under Data > Sort. If you record it with the macro recorder, you do not get Range.Sort but a longer block with Sort.SortFields.Clear and SortFields.Add. That Sort object of the sheet can also handle more than three keys. For most lists, the short form from this lesson is all you need.
Common mistakes
Forgetting Header
Without Header:=xlYes, Excel sorts the header along with the data. In the region exercise, "Region" ends up between North and South, and Check reminds you that A1 should contain the heading and the data starts in row 2.
Sorting only one column
Range("B1:B" & lastRow).Sort … rearranges only the regions; names and sales stay where they were. Check then finds the wrong name in row 2. Use a range across all columns, such as Range("A1:C" & lastRow) or Range("A1").CurrentRegion.
Key outside the range
If Key1 sits in a column that is not part of the sorted range, the macro stops. Excel and the exercise then show "Run-time error '1004': The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank."
A fixed range
Range("A1:C8").Sort … only works while the list has exactly 8 rows. New entries stay unsorted at the bottom. Check tests with more rows and tells you it works on the visible data but not on other data.
FAQ
How do I sort case-sensitively?
With the argument MatchCase:=True. With MatchCase:=False, Excel ignores case.
Does Key1 have to be the header cell?
No, any cell in the column works, Range("C1") as well as Range("C2"). Only the column matters.
How do I sort by more than three columns?
With the sheet's Sort object (Worksheets("Data").Sort with one SortFields.Add per key). The macro recorder shows you the structure if you record a sort once via Data > Sort.
How do I find a particular entry afterwards?
With Range.Find, which is the next lesson, Find.