The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (2023)

bottom line:Learn how to create macros that apply filters to ranges and tables using the AutoFilter method in VBA. The post contains links to examples of filtering different types of data, including text, numbers, dates, colors, and symbols.

Skill Level:intermediary

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (1)

Download the file

The Excel file with the code can be downloaded below. This file contains code to filter various types of data and filter types.

VBA-AutoFilters-Guide.zipdiscard

Write macros for filters in Excel

Filters are a great tool for analyzing data in Excel. For most analysts and frequent Excel users, filters are part of everyday life. We'll use the filter dropdown menus to apply filters to individual columns in a dataset. It helps us link numbers to reports and examine our data.

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (2)

Filtering can also be a slow process. Especially when applying filters to multiple columns in large worksheets or filtering data to copy/paste later into other worksheets or workbooks.

This article explains how to create macros to automate the filtering process. that is aDetailed guide on AutoFilter method in VBA.

I also have articles with examples of different filters and data types, including:spaces,Text,counting,Deadline,, jfilter cleaning.

Macro recorder is your friend (and enemy)

We can easily get the VBA code for the filters by activating the macro recorder and applying one or more filters to a range/table.

(Video) How to Create Macro Buttons for Filters in Excel

Here are the steps to create a filter macro using the macro recorder:

  1. Turn on the macro recorder:
    1. Developer Tab > Record Macro.
    2. Give the macro a name, choose where you want to save the code and press OK.
  2. Apply one or more filters using the filter drop-down menus.
  3. Stop the recorder.
  4. Open the VB editor (Developer tab > Visual Basic) to view the code.

If you've used the macro recorder for this process before, you know how useful it can be. Especially as our filter criteria are becoming more complex.

The code looks like this.

SubFilters_Macro_Recorder()'' Macrofilter_Macro_Recorder''ActiveSheet.ListObjects("tblData").Range.AutoFilter Field:=4, Criteria1:= _"Produto 2"ActiveSheet.ListObjects("tblData").Range.AutoFilter Field:=4ActiveSheet.ListObjects("tblData").Range .Campo AutoFilter:=5, Criteria1:= _">=500", Operador:=xlAnd, Criteria2:="<=1000"Final Sub

We can see that each row uses the AutoFilter method to apply the filter to the column. It also contains information about the criteria for the filter.

this and whereit can get complex, confusing, and frustrating.It can be difficult to understand what the code means when trying to change it for a different scenario or dataset. So let's take a look at how the AutoFilter method works.

Explanation of the automatic filter method

The AutoFilter method is used to clean and apply filters to aa single columnon a range or table in VBA. It automates the process of applying filters through the filter dropdowns and does all that work for us. 🇧🇷

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (3)

Can be used to apply filtersmultiple columns writing multiple lines of code, one for each column. We can also use AutoFilter to applymultiple filter criteria in a single column, just as you would in the filter dropdown by checking multiple boxes or specifying a date range.

Write the auto filter code

Here are step by step instructions on how to write one line of code for AutoFilter

Step 1: Reference the range or table

The AutoFilter method is a member of the Range object. Therefore, we need to refer to a range or table to which the worksheet filters will be applied. This is the entire area to which the filters will be applied.

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (4)

The following examples enable/disable filters in the range B3:G1000 on the AutoFilter Tab sheet.

SubAutoFilter_Rank()'AutoFilter is a member of the Range object“Refers to the entire area to which the filters apply'AutoFilter enables/disables filters if no parameter is specified.Sheet1.Range("B3:G1000").AutoFilter'Workbook level fully qualified referenceThisWorkbook.Worksheets("Guia do AutoFilter").Range("B3:G1000").AutoFilterFinal Sub

Here's an example using Excel spreadsheets.

(Video) Excel FILTER Function Explained (7 Examples) | Filter and Extract Data Easily

Subtable_autofilter()'Autofilters for tables work the same way.DarkHelloAslist objectexcel table'Define variable ListObject(table).Foundlo = Sheet1.ObjectList(1)'AutoFilter is a member of the Range object'The parent of the Range object is the List objectlo.Range.AutoFilterFinal Sub

The AutoFilter method has 5 optional parameters, which we'll cover next.If we don't specify any of the parameters, as in the previous examples, the AutoFilter method activates/deactivates the filters for the referenced range.It toggles when filters are on, when they are off, and vice versa.

Rankings or Tables?

Filters work the same in bothControl strips and Excel worksheets.

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (5)

