Filter data using auto filter – VBA Excel

filter data vba excel

Objective

To apply and remove the filter on excel range using VBA Excel.

Apply Filter

Here we had 4 rows in the data in range A1:B4, where first is the header row. Column A contained ID and corresponding to each ID we had state codes. We are applying the filter on state code “FL”. In the below code we have applied the filter on column B.

Code

Sub AutoFilterMacro()

'Apply the filter on column B
Worksheets("Sheet1").Range("A1:B4").AutoFilter Field:=2, Criteria1:="FL", VisibleDropDown:=True

End Sub

 

filter data vba excel

 

We had applied the filter for state “FL”  on column B. Once we execute the code, filter will be applied in below shown manner.

 

filter data vba excel

 

Remove Filter

To remove the filter, we need to apply the below code.

 

Sub RemoveTheFilter()

'To remove the filter
Selection.AutoFilter

End Sub

 

Reference

https://docs.microsoft.com/en-us/office/vba/api/excel.range.autofilter

Post you may like

Import and Export VBA Excel Module for moving code