You cannot use the word DoesNotContain directly in Excel VBA; the correct method is InStr (In String). This function returns the position of a substring within a string, allowing you to check if a specific value exists inside another string without raising an error. To fix a script that says it does not contain, simply replace the non-existent method with InStr(1, StringToSearch, StringToFind) > 0 or use the Like operator with wildcards.
What You'll Need
- A computer running Microsoft Excel (2010 or later is recommended for the best VBA experience).
- A spreadsheet containing the data you wish to process.
- The Microsoft Visual Basic for Applications (VBA) editor, accessible via the Developer tab or by pressing Alt + F11.
- Basic understanding of variables (String, Integer) and loops (For/Next).
Step-by-Step
- Open the VBA Editor. In Excel, navigate to the Developer tab on the ribbon and click the "Visual Basic" button. Alternatively, press Alt + F11 on your keyboard to open the editor window directly.
- Insert a New Module. In the left-hand Project Explorer pane, right-click on the workbook name (e.g., VBAProject (Book1)), hover over "Insert," and select "Module." This creates a blank code window where you will write your script.
- Define the Function. Clear any existing text in the module and start by declaring your variables. For example, to check if a cell contains a specific word, you would write:
This sets up a function that takes a source string and a search term and returns a Boolean (True/False).Function CheckStringContains(Source As String, SearchTerm As String) As Boolean ' Your logic goes here End Function - Implement the
InStrCheck. The core of the solution is theInStrfunction.InStrsearches for the first occurrence ofSearchTermwithinSource. If it finds the term, it returns the numerical position; if not, it returns 0. Add the following line inside your function:
This line translates to: "Is the position of the search term in the source string greater than 0?" If the result is greater than 0, the function returns True.CheckStringContains = InStr(1, Source, SearchTerm) > 0 - Test the Function with a Sub. Functions do not run on their own; they need a Sub (Subroutine) to trigger them. Below your function, paste the following code:
This script loops through cells in Column A, checks if they contain the word "Error," and highlights them if they do.Sub TestContains() Dim ws As Worksheet Dim targetRange As Range Dim cell As Range Dim searchTerm As String ' Set the worksheet and range Set ws = ThisWorkbook.Sheets("Sheet1") Set targetRange = ws.Range("A1:A10") searchTerm = "Error" ' Loop through each cell in the range For Each cell In targetRange ' Call your function If CheckStringContains(cell.Value, searchTerm) Then cell.Interior.Color = RGB(255, 200, 200) ' Highlight in light red cell.Offset(0, 1).Value = "Found: " & searchTerm End If Next cell End Sub - Run the Macro. Return to your Excel sheet. Press Alt + F11 to ensure the VBA editor is visible, or use the Macros button on the Developer tab. Select
TestContainsfrom the list and click "Run." You should see the cells containing "Error" highlighted, and the adjacent column populated with the text "Found: Error." - Alternative: Using the
LikeOperator. If you need more complex pattern matching (e.g., checking if a string starts with a letter), you can use theLikeoperator. Modify your function as follows:
To use this, pass patterns like "A*" (starts with A) or "*data*" (contains data) as the second argument. This is often more readable thanFunction CheckLike(Source As String, Pattern As String) As Boolean CheckLike = Source Like Pattern End FunctionInStrfor general wildcard checks.
Common Mistakes
One of the most frequent errors beginners make is attempting to use a method name or property that does not exist in VBA, such as Range("A1").DoesNotContain("value"). VBA does not have a built-in property called DoesNotContain for strings, which will cause a Runtime Error 438 (Object doesn't support this property or method). Another mistake is forgetting that InStr is case-sensitive by default. If you search for "excel" in "Excel", the result will be 0 (not found) because of the capitalization. To make the search case-insensitive, use InStr(1, Source, SearchTerm, vbTextCompare).
Tips
When checking if a cell is empty or contains no data before running a string search, always include a check for the length of the string. Forgetting this can cause the script to crash if it attempts to search a null reference. Use If Len(Source) = 0 Then Exit Function at the very top of your function. Additionally, when looping through large ranges, it is good practice to turn off screen updating (Application.ScreenUpdating = False) at the start of your Sub and turn it back on (Application.ScreenUpdating = True) at the end. This prevents the screen from flickering and significantly speeds up the execution of your macro.
Troubleshooting
If your script returns False when you are certain the text is there, check the data types. If you are comparing a numeric value stored in a cell with a string, the comparison will fail. Ensure you are converting the cell value to a string using CStr(cell.Value) before passing it to your InStr function. If you encounter a Compile Error saying "Procedure declaration does not match description of event or procedure having the same name," check the number of arguments passed to your function. Ensure that the number of arguments in the function definition matches exactly the number of arguments being passed in the calling Sub.
Frequently Asked Questions
How do I check if a cell contains any number or special character?
Use the Like operator with wildcards. For example, source Like "*[0-9]*" will return True if the string contains at least one digit.
Why does InStr return 0 even if the word is present?
This is usually due to case sensitivity. By default, VBA is case-sensitive. Use vbTextCompare as the fourth argument in InStr to make it case-insensitive.
Can I check if a string contains multiple words?
Yes. You can chain multiple InStr checks using logical operators like And. For example: InStr(1, text, "word1") > 0 And InStr(1, text, "word2") > 0.
How do I get the position of the found text?
If you want the actual index (1, 2, 3, etc.) where the text starts, you do not need the > 0 comparison. Simply store InStr(1, text, "search") in a variable. If it returns 0, the text was not found.
Is there a faster way to search an entire column?
For very large datasets, looping through every row can be slow. Consider using Excel's built-in Filter function on a range object or using the Find method for a single search, though these are more complex to implement in VBA than a simple loop.
What does the "1" in InStr(1, ...) mean?
The "1" is the starting position. It tells VBA to begin searching from the very first character of the string. You can change this to a higher number to start searching from a specific point within the text.