My preferred method is to use tables because we don't have to worry about changing range references as the table grows or shrinks. However, the code is the same for both objects. The rest of the code examples use Excel spreadsheets, but you can easily change this to normal ranges.

The 5 (or 6) autofilter parameters

The AutoFilter method has 5 (or 6) optional parameters that specify filter criteria for a column. Here is a list of parameters.

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (6)
NameMandatory/OptionalDescription
campoOptionalThe column number within the scope of the filter to which the filter is applied. This is the column number within the filter area, NOT the table column number.
Criterion 1OptionalA quoted string that specifies the filter criteria. Comparison operators can be added for less than or greater than filters. Depending on the column's data type, many rules apply. Check out the examples to continue.
OperatorOptionalSpecifies the type of filter for various data types and criteria using one of the XlAutoFilterOperator constants. Look at thisMSDN help page for a detailed listand list in the following macro examples.
criteria2OptionalIt is used in combination with the operator parameter and Criteria1 to create filters on multiple criteria or ranges. Also used for certain multi-item date filters.
Visible dropdown listOptionalShows or hides the filter dropdown button for a single column (field).
subfieldOptionalI'm not sure yet…

We can use a combination of these parameters to apply different filter criteria to different types of data. The first four are the most important, so let's see how to use them.

Step 2: The Field Parameter

The first parameter is the field. For the field parameter we provide a number which is the column number to which the filter will be applied.This is the column number inside the filter areathis is the parent of the AutoFilter method. NOT the column number in the worksheet.

In the example below, Field 4 is the Product column because it is the fourth column in the Scope/Filter table.

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (7)

Column filter will be cleared if we provide only Field parameter, and no other criteria.

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (8)

We can also use a variable for the Field parameter and set it dynamically. I will explain to you in more detailLow.

Step 3: The Criteria Parameters

There are two parameters that can be used to specify the criteria filter, criteria1 and criteria2. We use a combination of these parameters and the operator parameter for different filter types. This is where it gets tricky, so let's start with a simple example.

'Filter the product column by a single itemlo.Range.AutoFilter Field:=4, Criteria1:="Product 2"

This would be the same as selecting a single item from the list of checkboxes in the filter drop-down menu.

(Video) Auto Filter in Excel | Filtering Data in Excel | EXCEL AUTOFILTER | All features, Tips and Tricks

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (9)

General rules for Criterion 1 and Criterion 2

The values ​​we provide for Criteria1 and Criteria2 can be tricky. The following are some general guidelines for referencing criteria parameter values.

  • The criteria value is astring between blades🇧🇷 There are some exceptions where the date range criterion is constant and above or below average.
  • By specifying filters for individual numbers or dates thatThe number format must matchthe number format applied to the range/table.
  • Losthe greater/less than comparison operator, also enclosed in quotes, before the number.
  • Quotation marks are also used to match spaces "=" and non-spaces "<>".
The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (10)
"Filter by date greater than or equal to January 1, 2015lo.Range.AutoFilter Field:=1, Criteria1:=">=1/1/2015"' The comparison operator >= is enclosed in quotes' for parameter criterion1.' The date format in the code matches the format' applied to the worksheet cells.

Step 4: The operator parameter

What if we want to select multiple items from the filter drop-down list? Or create a filter for a range of dates or numbers?

For that, we need the operator. The operator parameter is used to specify what kind of filter we want to apply. This can vary depending on the type of data in the column. One of the following 11 constants must be used for the operator.

NamebravuraDescription
xlY1Include criterion 1 and criterion 2. Can be used for date or number ranges.
xlBottom10Items4Items displayed with the lowest value (number of items specified in criterion 1).
xlLower10 percent6Items with the lowest value are displayed (percentage specified in criterion 1).
xlFilterCellColor8cell fill color
xlDynamicFilterName11Dynamic filter used for above or below average periods and data
xlFiltroFuenteColor9Font color in the cell.
xl-Filtersymbol10Filter icon created by conditional formatting
xlFilterValues7Used for filters with multiple criteria specified with an array function.
xlO2Include criterion 1 or criterion 2. It can be used for date and number ranges.
xlTop10Artikel3Articles with the highest displayed value (number of articles specified in criterion 1).
xlTop10 percent5Items with the highest displayed value (percentage defined in Criterion 1).

Here is a link to the MSDN help page which contains the list of constants forXlAutoFilterOperator Enumeration.

Depending on the data type and filter type, the operator is used in combination with Criteria1 and/or Criteria2. Here are some examples.

