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.

ABCD
1Last nameFirst nameExtension
2WalshLiam214
3BakerEmma305
4JohnsonMia118
5ClarkeOlivia220
6PatelRavi307
7HughesGrace131

How Range.Sort works

Range("A1:C" & lastRow).Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
ArgumentMeaningIn the example
Range before .SortAll columns that belong together. Only these rows are rearranged.A1:C down to the last row
Key1A cell in the column to sort by.Range("A1"), so column A
Order1xlAscending (A to Z, smallest number first) or xlDescending.ascending
Key2, Order2, Key3, Order3Second and third key. They only decide where the previous key is equal.not used
HeaderxlYes: 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.

ABCD
1RepRegionSales
2Emma ClarkeSouth18,400
3Jake TurnerNorth22,150
4Mia JohnsonWest9,800
5Ravi PatelNorth31,200
6Olivia BrownSouth26,900
7Liam WalshEast15,300
8Grace HughesWest17,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).

ABCD
1Customer noNameCity
21004Harris & SonsBristol
31002Peters MotorsDenver
41003Green DentalBoston
51002Peters MotorsDenver
61001Carter BakeryLeeds
71005Lakeside HotelKeswick
81001Carter BakeryLeeds

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.

Learn this next: Find

Find searches the sheet for a value like Ctrl+F and hands you the cell. You learn what happens when it finds nothing, and how to deal with that.

Learn Find

Write to us

Choose language

Select your preferred language