Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA String Search: Find Text in Cells

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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.
  2. Write a basic InStr test. In the module, type:
    Sub FindText()
    Dim pos As Long
    pos = InStr(1, "Smart Home Camera", "Home", vbTextCompare)
    MsgBox pos
    End Sub
    Run it with F5. The message box shows 7 because "Home" starts at the seventh character. InStr returns 0 when the string is not found, so always compare with > 0 rather than testing for True.
  3. Understand the arguments. The syntax is InStr([start], string1, string2, [compare]). start is the character position to begin at (use 1 to search the whole string). string1 is the text being searched, string2 is what you are looking for. vbTextCompare makes the search case-insensitive; vbBinaryCompare makes it case-sensitive. Omitting the compare argument uses the module's Option Compare setting, which is a common source of surprise.
  4. Search a single cell. To test cell A1:
    If InStr(1, Range("A1").Value, "camera", vbTextCompare) > 0 Then
    MsgBox "Found"
    Else
    MsgBox "Not found"
    End If
    This is the pattern you will reuse everywhere.
  5. Loop through a column. To check every used cell in column A and highlight matches:
    Dim lastRow As Long, i As Long
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To lastRow
    If InStr(1, CStr(Cells(i, "A").Value), "camera", vbTextCompare) > 0 Then
    Cells(i, "A").Interior.Color = vbYellow
    End If
    Next i
    Wrapping the value in CStr prevents errors when a cell contains an error value or is empty.
  6. Use the Like operator for wildcards. When you need patterns rather than a fixed substring, Like is 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. Like is case-sensitive by default unless you set Option Compare Text at the top of the module.
  7. Search the whole sheet with Find. For large ranges, Range.Find is much faster than looping:
    Dim found As Range
    Set found = ActiveSheet.Cells.Find(What:="camera", LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False)
    If Not found Is Nothing Then MsgBox found.Address
    LookAt:=xlPart means partial matches count; xlWhole requires the entire cell to equal the search term. Find remembers its last settings, so always pass every argument explicitly.
  8. 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, combine InStr with Mid: Mid(text, pos, Len(searchTerm)) returns the matched text itself.
  9. Handle multiple matches. Find returns only the first hit. To get all of them, call FindNext in a loop and stop when the returned range equals the first result — otherwise the loop runs forever.
  10. 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(...) Then fails 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 in CStr or test with IsError first.
  • Assuming Find searches the whole workbook. Cells.Find searches only the active sheet. Loop through Worksheets if 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. InStrRev searches 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 Text at the top of the module to make all string comparisons case-insensitive by default, then use vbBinaryCompare where 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 vbNullString instead 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.