'Filter for multi-item list, operator is xlFilterValueslo.Range.AutoFilter _Field:=iCol, _Criteria1:=Array("Product 4", "Product 5", "Product 6"), _Operator:=xlFilterValues
'Filter by date range (between dates), operator is xlAndlo.Range.AutoFilter _Field:=iCol, _Criteria1:=">=1.1.2014", _Operator:=xlAnd, _Criteria2:="<=31.12.2015"

That's the basics of writing a line of code for the AutoFilter method. It gets more complex with different types of data. Therefore, I have provided many examples below that include most criteria and operator combinations for different filter types.

The automatic filter is NOT additive

When a line of AutoFilter code is executed,first clears the filters applied to that column (field) and then applies the filter criteria specified in the line of code.

This means that it is NOT additive. The next 2 lines do NOT create a filter for product 1 and product 2. After running the macro, the product column only filters product 2.

'AutoFilter is NOT additive. Filters are applied first' in the column before applying the new filterlo.Range.AutoFilter Field:=4, Criteria1:="Product 3""This line of code filters only column Product 2'The above filter for product 3 will be cleared when this line is executed.lo.Range.AutoFilter Field:=4, Criteria1:="Product 2"

If you want to apply a multi-criteria filter to a single column, you can specify it using the criteria and operator parameters.

How to set field number dynamically

When adding/removing/moving columns in the filter pane, the field number for a filtered column may change. So I try not to hard-code a number into the field parameter.

Instead, we can use a variable and use some code to find the column number by name. Here are two examples of regular ranges and tables.

(Video) 3 Tips for Writing Formulas with VBA Macros in Excel

The Ultimate Guide to Excel Filters Using VBA Macros - AutoFilter Method - Excel Campus (11)
Subdynamic_field_number()'Techniques for locating and setting the field based on the column name.DarkHelloAslist objectDarkiColAs Largo'Set reference to the first table in the sheetFoundlo = Sheet1.ObjectList(1)'Define filter fieldiCol = lo.ListColumns("Product").Index'Use the match function for regular intervals'iCol = WorksheetFunction.Match("Produto", Sheet1.Range("B3:G3"), 0)'Use variable for field parameter valuelo.Range.AutoFilter Field:=iCol, Criteria1:="Produto 3"Final Sub

The column number will be found every time we run the macro. We don't have to worry about the field number changing when the column is moved. This saves time and avoids mistakes (win-win)! 🇧🇷

Use Excel spreadsheets with filters

Using Excel spreadsheets has many advantages, especially with the AutoFilter method. These are some of the main reasons I prefer spreadsheets.

  • We don't need to redefine the range in VBA because the data range will be resized (rows/columns will be added/removed). The entire table is referenced with the ListObject object.
  • It's easy to reference the data in the table after applying the filters. We can use the DataBodyRange property to reference visible rows for copy/paste, formatting, changing values, etc.
  • We can have multiple tables in the same worksheet and therefore multiple filter areas. With regular ranges, we can only have one filtered range per worksheet.
  • Code to clear all filters on a table is easier to write.

Filters and data types

The options in the filter drop-down menu change depending on the type of data in the column. We have different filters for text, numbers, dates and colors. This creates MANY different combinations of operators and criteria for each filter type.

I made separate posts for each of these filter types. The posts contain explanations and examples of VBA code.

  • How to clear filters using VBA
  • How to filter text using VBA
  • How to filter by numbers using VBA
  • How to filter by date using VBA

The file in the download area above contains all these code examples in one place. You can add it to yourpersonal macro bookand use the macros in your projects.

Why is the automatic filter method so complex?

This post was inspired by a question from Chris, a member of the VBA Pro Course. The combinations of criteria and operators can be confusing and complex. Why is this?

Well, filters have evolved over the years. We've seen many new filter types introduced in Excel 2010 and the feature just keeps getting better. However, the parameters of the AutoFilter method have not changed. This is great for backward compatibility, but it also means that new filter types can be incorporated into existing parameters.

Most of the filter code makes sense, but it can be difficult to understand at first. Fortunately, we have the macro recorder to help us with this.

I hope you can use this post and the Excel file as a guide for writing macros for filters. Filter automation can save us and our users a lot of time, especially when using these techniques in a larger data automation project.

Please leave a comment below with any questions or suggestions. Thank you very much! 🇧🇷

FAQs

How do you use AutoFilter criteria in Excel VBA? ›

AutoFilter in VBA is which we can use as an expression. The syntax for it is as follows: Expression. Autofilter(Field, Criteria 1, Operator, Criteria 2, Dropdown) all of the arguments are optional. The filter helps filter the particular data from the huge data.

