Search code examples
vbaexcelautofilteradvanced-filter

Excel : filter with Multiple Criteria : AutoFilter or AdvancedFilter


I am trying to create a filter that will do the below

Begins with "4" or Contains "2TWH" or Contains "2TER"

I believe it will turn out to look like this

ActiveSheet.Range("$A$5:$H$10").AutoFilter Field:=2, Criteria1:="=4*", _
    Operator:=xlOr, Criteria2:="=*2TWH*" 

but I need to somehow also have a criteria 3 for ="=2TER"

I did some googling and saw that you can store the values into an array and then call the array values but I was unable to get them into the array in a usable fashion.

Is anyone able to offer some assistance with this please?


Solution

  • This should do the trick :

    ActiveSheet.Range("$A$5:$H$10").AutoFilter Field:=2, Criteria1:="=4*", _
        Operator:=xlOr, Criteria2:=Array("*2TWH*","*2TER*")
    

    This doesn't throw any error, but ...
    it'll only take 2 criteria because there are wildcards (*).
    Here it's the last criteria from the array (here *2TER*)


    Ideally, this would have been nice, as it works for constants,
    but because you use WildCards (*) it only supports 2 criteria... :/

    ActiveSheet.Range("$A$1:$H$10").AutoFilter Field:=2, Criteria1:=Array("*2TWH*", "*2TER*", "4*"), _
        Operator:=xlFilterValues
    


    So you'll have to go with AdvancedFilter :

    With ActiveSheet
        'Const xlFilterInPlace = 1
        .Range("$A$5:$H$10").AdvancedFilter _
                            Action:=xlFilterInPlace, _
                            CriteriaRange:=WsFilterSettings.Range("A1:A4")
    End With 'ActiveSheet
    

    AdvancedFilter take a Range as criteria inputs, CriteriaRange, so you'll have to put on a sheet :

    • the header of the column you want to apply to the filter on
    • your criteria below the respective header (if you have multiples columns)

    Each COLUMN of that Range, are linked by an AND
    Each ROW of that Range, are linked by an OR
    So build your table carefully!

    In the above example code, I have used :
    (let's say that your column's header was Column To Filter On) :

    A1 | Column To Filter On
    A2 | 4*
    A3 | *2TWH*
    A4 | *2TER*