Excel VBA Search Function: A Practical How-To
In this article
You can build a working search function in Excel VBA in about ten minutes: open the VBA editor with Alt+F11, insert a module, and write a short macro that uses the Find method or a For Each loop to scan a range and return matches. The Find method is the fastest and simplest for a single match; a loop is better when you need every hit or want to search multiple columns. This guide walks through both, with a reusable function you can drop into any workbook.
What You'll Need
- Excel on Windows or Mac (the VBA editor is included in both; the Mac editor looks slightly different but the menu names below are close).
- A workbook saved as .xlsm (macro-enabled) so your code is kept.
- The Developer tab visible: File > Options > Customize Ribbon > tick Developer. On Mac, Excel > Preferences > Ribbon & Toolbar.
- Macro security set to allow macros in trusted locations, or you will see a security warning each time.
Step-by-Step
- Open the VBA editor. Press Alt+F11 (on Mac, Fn+Alt+F11 or use Tools > Macro > Visual Basic Editor). A separate window opens.
- Insert a module. In the editor, choose Insert > Module. A blank code pane appears on the right. Code in a standard module is available to the whole workbook.
- Write a simple Find macro. Paste this and change the sheet name and range to match your data:
Sub FindOne() Dim ws As Worksheet Dim found As Range Dim term As String Set ws = ThisWorkbook.Worksheets("Sheet1") term = InputBox("What do you want to find?") If term = "" Then Exit Sub Set found = ws.Range("A1:A100").Find( _ What:=term, _ LookIn:=xlValues, _ LookAt:=xlPart, _ MatchCase:=False) If found Is Nothing Then MsgBox "No match for " & term Else MsgBox "Found in " & found.Address & ": " & found.Value found.Select End If End SubThe key arguments: LookIn:=xlValues searches displayed values (use xlFormulas to search formulas), LookAt:=xlPart matches anywhere in the cell (xlWhole matches the entire cell), and MatchCase:=False ignores case. - Run it. Click inside the Sub and press F5, or go back to Excel and use Developer > Macros, select FindOne, and click Run. Type a search term in the input box. If a match exists, Excel jumps to it and shows the address.
- Search every match, not just the first. The Find method returns one cell at a time. To list all hits, wrap it in a loop that calls FindNext until it wraps back to the first result:
Sub FindAll() Dim ws As Worksheet, rng As Range, found As Range Dim term As String, firstAddr As String, results As String Set ws = ThisWorkbook.Worksheets("Sheet1") Set rng = ws.Range("A1:A100") term = InputBox("Search term?") If term = "" Then Exit Sub Set found = rng.Find(term, LookIn:=xlValues, LookAt:=xlPart) If found Is Nothing Then MsgBox "No matches" Exit Sub End If firstAddr = found.Address Do results = results & found.Address & " - " & found.Value & vbCrLf Set found = rng.FindNext(found) Loop While Not found Is Nothing And found.Address <> firstAddr MsgBox results End SubThe firstAddr check is essential: without it, FindNext keeps cycling forever. - Return a row number instead of a message. If you want to use the result in other code, change the message box to a function return. A small helper makes this reusable:
Function FindRow(ws As Worksheet, term As String) As Long Dim f As Range Set f = ws.Columns("A").Find(term, LookIn:=xlValues, LookAt:=xlWhole) If f Is Nothing Then FindRow = 0 Else FindRow = f.Row End If End FunctionCall it from another macro with rowNum = FindRow(Sheets("Sheet1"), "Widget"). A return of 0 means not found. - Search across multiple columns. Change the range to the full table, for example ws.Range("A1:D100"), or use ws.UsedRange to cover everything with data. Find will scan row by row across that block.
- Save and test. Press Ctrl+S. Excel prompts you to keep the macro-enabled format; choose Yes. Run the macro on a copy of your data first so a bug cannot overwrite anything.
Common Mistakes
- Forgetting the firstAddr check. FindNext loops forever without comparing back to the starting address.
- Using LookAt:=xlWhole when you meant partial. "Widget" will not match "Blue Widget" with xlWhole. Switch to xlPart for substring searches.
- Searching the wrong sheet. ThisWorkbook refers to the file containing the code; ActiveSheet refers to whatever tab is visible. Be explicit with Worksheets("Sheet1").
- Assuming Find returns a value. It returns a Range object or Nothing. Always test If found Is Nothing before using .Value or .Address, or you get run-time error 91.
- Leaving Find settings sticky. Find remembers the last LookIn, LookAt and MatchCase settings across calls. Set them every time in your code.
- Searching hidden rows or filtered data. Find skips hidden cells by default in some cases; use a For Each loop over the range if you need to include them.
Tips
- Use Application.WorksheetFunction.Match when you only need the position of an exact value in a single column; it is faster than Find for large ranges.
- For very large datasets, read the range into a Variant array and loop the array in memory; cell-by-cell Find is slow past tens of thousands of rows.
- Add Application.ScreenUpdating = False at the start and True at the end of long macros to speed them up.
- Use wildcards in the search term: * for any characters, ? for one character. Escape a literal asterisk with ~*.
- Store the search term in a named cell or a small user form if you run the macro often; typing into InputBox every time gets tedious.
Troubleshooting
- Macro does nothing. Check the Developer tab is enabled and macro security is not blocking. Look at the Immediate window (Ctrl+G) for errors.
- Run-time error 91 (Object variable not set). You used the result of Find before checking for Nothing. Add the If test.
- Wrong sheet searched. Print the sheet name with Debug.Print ws.Name to confirm what the code is looking at.
- No matches when you can see the text. The cell may contain a formula returning text, a leading space, or a number stored as text. Try LookIn:=xlFormulas, or trim the term with Trim(term).
- Macro disappeared after saving. The file was saved as .xlsx, which strips macros. Save as .xlsm.
- Search is slow. Narrow the range, turn off ScreenUpdating, or switch to an array loop.
Frequently Asked Questions
Can I search for a value and return the whole row?
Yes. Once Find returns a cell, use found.EntireRow to read or copy the full row, for example found.EntireRow.Copy Destination:=Sheets("Results").Range("A1").
Does Find work on multiple sheets at once?
No. Find works on one Range object. Loop through ThisWorkbook.Worksheets and call Find on each sheet's range, collecting results as you go.
How do I make the search case-sensitive?
Set MatchCase:=True in the Find call. The default is False, which ignores case.
Can I search by cell colour or format?
Yes, Find accepts SearchFormat:=True with format criteria set beforehand via Application.FindFormat. It is fiddly; a loop checking cell.Interior.Color is often clearer.
Why does Find return the wrong cell after the first run?
Because Find remembers the last search settings and starting cell. Always pass LookIn, LookAt and MatchCase explicitly, and pass the full range each time.
Can this run automatically when a cell changes?
Yes, but the code must go in the worksheet's code module (double-click the sheet in the Project Explorer and use the Worksheet_Change event), not a standard module. Keep it simple to avoid recursive triggers.