How do I filter AutoFilter in Excel? ›

Use AutoFilter to filter your data
  1. Select the data you want to filter.
  2. Click Data > Filter.
  3. Click the arrow. ...
  4. Choose specific values: Uncheck (Select All) to clear all of the check boxes, and then check the boxes for the specific value(s) you want to see.

What is the difference between filter and AutoFilter in Excel? ›

AutoFilter allows filtering data with a maximum of 2 criteria, and those conditions are specified directly in the Custom AutoFilter dialog box. Using Advanced Filter, you can find rows that meet multiple criteria in multiple columns, and the advanced criteria need to be entered in a separate range on your worksheet.

How do you use filtering in Excel? ›

Filter a range of data
  1. Select any cell within the range.
  2. Select Data > Filter.
  3. Select the column header arrow .
  4. Select Text Filters or Number Filters, and then select a comparison, like Between.
  5. Enter the filter criteria and select OK.

How do I create a filter in Excel VBA? ›

Examples to Filter Data using VBA
  1. Step 1: Supply data range. To activate the filter option first, we need to supply what is our data range. ...
  2. Step 2: Then access AutoFilter function. Now, access the AutoFilter function for this range. ...
  3. Step 3: Run the code to enable the filter. That is all.

What are macro filters used for? ›

In photography, a close-up lens (sometimes referred to as close-up filter or a macro filter) is a simple secondary lens used to enable macro photography without requiring a specialised primary lens. They work like reading glasses, allowing a primary lens to focus more closely.

How do you AutoFilter multiple columns in Excel VBA? ›

To filter more fields or columns simply copy and paste this line in the macro (Range("A1"). AutoFilter Field:=2, Criteria1:="Enter Criteria Here" ) and change the field number and the criteria. That is all you have to do to filter more than two columns at once.

How many types of filters are there in Excel? ›

In Excel, you can create three kinds of filters: by values, by a format, or by criteria. But each of these filter types is mutually exclusive. For example, you can filter by cell color or by a list of numbers, but not by both. You can filter by icon or by a custom filter, but not by both.

What is AutoFilter in MS Excel write the steps with example? ›

Excel AutoFilter is an easy way to turn the values in Excel columns into specific filters based on the cell content. The AutoFilter in Excel enables us to filter our data as we desire in one, two, or more columns at once. Excel AutoFilter allows us to slice and dice our data as per our requirements.

What is filter in MS Excel? ›

The FILTER function allows you to filter a range of data based on criteria you define.

Can you use filter function in VBA? ›

The VBA FILTER function is listed under the array category of VBA functions. When you use it in a VBA code, it can return strings from an array of strings based on the string you have specified as a subset.

How do I filter a column in Excel VBA? ›

How to Filter a Column with VBA AutoFilter
  1. The Filter Range. A Word on Terminology. The Field Parameter.
  2. Defining the Filter Criteria. Filter For a String. Filter For Multiple Strings. Filter For Values. Special Filters. Leverage User Input.
  3. Clearing Filters.
17 Sept 2021

What is the fastest way to filter multiple values in Excel? ›

How to filter in Excel effectively
  1. Select the cell of interest and click Apply Filter by Selected Value.
  2. Filter by selected value is created.
  3. Select several cells and click Apply Filter by Selected Value.
  4. The list is filtered by multiple values.
  5. Clear all filters in one click.

What types of data can you filter using the Autofilter tool? ›

When you filter data, entire rows are hidden if values in one or more columns don't meet the filtering criteria. You can filter on numeric or text values, or filter by color for cells that have color formatting applied to their background or text.

What is filter and types? ›

Electronic filters remove unwanted frequency components from the applied signal, enhance wanted ones, or both. They can be: passive or active. analog or digital. high-pass, low-pass, band-pass, band-stop (band-rejection; notch), or all-pass.

What is the importance of filtering data in Excel? ›

In addition to sorting, you may find that adding a filter allows you to better analyze your data. When data is filtered, only rows that meet the filter criteria will display and other rows will be hidden. With filtered data, you can then copy, format, print, etc., your data, without having to sort or move it first.

What is filtering why and how it is done in Excel? ›

What is Filter in Excel? The filter in excel helps display relevant data by eliminating the irrelevant entries temporarily from the view. The data is filtered as per the given criteria. The purpose of filtering is to focus on the crucial areas of a dataset.

Why is filtering important in Excel? ›

You sort data to quickly organize your data and to find the data that you want. You filter data to display only the rows that meet criteria that you specify and hide rows that you do not want displayed, for one or more columns of data.

