Home » excel » excel – Can I use an array to compare multiple criteria using the like operator?

excel – Can I use an array to compare multiple criteria using the like operator?

Posted by: admin May 14, 2020 Leave a comment

Questions:

Can I use Array to compare multiple criteria using Like statement

Example:

LCase(Cells(lig, 2)) Like Array("object**", "**cash**", "lobby**")
How to&Answers:

Or you can use following syntax with Or

(LCase(Cells(lig, 2)) Like "object**") Or (LCase(Cells(lig, 2)) Like "**cash**") Or (LCase(Cells(lig, 2)) Like "lobby**")  

And so on

Answer:

No you cannot. You must loop through the array and check each item of the array individually.

Dim Criteria() As Variant
Criteria = Array("object**", "**cash**", "lobby**")

Dim Criterion As Variant
For Each Criterion In Criteria
    If LCase(Cells(lig, 2)) Like Criterion Then 
        '...
    End If 
Next Criterion

Answer:

No, you will have to loop through the array in order to compare multiple values.

For a one-dimensional array, try the following

Dim arr As Variant
arr = Array("object*", "*cash*", "lobby*")
For i = LBound(arr) To UBound(arr)
    If LCase(Cells(lig, 2)) Like arr(i) Then
        'Do something
    End If
Next i

Furthermore, you are using Cells without specifying a workbook/worksheet. In this case, VBA always refers to the active wb & ws, which may not be as you wish.