EXCEL VBA: Is it possible to use the Filter function in VBA to filter more than 1 search string?

Lai Kan Leon 596 Reputation points
2021-08-07T05:50:18.37+00:00

Hello,

I sometimes use the Filter function to filter a 1-dimensional array.

The syntax is:
Filter(sourcearray, match, [ include, [ compare ]])

The "match" argument is used to search the string we want.
It seems that we can only search ONE string, say "cat".

Is it possible to search more than one string, say "cat" and "dog"?
How can this be done? In Excel, we can use filters to do this. I wonder if we can do this in VBA.

I tried using a variable to represent "match", like this:

ElseIf opt_1 = True Then
Dim var As String
var = "cat"
vArray2 = Filter(vArray1, var, True, vbTextCompare)

It works fine!

But how can I add "dog" to var? (so that the filtered rows contain either "cat" or "dog")

Thanks
Leon

Developer technologies | Visual Basic for Applications

Locked Question. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

Answer accepted by question author
Viorel 127.3K Reputation points
2021-08-08T15:52:09.58+00:00

Try something like this:

Dim array1 As Variant
array1 = Array("... cats ...", " ...Dogs ...", " ...Cats and dogs ...", "another text")

Dim array2 As Variant
array2 = Array()
Dim t
For Each t In array1
    If InStr(1, t, "cats", vbTextCompare) > 0 Or InStr(1, t, "dogs", vbTextCompare) > 0 Then
        ReDim Preserve array2(UBound(array2) + 1)
        array2(UBound(array2)) = t
    End If
Next

It is also possible to exclude words like "ducats" or "hotdogs".

Was this answer helpful?

1 additional answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more