Are macro filters any good? ›

The main benefit of using a macro filter is that it can turn any of your lenses into a macro lens. Unlike other macro attachments, it's also small and lightweight. Finally, it is one of the cheapest options out there for those who want to get into macro photography.

What is a disadvantage of using a macro filter? ›

One of the disadvantages of macro filters is that the images will not be as sharp and detailed as they would be if they were taken with a macro lens. Using a UV filter in the studio is completely unnecessary and pointless, unless it serves to protect the front lens of the lens.

What are filters and why are they so important? ›

A filter is a circuit capable of passing (or amplifying) certain frequencies while attenuating other frequencies. Thus, a filter can extract important frequencies from signals that also contain undesirable or irrelevant frequencies. In the field of electronics, there are many practical applications for filters.

How do I filter data in Excel with multiple criteria? ›

Multiple criteria, multiple columns, all criteria true
  1. Insert at least three blank rows above the list range that can be used as a criteria range. ...
  2. To find rows that meet multiple criteria in multiple columns, type all the criteria in the same row of the criteria range. ...
  3. Click a cell in the list range.

How do you Autofilter a table based on a cell value in Excel? ›

To apply a filter for a cell's value: Right-click a cell that contains the value you want to filter for. Choose Filter > Filter by Selected Cell's Value. The filter will be applied to the column.

How do you AutoFilter based on cell value? ›

To apply a filter for a cell's value: Right-click a cell that contains the value you want to filter for. Choose Filter > Filter by Selected Cell's Value. The filter will be applied to the column.

How does filter function work in Excel? ›

The FILTER function in Excel is used to filter a range of data based on the criteria that you specify. The function belongs to the category of Dynamic Arrays functions. The result is an array of values that automatically spills into a range of cells, starting from the cell where you enter a formula.

Is VBA useful for data analytics? ›

Microsoft Excel VBA allows for automating tasks in Excel and provides a full programming environment for data analysis. Macro record a set of actions so they can be easily executed again.

What are the three main categories of the VBA statements? ›

Each statement belongs to one of the following three categories: Declaration statements, which name a variable, constant, or procedure and can also specify a data type. Assignment statements, which assign a value or expression to a variable or constant. Executable statements, which initiate actions.

What are the three main logical operators in VBA? ›

Logical operators allow you to evaluate one or more expressions and return a Boolean value ( True or False ). VB.NET supports four logical operators: And , AndAlso , Or , OrElse , Not , and Xor . These operators also double as bitwise operators.

How do I filter unique values in Excel VBA? ›

Finding Unique Values
  1. Range("C:C"). AdvancedFilter xlFilterCopy, , Range("H1:H1"), True.
  2. Range("A:B"). AdvancedFilter xlFilterCopy, , Range("H1:H1"), True.
  3. Sub wasOriginalUnique() Dim beforeCount, afterCount As Integer Range("A:A"). ...
  4. Sub uniquesToColumnH() Range("A:A").
6 Aug 2021

How do you filter a column in Excel using macro? ›

Step 1: Record or Write the Macro
  1. Clear the filters on your sheet or Table.
  2. Turn the macro recorder on (Developer Tab > Record Macro button)
  3. Give the macro a name.
  4. Choose to Store macro in: This Workbook.
  5. Click OK.
  6. Apply filters to one or more columns using the Filter Drop-down menus.
19 Jul 2018

How do I create a custom AutoFilter list? ›

To do this, select the Text Filter command from the table menu and choose one of its text filtering options. No matter which text filtering option you pick, Excel displays the Custom AutoFilter dialog box. This dialog box enables you to specify with great precision what records you want to appear on your filtered list.

Videos

1. Excel Filter - Part 1 (Basic Excel Filters) Complete Tutorial
(Microsoft Office Tutorials)
2. Create Multiple Pivot Table Reports with Show Report Filter Pages
(Excel Campus - Jon)
3. Excel 2010 New features- Sparklines, new conditional format, easier data filter, new weekend options
(AuditExcel Advanced Excel and Financial Model Training and Consulting)
4. Excel Filters Training - Keyboard Shortcuts - Part 2 of 3
(Excel Campus - Jon)
5. PART 140 - HOW TO CLEAR SLICERS FILTER IN MS EXCEL BY USING VBA MACRO (TAMIL)
(Kallanai YT)
6. How to Filter Pivot Tables for Month-to-Date MTD Comparisons with Slicers
(Excel Campus - Jon)
Top Articles
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated: 03/11/2023

Views: 6047

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.