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.

Intermediate 20 min read

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:

ABCDEF
1InvoiceCustomerRegionDateAmountStatus
2INV-1001Alder LtdNorth03-Nov-20261250Paid
3INV-1002Brook & CoSouth05-Nov-2026480Open
4INV-1003Alder LtdNorth12-Nov-20262300Open
5INV-1004Cedar plcEast15-Nov-2026760Paid
6INV-1005Brook & CoSouth20-Nov-20261940Overdue
7INV-1006Delta GmbHWest24-Nov-2026315Open

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.

VBA
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 Sub
Find one invoice number and show its amount

The arguments you should set every time:

ArgumentTypical valueWhat it controls
What"INV-1004"The value to look for; wildcards * and ? are allowed
LookInxlValues or xlFormulasSearch the displayed values or the formulas behind them
LookAtxlWhole or xlPartWhole-cell match, or the text anywhere inside the cell
MatchCaseFalseWhether upper and lower case must match
SearchOrderxlByRows or xlByColumnsRow by row or column by column
SearchDirectionxlNext or xlPreviousForwards or backwards from the start cell
Aftera single cellWhere the search starts (it begins with the cell after this one)
Watch out. 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.

VBA
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 Sub
List every invoice of one customer and add up the amounts

With 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.

Tip. For "find one value and return another" a worksheet function is often shorter: 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.

VBA
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 Sub
Show only open invoices in the South region

Calling 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:

VBA
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 Sub
Number ranges, top items and lists of values

xlFilterValues 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".

Note. Dates are the trickiest filter. Excel compares the criterion text with the cell's underlying serial number, and the result depends on regional settings. The safest form is a number: 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.

VBA
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 Sub
Copy all overdue invoices to a new sheet, then clear the filter

The 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.ShowAllData clears 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 = False removes 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:

VBA
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 Sub
Sort by region A to Z, then amount largest first

Always 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.

VBA
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 Sub
Sort by status in a custom order, then by date

CustomOrder 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.

VBA
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
Make a unique list of customers and regions on a new sheet
AB
1CustomerRegion
2Alder LtdNorth
3Brook & CoSouth
4Cedar plcEast
5Delta GmbHWest

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 Find without testing Is Nothing.
  • Leaving out LookAt and LookIn, so the search depends on whatever the user last did in Ctrl+F.
  • Writing an endless FindNext loop because the first address was not saved.
  • Counting SpecialCells(xlCellTypeVisible) on the whole range instead of one column: you get cells, not rows.
  • Calling ShowAllData when 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?

2. Why do you store found.Address before a FindNext loop?

3. Which code filters column 6 to show both Open and Overdue?

4. What is the safe way to clear filter criteria but keep the arrows?

5. What must you do before adding keys to ws.Sort.SortFields?