Excel VBA String Search: Find Text in Cells
In this article
To search for a string in Excel VBA, use the InStr function to get the position of one string inside another, or loop through a range and test each cell with InStr or the Like operator. The shortest working pattern is If InStr(1, cell.Value, "text", vbTextCompare) > 0 Then — a result greater than zero means the text was found. This guide shows the exact syntax, how to search a whole column or sheet, and how to handle case, wildcards and empty cells.
What You'll Need
- Excel on Windows or Mac with the Developer tab enabled (File > Options > Customize Ribbon > tick Developer; on Mac, Excel > Preferences > Ribbon & Toolbar).
- A workbook saved as .xlsm (macro-enabled) if you want to keep your code.
- Basic familiarity with the VBA editor: press Alt+F11 (Windows) or Option+F11 (Mac) to open it.
- Some text in a worksheet to test against — a column of names, product codes or notes works well.
Menu labels and editor shortcuts can differ slightly by Excel version and by operating system; the code itself is the same.
Step-by-Step
- Open the VBA editor and insert a module. Press Alt+F11 (Windows) or Option+F11 (Mac), then in the Project Explorer right-click your workbook and choose Insert > Module. Code in a standard module can be run from the Macros dialog.
- Write a basic InStr test. In the module, type:
Sub FindText()Dim pos As Longpos = InStr(1, "Smart Home Camera", "Home", vbTextCompare)MsgBox posEnd Sub
Run it with F5. The message box shows 7 because "Home" starts at the seventh character.InStrreturns 0 when the string is not found, so always compare with> 0rather than testing for True. - Understand the arguments. The syntax is
InStr([start], string1, string2, [compare]).startis the character position to begin at (use 1 to search the whole string).string1is the text being searched,string2is what you are looking for.vbTextComparemakes the search case-insensitive;vbBinaryComparemakes it case-sensitive. Omitting the compare argument uses the module's Option Compare setting, which is a common source of surprise. - Search a single cell. To test cell A1:
If InStr(1, Range("A1").Value, "camera", vbTextCompare) > 0 ThenMsgBox "Found"ElseMsgBox "Not found"End If
This is the pattern you will reuse everywhere. - Loop through a column. To check every used cell in column A and highlight matches:
Dim lastRow As Long, i As LonglastRow = Cells(Rows.Count, "A").End(xlUp).RowFor i = 1 To lastRowIf InStr(1, CStr(Cells(i, "A").Value), "camera", vbTextCompare) > 0 ThenCells(i, "A").Interior.Color = vbYellowEnd IfNext i
Wrapping the value inCStrprevents errors when a cell contains an error value or is empty. - Use the Like operator for wildcards. When you need patterns rather than a fixed substring,
Likeis clearer:If CStr(cell.Value) Like "*cam*" Then
The asterisk matches any number of characters, the question mark matches one character, and#matches a single digit.Likeis case-sensitive by default unless you setOption Compare Textat the top of the module. - Search the whole sheet with Find. For large ranges,
Range.Findis much faster than looping:Dim found As RangeSet found = ActiveSheet.Cells.Find(What:="camera", LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False)If Not found Is Nothing Then MsgBox found.AddressLookAt:=xlPartmeans partial matches count;xlWholerequires the entire cell to equal the search term.Findremembers its last settings, so always pass every argument explicitly. - Return the found text or its position. To send the matched cell's address to the Immediate window, use
Debug.Print found.Address. To extract a substring around the match, combineInStrwithMid:Mid(text, pos, Len(searchTerm))returns the matched text itself. - Handle multiple matches.
Findreturns only the first hit. To get all of them, callFindNextin a loop and stop when the returned range equals the first result — otherwise the loop runs forever. - Test and save. Run the macro with F5 or from Developer > Macros. Save the workbook as .xlsm so the code is retained.
Common Mistakes
- Testing InStr as a Boolean.
If InStr(...) Thenfails when the match is at position 0 — but it also misleads when the match is at position 1, because some people expect 1 to mean True. Always compare> 0. - Forgetting the compare argument. Without
vbTextCompare, "Camera" and "camera" are different strings. Decide deliberately which behaviour you want. - Searching error cells. A cell containing #N/A raises a type mismatch when passed to
InStr. Wrap values inCStror test withIsErrorfirst. - Assuming Find searches the whole workbook.
Cells.Findsearches only the active sheet. Loop throughWorksheetsif you need workbook-wide results. - Leaving Find's arguments out. A previous search may have set
MatchCase:=True, so your next call silently misses lowercase matches. Specify every argument. - Using InStrRev when you meant InStr.
InStrRevsearches from the end of the string and returns the last match, which is useful for file extensions but wrong for first-occurrence searches.
Tips
- Put
Option Compare Textat the top of the module to make all string comparisons case-insensitive by default, then usevbBinaryComparewhere you need exact case. - Trim cell values with
Trim(CStr(cell.Value))before searching so trailing spaces do not break matches. - For repeated searches in a loop, read the range into a Variant array first — it is dramatically faster than touching each cell.
- Use
vbNullStringinstead of "" when testing for empty strings; it is the idiomatic VBA constant. - Name your search term as a constant or read it from a cell, so you can change it without editing code.
Troubleshooting
The macro finds nothing. Check the compare argument first, then confirm the search range actually contains data — End(xlUp) on an empty column returns row 1. Print lastRow to the Immediate window to verify.
Run-time error 13 (type mismatch). A cell holds an error value or a date that cannot be coerced. Wrap the value in CStr and skip error cells with If Not IsError(cell.Value) Then.
The macro is very slow. Turn off screen updating while it runs: Application.ScreenUpdating = False at the start and back to True at the end. Better still, switch to Range.Find or an array.
Find returns Nothing unexpectedly. The sheet may be filtered or the values may be formulas returning text that LookIn:=xlValues cannot see in some cases — try LookIn:=xlFormulas.
The code will not run at all. Macros may be disabled. Check File > Options > Trust Center > Trust Center Settings > Macro Settings, and confirm the file is saved as .xlsm. On a managed work machine, macro policy may be controlled by your administrator.
If that did not work, step through the code line by line with F8 to see exactly which line fails, and use Debug.Print to inspect the values being compared.
Frequently Asked Questions
What is the difference between InStr and the Like operator?
InStr returns the character position of a substring and is best for simple "contains" tests. Like returns True or False and supports wildcards, so it suits pattern matching such as codes starting with a letter.
How do I make the search case-insensitive?
Pass vbTextCompare as the fourth argument to InStr, or set Option Compare Text at the top of the module.
Can I search for text across multiple sheets?
Yes. Loop through each worksheet in ThisWorkbook.Worksheets and run Cells.Find or your InStr loop on each one, collecting the results.
Why does InStr return 0 when the text is clearly there?
Usually a case mismatch, a leading or trailing space, or the compare argument set to binary. Trim the value and use vbTextCompare.
How do I find the last occurrence of a string?
Use InStrRev(string1, string2), which searches from the end and returns the position of the last match.
Does Range.Find search hidden rows?
Yes, it searches hidden rows and columns as well as visible ones, so results can appear in places you cannot see on screen.