VBA course · Lesson 22 of 33
Find, filter and sort data with VBA
Search with Range.Find and FindNext, filter lists with AutoFilter, copy only visible rows, sort with SortFields and remove duplicates from VBA.
Most real macros work on lists: an invoice register, a staff list, a sales export. Sooner or later you need to find a particular row, filter the list down to the rows that matter, or sort it into a useful order. You could do all of this with loops (For loops: For...Next and For Each), checking every cell one by one, but Excel already has fast, well-tested tools for these jobs. VBA gives you direct access to them: Range.Find, AutoFilter, Sort and RemoveDuplicates. This lesson shows each one with complete examples and the traps that catch almost everyone the first time.
All examples use this invoice register on a sheet named Invoices:
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Invoice | Customer | Region | Date | Amount | Status |
| 2 | INV-1001 | Alder Ltd | North | 03-Nov-2026 | 1250 | Paid |
| 3 | INV-1002 | Brook & Co | South | 05-Nov-2026 | 480 | Open |
| 4 | INV-1003 | Alder Ltd | North | 12-Nov-2026 | 2300 | Open |
| 5 | INV-1004 | Cedar plc | East | 15-Nov-2026 | 760 | Paid |
| 6 | INV-1005 | Brook & Co | South | 20-Nov-2026 | 1940 | Overdue |
| 7 | INV-1006 | Delta GmbH | West | 24-Nov-2026 | 315 | Open |
The Invoices sheet used in this lesson
Range.Find: the Ctrl+F of VBA
Find searches a range and returns the first matching cell as a Range object. If nothing matches it returns Nothing, a special value that means "no object". The most important rule of this lesson: always test for Nothing before you use the result. Code that does Set c = ...Find(...) and then immediately reads c.Row crashes with error 91 ("Object variable not set") as soon as the value is missing.
Option Explicit
Sub FindInvoice()
Dim ws As Worksheet
Dim found As Range
Dim invNo As String
Set ws = ThisWorkbook.Worksheets("Invoices")
invNo = "INV-1004"
Set found = ws.Range("A:A").Find(What:=invNo, _
LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If found Is Nothing Then
MsgBox invNo & " was not found.", vbExclamation
Else
MsgBox invNo & " is in row " & found.Row & _
", amount " & Format(found.Offset(0, 4).Value, "#,##0.00")
End If
End SubThe arguments you should set every time:
| Argument | Typical value | What it controls |
|---|---|---|
| What | "INV-1004" | The value to look for; wildcards * and ? are allowed |
| LookIn | xlValues or xlFormulas | Search the displayed values or the formulas behind them |
| LookAt | xlWhole or xlPart | Whole-cell match, or the text anywhere inside the cell |
| MatchCase | False | Whether upper and lower case must match |
| SearchOrder | xlByRows or xlByColumns | Row by row or column by column |
| SearchDirection | xlNext or xlPrevious | Forwards or backwards from the start cell |
| After | a single cell | Where the search starts (it begins with the cell after this one) |
Find remembers LookIn, LookAt, SearchOrder and MatchCase from the last search, including searches the user did with Ctrl+F (Cmd+F). If you leave them out, your macro may silently search for part of a cell because someone ticked "Match entire cell contents" off yesterday. Always pass them explicitly.Offset(0, 4) moves four columns to the right of the found cell, from Invoice to Amount. You could also write ws.Cells(found.Row, "E"), which is easier to read when columns are far apart.
Finding every match with FindNext
Find returns only the first match. To get all of them, call FindNext in a loop. FindNext wraps around: after the last match it starts again at the top, so the loop would run forever. The standard solution is to remember the address of the first match and stop when you are back at it.
Sub FindAllForCustomer()
Dim ws As Worksheet
Dim searchArea As Range
Dim found As Range
Dim firstAddress As String
Dim total As Double
Dim hits As Long
Set ws = ThisWorkbook.Worksheets("Invoices")
Set searchArea = ws.Range("B2:B" & ws.Cells(ws.Rows.Count, "B").End(xlUp).Row)
Set found = searchArea.Find(What:="Alder Ltd", LookIn:=xlValues, _
LookAt:=xlWhole, MatchCase:=False)
If found Is Nothing Then
MsgBox "No invoices for this customer."
Exit Sub
End If
firstAddress = found.Address
Do
hits = hits + 1
total = total + found.Offset(0, 3).Value
Debug.Print found.Offset(0, -1).Value, found.Offset(0, 3).Value
Set found = searchArea.FindNext(found)
Loop While found.Address <> firstAddress
MsgBox hits & " invoices, total " & Format(total, "#,##0.00")
End SubWith the sample data this finds INV-1001 and INV-1003 and reports a total of 3,550.00. The loop needs no extra Nothing check inside because the first match is never deleted; if your loop deletes or changes the found cells, so that they no longer match, check found Is Nothing inside the loop as well.
Application.Match or WorksheetFunction.XLookup from VBA (Using Excel worksheet functions in VBA). Use Find when you need the cell itself, all matches, partial matches or a search over a whole block.AutoFilter: show only the rows you want
AutoFilter is the filter you get from Data > Filter, controlled from code. You apply it to the whole list (headers included), give the field number, which is the column position inside the list starting at 1, and a criterion.
Sub FilterOpenSouth()
Dim ws As Worksheet
Dim data As Range
Set ws = ThisWorkbook.Worksheets("Invoices")
Set data = ws.Range("A1").CurrentRegion
' Remove any existing filter first
If ws.AutoFilterMode Then ws.AutoFilterMode = False
data.AutoFilter Field:=3, Criteria1:="South"
data.AutoFilter Field:=6, Criteria1:="Open"
End SubCalling AutoFilter twice on the same range adds a second condition on another column; both must be true. To combine two conditions on the same column, use Criteria1, Operator and Criteria2:
Sub FilterExamples()
Dim data As Range
Set data = ThisWorkbook.Worksheets("Invoices").Range("A1").CurrentRegion
' Amount between 500 and 2000
data.AutoFilter Field:=5, Criteria1:=">=500", _
Operator:=xlAnd, Criteria2:="<=2000"
' Status is Open OR Overdue: pass an array of values
data.AutoFilter Field:=6, _
Criteria1:=Array("Open", "Overdue"), _
Operator:=xlFilterValues
' Customers whose name starts with B (wildcard)
data.AutoFilter Field:=2, Criteria1:="B*"
End SubxlFilterValues with an Array(...) is the code version of ticking several boxes in the filter list. Other operators include xlOr, xlTop10Items and xlTop10Percent (with the count in Criteria1) and xlFilterDynamic for date periods such as "this month".
Criteria1:=">=" & CLng(DateSerial(2026, 11, 15)). See Working with dates and times in VBA for why dates are numbers.Copying the visible rows
The usual reason to filter in code is to copy the matching rows somewhere else. SpecialCells(xlCellTypeVisible) returns only the rows the filter shows. If no rows match, it raises an error instead of returning nothing, so check the count first.
Sub CopyOverdue()
Dim ws As Worksheet
Dim target As Worksheet
Dim data As Range
Dim visibleRows As Long
Set ws = ThisWorkbook.Worksheets("Invoices")
Set data = ws.Range("A1").CurrentRegion
If ws.AutoFilterMode Then ws.AutoFilterMode = False
data.AutoFilter Field:=6, Criteria1:="Overdue"
' Count visible cells in column A, minus the header
visibleRows = data.Columns(1).SpecialCells(xlCellTypeVisible).Count - 1
If visibleRows > 0 Then
Set target = ThisWorkbook.Worksheets.Add(After:=ws)
target.Name = "Overdue " & Format(Date, "yyyy-mm-dd")
data.SpecialCells(xlCellTypeVisible).Copy Destination:=target.Range("A1")
target.Columns.AutoFit
End If
ws.AutoFilterMode = False
MsgBox visibleRows & " overdue invoice(s) copied."
End SubThe copy includes the header row, because it is visible too. With the sample data, one row (INV-1005) is copied. The sheet name must be unique; running the macro twice on the same day fails at target.Name, which is a good case for the error handling in Error handling and debugging in VBA.
ShowAllData versus AutoFilterMode
There are two ways to clean up:
ws.ShowAllDataclears the criteria but keeps the filter arrows. It raises an error if no filter is currently active, so guard it:If ws.FilterMode Then ws.ShowAllData.ws.AutoFilterMode = Falseremoves the arrows and the criteria completely.
FilterMode is True when rows are actually hidden by a filter; AutoFilterMode is True when the arrows exist. Mixing these up is one of the most common errors in filtering code.
Sorting
The quick way: Range.Sort
For one to three sort keys, Range.Sort does the job in one statement:
Sub QuickSort()
Dim data As Range
Set data = ThisWorkbook.Worksheets("Invoices").Range("A1").CurrentRegion
data.Sort Key1:=data.Columns(3), Order1:=xlAscending, _
Key2:=data.Columns(5), Order2:=xlDescending, _
Header:=xlYes
End SubAlways pass Header:=xlYes. If you leave it out, Excel guesses, and a wrong guess sorts your header row into the middle of the data.
The full way: Worksheet.Sort with SortFields
The Sort object of a worksheet is what the Data > Sort dialog uses. It allows any number of keys, custom lists and sorting by colour. It also remembers old keys, so you must clear them first.
Sub SortWithSortFields()
Dim ws As Worksheet
Dim data As Range
Set ws = ThisWorkbook.Worksheets("Invoices")
Set data = ws.Range("A1").CurrentRegion
With ws.Sort
.SortFields.Clear
.SortFields.Add2 Key:=data.Columns(6), Order:=xlAscending, _
CustomOrder:="Overdue,Open,Paid"
.SortFields.Add2 Key:=data.Columns(4), Order:=xlAscending
.SetRange data
.Header = xlYes
.MatchCase = False
.Apply
End With
End SubCustomOrder sorts statuses by urgency instead of alphabetically. Add2 is the newer version of Add (Excel 2016 and later) and handles data types better; in older versions use .SortFields.Add with the same arguments.
Removing duplicates
RemoveDuplicates deletes rows whose values repeat in the columns you list, keeping the first occurrence. The column numbers are given as an array, relative to the range.
Sub UniqueCustomers()
Dim src As Range
Dim target As Worksheet
Dim lastRow As Long
Set src = ThisWorkbook.Worksheets("Invoices").Range("A1").CurrentRegion
Set target = ThisWorkbook.Worksheets.Add
' Copy Customer and Region (columns 2 and 3) only
src.Columns("B:C").Copy Destination:=target.Range("A1")
lastRow = target.Cells(target.Rows.Count, "A").End(xlUp).Row
target.Range("A1:B" & lastRow).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End Sub| A | B | |
|---|---|---|
| 1 | Customer | Region |
| 2 | Alder Ltd | North |
| 3 | Brook & Co | South |
| 4 | Cedar plc | East |
| 5 | Delta GmbH | West |
Result on the new sheet: one row per customer
RemoveDuplicates changes data permanently and cannot be undone after a macro, so run it on a copy, as here. If you only need the unique values in a cell, the UNIQUE function may be the better tool.
Common mistakes
- Using the result of
Findwithout testingIs Nothing. - Leaving out
LookAtandLookIn, so the search depends on whatever the user last did in Ctrl+F. - Writing an endless
FindNextloop because the first address was not saved. - Counting
SpecialCells(xlCellTypeVisible)on the whole range instead of one column: you get cells, not rows. - Calling
ShowAllDatawhen no filter is active, which raises an error. - Forgetting
SortFields.Clear, so yesterday's keys are applied as well. - Selecting cells before filtering or sorting. None of these methods needs
Select; see Make your macros fast: speed optimization in VBA.
Check yourself
1. What does Range.Find return when the value is not found?
Find returns Nothing; test with If found Is Nothing before using the result.
2. Why do you store found.Address before a FindNext loop?
When the search returns to the first address, every match has been visited.
3. Which code filters column 6 to show both Open and Overdue?
An array with xlFilterValues ticks several values in the same column.
4. What is the safe way to clear filter criteria but keep the arrows?
ShowAllData fails when nothing is filtered, so check FilterMode first.
5. What must you do before adding keys to ws.Sort.SortFields?
The Sort object keeps earlier keys; clearing them makes the sort predictable.