Tuesday, July 24, 2018

Autofilter: To filter with macro

Below is very basic macro to define filter on atable which has two columns. Name(Comuln A) and Dept(Column B). Function will filter all employees with dept = "Technology"

With ThisWorkbook.Worksheets(1)

'Step 1: Remove all filters from the sheet by setting AutoFilterMode property to false.

.AutoFilterMode = False

'Step 2: Optional Step. Select the table on which you want to apply filter.

R = .Range("A100").End(xlUp).Row
.Range("A1:D" & R).Select

'Step 3: Select the Headers

With .Range("A1:D1")

'Step 4: Define filter with .Autofilter

    .AutoFilter field:=2, Criteria1:="Technology"

End With
End With

Please note in step 4,
                     field : sequence of column in table.
                     criteria1: defined which value you want to filter. There can be multiple criterias.

Further example:
Lets say Column C in table contains employee grade and you want to get employees with grades >2 and <5:

 .AutoFilter field:=3, Criteria1:=">2", Criteria2:="<5"




No comments:

Post a Comment

Autofilter: To filter with macro

Below is very basic macro to define filter on atable which has two columns. Name(Comuln A) and Dept(Column B). Function will filter all emp...