Smart Systems for Home

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

Excel VBA String Contains: A How-To Guide

· 5 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 check whether a string contains a substring in Excel VBA, use the InStr function. It returns the character position of the first match (0 if not found), so you test If InStr(1, text, substring) > 0 Then. For case-insensitive matching, pass vbTextCompare as the fourth argument or use Option Compare Text at the top of the module. This guide walks through the exact syntax, common patterns, and fixes for the usual pitfalls.

What You'll Need

  • Excel with macros enabled (any desktop version).
  • Access to the VBA editor: press Alt+F11 on Windows, or Opt+F11 on Mac.
  • A workbook saved as .xlsm or .xlsb so your code persists.
  • Basic familiarity with variables and If statements.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or Opt+F11 (Mac). If the Project Explorer is hidden, choose View > Project Explorer. Menu labels can differ slightly by version and platform.
  2. Insert a module. In the Project Explorer, right-click your workbook name, choose Insert > Module. Code in a standard module is available to all sheets.
  3. Write a basic InStr test. Paste this into the module:
    Sub CheckContains()
        Dim text As String
        Dim find As String
        text = "Smart home hub"
        find = "home"
        If InStr(1, text, find) > 0 Then
            MsgBox "Found at position " & InStr(1, text, find)
        Else
            MsgBox "Not found"
        End If
    End Sub
    The first argument (1) is the start position. The function returns 0 when there is no match, so always compare with > 0, not with = 1.
  4. Make it case-insensitive. Add vbTextCompare as the fourth argument: InStr(1, text, find, vbTextCompare). Alternatively, put Option Compare Text at the very top of the module (before any procedures). With Option Compare Text, all string comparisons in that module ignore case.
  5. Test against a cell. Replace the hard-coded text with a cell reference:
    If InStr(1, Range("A1").Value, "error", vbTextCompare) > 0 Then
        MsgBox "Cell A1 mentions error"
    End If
    Use .Value (not .Text) to get the underlying value rather than the displayed formatting.
  6. Loop through a range. To flag every row that contains a keyword:
    Dim r As Range
    For Each r In Range("A1:A100")
        If InStr(1, CStr(r.Value), "urgent", vbTextCompare) > 0 Then
            r.Offset(0, 1).Value = "Flagged"
        End If
    Next r
    CStr guards against empty cells and errors.
  7. Use InStrRev for the last occurrence. InStrRev(text, find) searches from the end and returns the position of the last match. Handy for extracting file extensions or the text after a final delimiter.
  8. Consider Like for pattern matching. If you need wildcards, use If text Like "*home*" Then. The asterisk matches any sequence of characters; the question mark matches a single character. Like is case-sensitive by default unless Option Compare Text is set.
  9. Run and debug. Press F5 to run, or F8 to step through line by line. Use Debug.Print to send results to the Immediate Window (View > Immediate Window).

Common Mistakes

  • Comparing InStr to 1 instead of > 0. A match can start at any position, so = 1 only catches matches at the very beginning.
  • Forgetting case sensitivity. By default VBA compares strings binary (case-sensitive). "Home" will not match "home" unless you use vbTextCompare or Option Compare Text.
  • Using .Text instead of .Value. .Text returns what is displayed, which can be truncated or formatted (e.g., "###" for narrow columns).
  • Not handling empty cells. Passing an empty variant to InStr can raise a type mismatch; wrap with CStr() or test If Len(cell.Value) > 0 first.
  • Assuming InStr finds all occurrences. It returns only the first match from the start position. To find every match, loop with an incrementing start position.
  • Mixing up InStr argument order. The signature is InStr([start], string1, string2, [compare]) — the text to search comes before the text to find.

Tips

  • Use a helper function to keep your code readable:
    Function Contains(txt As String, find As String) As Boolean
        Contains = (InStr(1, txt, find, vbTextCompare) > 0)
    End Function
    Then write If Contains(Range("A1").Value, "error") Then.
  • For multiple keywords, loop through an array of terms and exit early once one matches.
  • Remember that InStr returns a Variant (or Null if either string is Null); assign to a Long and test with > 0.
  • Use vbBinaryCompare when case matters, such as matching product codes.
  • Keep Option Explicit at the top of every module to catch undeclared variables early.
  • Test with edge cases: empty strings, strings that are only the substring, and substrings at the very start or end.

Troubleshooting

If your code compiles but never finds a match, first check case: add vbTextCompare and retest. Next, verify you are reading the right property — use .Value and confirm the cell actually contains the text (watch for leading/trailing spaces; trim with Trim()). If you get a "Type mismatch" error, one of the arguments is not a string; wrap cell values in CStr() and guard against empty cells. If nothing runs at all, check that macros are enabled and the file is saved as .xlsm. If the Immediate Window shows nothing, make sure you are using Debug.Print and that the Immediate Window is visible. For unexpected results with Like, remember that Like is case-sensitive unless Option Compare Text is set, and that special characters like [, ], *, and ? have meaning in patterns — escape them with brackets if you need literal matches.

Frequently Asked Questions

Is there a built-in "Contains" function in VBA?

No. VBA has no Contains method for strings. Use InStr (or Like for wildcards) and compare the result to zero.

How do I make InStr case-insensitive?

Pass vbTextCompare as the fourth argument, or place Option Compare Text at the top of the module. The latter affects all string comparisons in that module.

What is the difference between InStr and InStrRev?

InStr searches from the start (or a given start position) forward and returns the first match. InStrRev searches backward and returns the position of the last match.

Can I check if a string contains any of several words?

Yes. Loop through an array of words and call InStr for each, exiting the loop as soon as one returns greater than zero.

Why does InStr return 0 even though the text is there?

Most often it is a case mismatch, a leading or trailing space, or you are reading .Text instead of .Value. Trim the string and use vbTextCompare to rule these out.

Does InStr work with numbers?

It expects strings. Convert numbers with CStr() first, or concatenate them into a string, otherwise you may get a type mismatch.