Excel VBA String Contains: A How-To Guide
In this article
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
- 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.
- 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.
- Write a basic InStr test. Paste this into the module:
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.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 - Make it case-insensitive. Add
vbTextCompareas the fourth argument:InStr(1, text, find, vbTextCompare). Alternatively, putOption Compare Textat the very top of the module (before any procedures). WithOption Compare Text, all string comparisons in that module ignore case. - Test against a cell. Replace the hard-coded text with a cell reference:
UseIf InStr(1, Range("A1").Value, "error", vbTextCompare) > 0 Then MsgBox "Cell A1 mentions error" End If.Value(not.Text) to get the underlying value rather than the displayed formatting. - 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 rCStrguards against empty cells and errors. - 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. - 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.Likeis case-sensitive by default unlessOption Compare Textis set. - 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
= 1only 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
vbTextCompareorOption Compare Text. - Using
.Textinstead of.Value..Textreturns 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 testIf Len(cell.Value) > 0first. - 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:
Then writeFunction Contains(txt As String, find As String) As Boolean Contains = (InStr(1, txt, find, vbTextCompare) > 0) End FunctionIf 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
vbBinaryComparewhen case matters, such as matching product codes. - Keep
Option Explicitat 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.