Excel VBA Wildcard String Search: A Complete Guide
In this article
To perform a wildcard string search in Excel VBA, use the Like operator combined with standard wildcard characters: the asterisk (*) for any number of characters and the question mark (?) for a single character. For example, the expression If myString Like "*search*" Then will return True if the word "search" appears anywhere within the variable myString.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- The Developer tab enabled in the Excel Ribbon (found via File > Options > Customize Ribbon).
- A basic understanding of how to open the Visual Basic Editor (ALT + F11).
- A dataset in an Excel worksheet to test your search logic.
Step-by-Step
- Open the Visual Basic Editor: Press
ALT + F11on your keyboard to launch the VBA environment. If you are on a Mac, the shortcut may vary, or you can click the Visual Basic button on the Developer tab. - Insert a New Module: In the Project Explorer window on the left, right-click on your workbook name, select
Insert, and then clickModule. This provides a clean slate to write your search procedure. - Declare Your Variables: Start your subroutine by defining the variables you will use. You need a variable for the string you are checking and a variable for the pattern you are searching for.
Dim cellValue As StringDim searchPattern As String - Define Your Wildcard Pattern: Assign a value to your search pattern using wildcards.
- Use
"*text*"to find a string that contains "text" anywhere. - Use
"text*"to find a string that starts with "text". - Use
"*text"to find a string that ends with "text". - Use
"t?xt"to find a four-letter word starting with 't' and ending in 'xt' (e.g., "text" or "tost").
- Use
- Implement the Like Operator: Use an
If...Thenstatement to compare the cell value against the pattern. TheLikeoperator is the engine of the wildcard search in VBA.If cellValue Like searchPattern Then' Action to take if a match is foundEnd If - Create a Loop for Range Searching: To search an entire column rather than a single cell, wrap your logic in a
For Eachloop.Dim cell As RangeFor Each cell In Range("A1:A100")If cell.Value Like "*Apple*" Thencell.Interior.Color = vbYellowEnd IfNext cell - Run and Test: Press
F5or click the Play button in the toolbar to execute the code. Check your worksheet to ensure the correct cells were identified.
Common Mistakes
One of the most frequent errors is forgetting that the Like operator is case-sensitive by default. If you search for "*Apple*", VBA will not find "apple" or "APPLE". This often leads users to believe their code is broken when it is actually functioning exactly as programmed. To fix this, you must either convert both strings to uppercase using UCase() or place Option Compare Text at the very top of your module to make all string comparisons in that module case-insensitive.
Another common mistake is the misuse of the question mark wildcard. Beginners often use ? when they actually mean *. Remember that ? represents exactly one character. If you search for "A?C", it will match "ABC" or "A1C", but it will not match "ABBC".
Users also frequently forget to handle empty cells. If your loop encounters a cell with an error value (like #N/A or #VALUE!), the Like operator will trigger a Type Mismatch error (Error 13). Always ensure you are checking if the cell contains a string or using CStr(cell.Value) to force the value into a string format before comparison.
Tips
For more advanced searches, utilize the bracket notation [ ]. This allows you to search for any single character within a specific set. For example, "[A-Z]*" will find any string that starts with an uppercase letter. "[aeiou]*" will find any string starting with a vowel. This provides a level of precision that the asterisk cannot offer.
If you are searching through thousands of rows, looping through cells one by one can be slow. To optimize performance, load your range into a VBA Array first. Processing data in memory is significantly faster than interacting with the Excel worksheet interface for every single cell check. Once the array is processed, you can write the results back to the sheet in one bulk operation.
Combine your wildcard search with the Instr function if you need to know the exact position of the string. While Like tells you if a pattern exists, Instr tells you where it starts. Using both allows you to validate a pattern and then perform a precise string manipulation, such as extracting text after the match.
Troubleshooting
If your code is running but not finding any matches, first check your case sensitivity. Try adding Option Compare Text to the top of your module. If that doesn't work, print your variables to the Immediate Window (Ctrl + G) using Debug.Print cellValue to see exactly what VBA is seeing. Hidden spaces or non-printing characters in your cells can cause a match to fail even if the text looks correct. Use the Trim() function to remove leading and trailing spaces: If Trim(cellValue) Like searchPattern Then.
If you encounter a "Type Mismatch" error, it is likely because your range contains numbers or errors. The Like operator requires string operands. Wrap your cell reference in the CStr() function, like this: If CStr(cell.Value) Like "*123*" Then. This converts numeric values to strings so the comparison can proceed without crashing.
If the VBA editor freezes or Excel becomes unresponsive, you are likely stuck in an infinite loop or processing too much data. Press Ctrl + Break or Esc to force the code to stop. To prevent this in the future, ensure your loop has a clear end point and consider adding Application.ScreenUpdating = False at the start of your code to reduce the graphical overhead of updating the screen during the search.
Frequently Asked Questions
Can I use regular expressions instead of the Like operator?
Yes. While Like is simpler for basic wildcards, you can enable the Microsoft VBScript Regular Expressions 5.5 library in Tools > References. This allows you to use the RegExp object for complex pattern matching, such as validating email addresses or phone numbers.
Is there a difference between * and ? in VBA?
Yes. The asterisk (*) represents zero or more characters of any kind. The question mark (?) represents exactly one single character. For example, "b?t" matches "bat" or "bit", but not "boat".
How do I search for a literal asterisk or question mark?
To search for a character that is normally a wildcard, wrap it in square brackets. To find a literal asterisk, use "[*]". To find a literal question mark, use "[?]". This tells VBA to treat the symbol as a character rather than a command.
Does the Like operator work with arrays?
The Like operator works on individual strings. To search an array, you must loop through the array elements and apply the Like operator to each element individually within the loop.
Can I use wildcards in the Excel Find and Replace dialog via VBA?
Yes, the Range.Find method supports wildcards (* and ?) natively. This is often faster than a For Each loop because it uses Excel's built-in search engine rather than iterating through every cell in VBA.