Excel VBA: Check If String Contains Substring
In this article
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
- 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.
- Write a basic InStr check. In the module, paste this code:
Run it with F5. The message box confirms the substring is found.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 SubInStrreturns 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. - Make the check case-insensitive. By default,
InStris case-sensitive ("World" ≠ "world"). Add the fourth argumentvbTextCompare:
This treats uppercase and lowercase as equal. Alternatively, useIf InStr(1, text, substring, vbTextCompare) > 0 ThenLCaseon both strings:If InStr(1, LCase(text), LCase(substring)) > 0 Then. Both work;vbTextCompareis cleaner. - Use the Like operator with wildcards. For a more readable check, try:
This is case-insensitive by default (unlessIf text Like "*" & substring & "*" ThenOption Compare Binaryis set). Note thatLiketreats certain characters (?, *, #, [ ]) as wildcards, so if your substring contains them, escape them with brackets (e.g.,[*]). - Loop through a range of cells. To check many cells, use a For Each loop:
This highlights cells containing "target" (case-insensitive). Adjust the range and substring as needed.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 - Return a Boolean function. Wrap the logic in a reusable function:
Call it from other macros: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 FunctionIf ContainsSubstring("Hello", "ell") Then ... - Test edge cases. Check empty strings, substrings longer than the text, and special characters.
InStrhandles these gracefully: empty substring returns 1 (found at start), empty text returns 0 unless substring is also empty. Always guard againstNullvalues from database fields or empty cells by usingNz-like logic or checkingIsNull.
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.
InStris case-sensitive by default. Many expect it to match "Hello" and "hello" — usevbTextCompareorLCase. - Using
InStrwithNull. IftextisNull,InStrreturnsNull, andNull > 0isNull(not False), causing runtime error 94. Check forNullfirst:If Not IsNull(text) Then .... - Misusing
Likewildcards. 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 Textmakes all string comparisons case-insensitive, affectingInStrandLike. Be aware of this setting if results seem inconsistent.
Tips
- Use
InStrRevto 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
InStrwithMid,Left, orReplacefor 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.