Excel VBA String Contains Value: Step-by-Step Guide
In this article
To check if a string contains a value in Excel VBA, use the InStr function: If InStr(1, text, searchValue, vbTextCompare) > 0 Then. This returns a number greater than zero when the value is found, so you can branch your code on the result. The steps below show how to set this up, handle case sensitivity, and avoid the usual pitfalls.
What You'll Need
- Microsoft Excel with the Developer tab enabled (File > Options > Customize Ribbon > check Developer).
- A workbook saved as .xlsm if you want to keep macros.
- Basic familiarity with opening the VBA editor (Alt+F11) and inserting a module.
Step-by-Step
- Open the VBA editor. Press Alt+F11 in Excel. The Visual Basic Editor opens in a separate window. Menu labels can differ slightly by Excel version and region, but the core layout is the same.
- Insert a module. In the editor, go to Insert > Module. A blank code window appears where you can write your macro.
- Write a basic InStr test. Paste this into the module:
The first argumentSub CheckContains() Dim text As String Dim searchValue As String text = "Excel VBA string contains value" searchValue = "VBA" If InStr(1, text, searchValue, vbTextCompare) > 0 Then MsgBox "Found" Else MsgBox "Not found" End If End Sub1sets the start position.vbTextComparemakes the search case-insensitive. - Run the macro. Press F5 or go to Run > Run Sub/UserForm. A message box confirms whether the value was found. Change
searchValueto test other strings. - Make it case-sensitive if needed. Replace
vbTextComparewithvbBinaryCompare. Now "VBA" and "vba" are treated differently. Use this when case matters, such as matching product codes. - Check against cell values. To test a cell, assign the cell's text to a variable:
This works for any cell reference.Dim cellText As String cellText = Range("A1").Value If InStr(1, cellText, "target", vbTextCompare) > 0 Then ' do something End If - Use InStrRev for the last occurrence. If you need the position of the last match, use
InStrRev(text, searchValue). It returns 0 when not found, just like InStr. - Consider the Like operator for pattern matching. For wildcards, use
If text Like "*value*" Then. The asterisks match any characters before and after. This is handy for simple contains checks without calling a function.
Common Mistakes
- Forgetting the start argument. InStr requires a start position as its first argument. Omitting it causes a compile error. Always pass 1 to search from the beginning.
- Mixing up InStr arguments. The order is
InStr(start, string1, string2, compare). Swapping string1 and string2 gives wrong results or errors. - Assuming case-insensitivity. Without
vbTextCompare, InStr is case-sensitive by default. If your search fails unexpectedly, check the compare argument. - Using InStr with empty strings. If the search value is an empty string, InStr returns the start position (1), which may be misinterpreted as a match. Guard against empty search values.
- Ignoring errors from non-text cells. Assigning a cell containing an error value to a String variable raises a type mismatch. Check for errors or use
CStrcarefully.
Tips
- Store the result in a Long variable to inspect the exact position, not just a Boolean.
- Use
vbTextComparefor user-facing searches where case should not matter, andvbBinaryComparefor exact code matching. - For multiple search terms, loop through an array and call InStr for each term.
- Combine InStr with
Lento extract substrings around the match. - Test with edge cases: empty strings, very long strings, and strings with special characters.
Troubleshooting
If your macro does not find a value that you can see in the cell, first check for leading or trailing spaces. Use Trim(cellText) before searching. Next, confirm the compare argument: if you used vbBinaryCompare, case differences will cause a miss. Also verify the cell reference points to the intended sheet; unqualified Range calls use the active sheet, which may not be the one you expect. If you get a compile error, check that InStr is spelled correctly and that all arguments are separated by commas. For runtime errors, step through the code with F8 to see the actual variable values. If the search value comes from a cell, ensure it is not empty and does not contain hidden characters. Finally, remember that InStr returns a Variant; comparing it directly to True or False can behave unexpectedly, so always compare to 0 or use > 0.
Frequently Asked Questions
How do I check if a string contains a value in VBA?
Use InStr(1, text, searchValue, vbTextCompare) > 0. This returns True when the value appears anywhere in the string.
Is InStr case-sensitive?
By default, InStr uses binary comparison, which is case-sensitive. Pass vbTextCompare as the fourth argument to make it case-insensitive.
Can I use wildcards with InStr?
No, InStr does not support wildcards. Use the Like operator with asterisks for simple pattern matching, or use regular expressions via the VBScript.RegExp object for advanced patterns.
What does InStr return when the value is not found?
It returns 0. When found, it returns the position of the first character of the match.
How do I find the last occurrence of a value?
Use InStrRev(text, searchValue). It searches from the end and returns the position of the last match, or 0 if not found.
Why does my InStr check fail for a cell value?
Common causes are extra spaces, case differences, or the cell containing an error. Trim the text and confirm the compare argument. Also ensure you are referencing the correct sheet.