Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA: Check if String is in String Array

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To check if a string exists within a string array in Excel VBA, you must iterate through the array using a loop and compare each element to your target string, or use a helper function like Filter. Because VBA does not have a built-in "contains" or "exists" method for arrays (unlike Python or JavaScript), a For Each loop is the most reliable and standard way to achieve this result.

What You'll Need

  • Microsoft Excel installed on Windows.
  • The Developer tab enabled in the Excel Ribbon.
  • Basic familiarity with the Visual Basic Editor (VBE).
  • An existing dataset or a defined list of strings to search through.

Step-by-Step

  1. Open the Visual Basic Editor: Press Alt + F11 on your keyboard to launch the VBE. This is the environment where all VBA macros are written and managed.
  2. Insert a New Module: In the top menu, go to Insert > Module. This creates a blank space where you can write your custom functions and subroutines, ensuring they are accessible throughout your workbook.
  3. Declare Your Variables: At the start of your procedure, define the variables you will use. You will need a variable for the array (Dim myArray() As String), a variable for the string you are searching for (Dim searchString As String), and a boolean variable to track if the item was found (Dim isFound As Boolean).
  4. Initialize the Array: You can populate your array manually using the Array() function or by assigning values to specific indices. For example: myArray = Array("Apple", "Banana", "Cherry"). Note that if you use the Array() function, your array variable must be declared as a Variant rather than a String() array.
  5. Implement the For Each Loop: Create a loop that examines every single item in the array. Use the syntax For Each item In myArray. This approach is generally cleaner than using a numeric counter (For i = LBound(myArray) To UBound(myArray)) because it handles the array boundaries automatically regardless of whether the array is 0-based or 1-based.
  6. Perform the String Comparison: Inside the loop, use an If statement to compare the current item with your searchString. For a strict match, use If item = searchString Then. If you want the search to be case-insensitive (so that "apple" matches "Apple"), use If LCase(item) = LCase(searchString) Then.
  7. Set the Found Flag and Exit: Once a match is found, set your boolean variable isFound = True. Immediately follow this with an Exit For statement. This is a critical performance step; once you find the match, there is no need to check the remaining elements of the array.
  8. Handle the Result: After the loop ends, use another If statement to check the value of isFound. You can then trigger a message box, update a cell value, or execute another piece of code based on whether the string was located.
  9. Test the Code: Press F5 or click the Run button to execute the macro. Try searching for a string that exists in the array and one that does not to verify the logic works in both scenarios.

Common Mistakes

One of the most frequent errors is the Type Mismatch error. This often happens when a developer declares a variable as Dim myArray() As String but then tries to assign it using myArray = Array("A", "B"). The Array() function in VBA returns a Variant containing an array, not a typed String array. To fix this, declare the array as Dim myArray As Variant.

Another common mistake is ignoring Case Sensitivity. By default, VBA string comparisons are case-sensitive. If your array contains "New York" and you search for "new york", the = operator will return False. Developers often forget to use LCase() or UCase() on both sides of the comparison to ensure a match regardless of capitalization.

Many users also forget the Exit For command. While the code will still function without it, the loop will continue to run through every single element even after the target string has been found. In a small array of ten items, this is negligible, but in an array of 10,000 items, it can cause a noticeable lag in the application's performance.

Lastly, there is the issue of Leading and Trailing Spaces. If your array is populated from a spreadsheet, cells often contain accidental spaces (e.g., "Apple "). A standard comparison will fail because "Apple " is not the same as "Apple". Using the Trim() function during the comparison is essential for cleaning data on the fly.

Tips

For those looking for a more concise way to check for a string without writing a full loop every time, consider creating a Custom User Defined Function (UDF). By writing a function called ExistsInArray(arr As Variant, str As String) As Boolean, you can reuse this logic across multiple macros or even call it directly from an Excel worksheet formula.

If you are dealing with very large datasets where performance is critical, consider using a Collection or a Dictionary object (from the Microsoft Scripting Runtime library) instead of a standard array. Dictionaries allow for "Key" lookups, which are nearly instantaneous regardless of the size of the list, eliminating the need for a loop entirely.

To make your search more flexible, you can use the Like operator instead of the equals sign. For example, If item Like "*" & searchString & "*" Then will return True if the search string is found anywhere inside the array element, rather than requiring an exact match. This is useful for partial matches or keyword searches.

If you prefer a one-liner approach for simple checks, the Filter function can be used. Filter(myArray, searchString) returns a new array containing only the elements that match the search string. If the resulting array's upper bound is greater than or equal to its lower bound, the string exists. However, be cautious: Filter performs a partial match search, which may lead to false positives (e.g., searching for "Cat" will find "Category").

Troubleshooting

If your code is running but always returning False even when you know the string is present, the first thing to check is hidden characters. Use a temporary Debug.Print "[" & item & "]" inside your loop to see if there are hidden spaces or non-printing characters surrounding your strings. If you see [Apple ] instead of [Apple], wrap your comparison in Trim().

If you encounter a Subscript out of range error, it usually means you are trying to access an index of the array that doesn't exist. This typically happens when using a For i = 0 To ... loop on an array that starts at index 1. Always use LBound(myArray) and UBound(myArray) to define your loop boundaries to ensure compatibility with all array types.

If the VBE tells you that Variable not defined, you likely have Option Explicit turned on at the top of your module. This is actually a good thing, as it forces you to declare all variables. Check the spelling of your variables and ensure every single one has a corresponding Dim statement.

If your macro is freezing Excel when processing a very large array, try adding Application.ScreenUpdating = False at the start and Application.ScreenUpdating = True at the end. While this doesn't speed up the loop itself, it prevents Excel from trying to refresh the UI during the process, which can save significant time.

Frequently Asked Questions

Can I check for a string in an array without using a loop?

Yes, you can use the Filter function, but it performs a partial match. For a precise, exact match without a manual loop, you would need to use a Scripting.Dictionary object, which allows you to check for the existence of a key using the .Exists method.

Does the order of elements in the array matter?

No, the order does not matter when searching for a string. The loop checks every element sequentially from the first to the last, so the item will be found regardless of its position.

How do I handle case-insensitive searches?

The most reliable way is to convert both the array element and the search string to lowercase using the LCase() function during the comparison: If LCase(item) = LCase(searchString) Then.

What is the difference between a String array and a Variant array?

A String() array can only hold text and is more memory-efficient. A Variant array can hold any data type. In VBA, if you use the Array() function to create your list, you must use a Variant variable to store the result.

Will this work if my array is multi-dimensional?

No, a For Each loop works on one-dimensional arrays. For multi-dimensional arrays, you must use nested For...Next loops, one for each dimension, to iterate through every possible coordinate in the array.

How do I search for a string that is only part of an array element?

Use the InStr function or the Like operator. For example, If InStr(1, item, searchString, vbTextCompare) > 0 Then will return true if the search string is found anywhere within the element, ignoring case.