Smart Systems for Home

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

Excel VBA: Check If String Contains Substring

· 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

You can check whether a string contains a substring in Excel VBA using the InStr function, which returns the position of the first occurrence or 0 if not found. The shortest working pattern is If InStr(1, text, substring) > 0 Then — this is the most reliable and case-sensitive by default. For case-insensitive checks, use InStr(1, text, substring, vbTextCompare) or convert both strings with LCase. Alternatively, the Like operator with wildcards (*substring*) offers a more readable but slightly less flexible option. This guide shows you how to implement each method, avoid common pitfalls, and troubleshoot when results don't match expectations.

What You'll Need

  • Excel with macros enabled (any desktop version).
  • Basic familiarity with the VBA editor (press Alt+F11 to open it).
  • A worksheet with sample text in column A (or use the examples below).

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or Fn+Alt+F11 (Mac). In the Project Explorer, right-click your workbook and choose Insert > Module.
  2. Write a basic InStr check. In the module, paste this code:
    Sub CheckContains()
        Dim text As String
        Dim substring As String
        text = "Hello world"
        substring = "world"
        If InStr(1, text, substring) > 0 Then
            MsgBox "Contains substring"
        Else
            MsgBox "Does not contain substring"
        End If
    End Sub
    Run it with F5. The message box confirms the substring is found. InStr returns the starting position (6 in this case) or 0 if not found. The first argument (1) is the start position; you can change it to skip characters.
  3. Make the check case-insensitive. By default, InStr is case-sensitive ("World" ≠ "world"). Add the fourth argument vbTextCompare:
    If InStr(1, text, substring, vbTextCompare) > 0 Then
    This treats uppercase and lowercase as equal. Alternatively, use LCase on both strings: If InStr(1, LCase(text), LCase(substring)) > 0 Then. Both work; vbTextCompare is cleaner.
  4. Use the Like operator with wildcards. For a more readable check, try:
    If text Like "*" & substring & "*" Then
    This is case-insensitive by default (unless Option Compare Binary is set). Note that Like treats certain characters (?, *, #, [ ]) as wildcards, so if your substring contains them, escape them with brackets (e.g., [*]).
  5. Loop through a range of cells. To check many cells, use a For Each loop:
    Dim cell As Range
    For Each cell In Range("A1:A10")
        If InStr(1, cell.Value, "target", vbTextCompare) > 0 Then
            cell.Interior.Color = vbYellow
        End If
    Next cell
    This highlights cells containing "target" (case-insensitive). Adjust the range and substring as needed.
  6. Return a Boolean function. Wrap the logic in a reusable function:
    Function ContainsSubstring(text As String, substring As String, Optional caseSensitive As Boolean = False) As Boolean
        If caseSensitive Then
            ContainsSubstring = InStr(1, text, substring, vbBinaryCompare) > 0
        Else
            ContainsSubstring = InStr(1, text, substring, vbTextCompare) > 0
        End If
    End Function
    Call it from other macros: If ContainsSubstring("Hello", "ell") Then ...
  7. Test edge cases. Check empty strings, substrings longer than the text, and special characters. InStr handles these gracefully: empty substring returns 1 (found at start), empty text returns 0 unless substring is also empty. Always guard against Null values from database fields or empty cells by using Nz-like logic or checking IsNull.

Common Mistakes

  • Forgetting the start argument. InStr(text, substring) without the first argument defaults to start=1, but omitting it can cause confusion when copying code. Always include the 1 for clarity.
  • Assuming case-insensitivity. InStr is case-sensitive by default. Many expect it to match "Hello" and "hello" — use vbTextCompare or LCase.
  • Using InStr with Null. If text is Null, InStr returns Null, and Null > 0 is Null (not False), causing runtime error 94. Check for Null first: If Not IsNull(text) Then ....
  • Misusing Like wildcards. Characters like ? and * in the substring act as wildcards. If you need literal matching, escape them with brackets: [*] for asterisk.
  • Ignoring Option Compare. At module level, Option Compare Text makes all string comparisons case-insensitive, affecting InStr and Like. Be aware of this setting if results seem inconsistent.

Tips

  • Use InStrRev to find the last occurrence of a substring (search from the end).
  • For performance with large datasets, read ranges into arrays and loop arrays instead of cell-by-cell.
  • Combine InStr with Mid, Left, or Replace for advanced text manipulation.
  • When checking multiple substrings, consider using a helper function that loops through an array of substrings and returns True if any match.
  • Always test with realistic data, including empty cells, numbers stored as text, and special characters.

Troubleshooting

If your check always returns False, verify the substring spelling and case. Use vbTextCompare if case should be ignored. If you get runtime error 94 (Invalid use of Null), add a Null check. If Like gives unexpected results, check for wildcard characters in your substring and escape them. If results differ between macros, check the module's Option Compare setting. For large ranges, ensure you're not hitting Excel's memory limits — process in chunks. If the code runs but doesn't highlight cells, confirm the range reference is correct and the worksheet is active. Finally, if nothing works, step through the code with F8 to inspect variable values at each stage.

Frequently Asked Questions

How do I check if a string contains a substring in VBA?

Use InStr(1, text, substring) > 0. For case-insensitive, add vbTextCompare as the fourth argument.

Is InStr case-sensitive?

Yes, by default it is case-sensitive. Use vbTextCompare or convert both strings with LCase to ignore case.

Can I use wildcards with InStr?

No, InStr does not support wildcards. Use the Like operator with * and ? for pattern matching.

What if the substring is not found?

InStr returns 0. Check If InStr(...) = 0 Then to handle the not-found case.

How do I find the position of a substring?

InStr returns the starting position (1-based). For example, InStr(1, "Hello", "ll") returns 3.

Can I check multiple substrings at once?

Not directly. Loop through an array of substrings and call InStr for each, or use a regular expression (RegExp object) for complex patterns.