To filter a table using VBA, you use the AutoFilter method applied to a ListObject or a Range. The most efficient way to do this is by referencing the table name and specifying the field index (the column number) and the criteria you want to match. For example, ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=2, Criteria1:="Completed" will filter the second column of "Table1" to show only rows marked as "Completed".
What You'll Need
- Microsoft Excel installed on a Windows or Mac PC.
- A dataset formatted as an official Excel Table (Insert > Table).
- The Developer tab enabled in the Excel Ribbon.
- Basic knowledge of how to open the Visual Basic Editor (ALT + F11).
Step-by-Step
- Prepare Your Table: Ensure your data is converted into an official Excel Table. Select your data range and press
Ctrl + T. In the Table Design tab, note the "Table Name" (e.g., Table1). Using an official table is superior to using a standard range because tables expand automatically when data is added, and VBA can reference them by name regardless of where they move on the sheet. - Open the VBA Editor: Press
ALT + F11on your keyboard to launch the Visual Basic for Applications (VBA) editor. This opens a separate window where you will write your automation scripts. - Insert a New Module: In the Project Explorer on the left, right-click on your workbook name, select
Insert, and then clickModule. This creates a blank space where your code will live, ensuring it is available to the entire workbook. - Write the Basic Filter Code: Copy and paste the following structure into the module:
Sub FilterMyTable() Dim myTable As ListObject Set myTable = ActiveSheet.ListObjects("Table1") myTable.Range.AutoFilter Field:=1, Criteria1:="North" End SubIn this example,Field:=1refers to the first column of the table, andCriteria1:="North"tells Excel to only show rows where that column contains the word "North". - Adding Multiple Criteria: If you need to filter for two different values in the same column (an "OR" logic), you must use the
Operatorargument. Modify your code like this:myTable.Range.AutoFilter Field:=1, Criteria1:="North", Operator:=xlOr, Criteria2:="South"
This will display rows that are either "North" or "South". - Filtering by Date or Number: When filtering numbers or dates, the criteria often require specific formatting. For a number greater than 100, use:
myTable.Range.AutoFilter Field:=3, Criteria1:=">100"
For dates, it is safest to use theDateSerialfunction or a formatted string to ensure Excel recognizes the date regardless of the user's regional settings. - Creating a Clear Filter Button: To allow users to reset the table, create a second macro:
Sub ClearTableFilter() Dim myTable As ListObject Set myTable = ActiveSheet.ListObjects("Table1") if myTable.ShowAutoFilter then myTable.AutoFilter.ShowAllData End If End SubTheShowAllDatamethod removes all active filters without removing the filter dropdown arrows from the header row. - Assigning the Code to a Button: Go back to your Excel sheet. Go to the
Developertab, clickInsert, and choose theButton (Form Control). Draw the button on your sheet, and when the "Assign Macro" window appears, selectFilterMyTable. Repeat this for the clear filter button.
Common Mistakes
One of the most frequent errors is referencing the wrong Field index. The field number is relative to the table, not the worksheet. If your table starts in Column C, the first column of that table is Field:=1, not Field:=3. If you use the worksheet column index, your filter will either apply to the wrong column or trigger a "Run-time error 1004".
Another common mistake is forgetting that AutoFilter is case-insensitive by default but sensitive to trailing spaces. If your data contains "North " (with a space) and your code looks for "North", the filter will return no results. Always ensure your data is trimmed using the TRIM function before applying VBA filters.
Many users also attempt to filter a range that is not a Table (ListObject) using Range.AutoFilter. While this works, it is fragile. If you insert a new column to the left of your data, the hardcoded range in your VBA will be offset, and the filter will break. Always prefer ListObjects for stability.
Finally, attempting to use ShowAllData when no filters are currently applied will result in an error. This is why the If myTable.ShowAutoFilter check or an On Error Resume Next statement is necessary to prevent the macro from crashing when the table is already unfiltered.
Tips
To make your filter dynamic, instead of hardcoding the criteria (like "North"), link the VBA code to a cell. For example, Criteria1:=Range("H1").Value. This allows users to type a value into cell H1 and click the button to filter the table based on that input without ever touching the code.
If you need to filter for a list of many items (more than two), the Criteria1 and Criteria2 approach won't work. Instead, you should pass an array of strings to the filter and set the operator to xlFilterValues. Example: myTable.Range.AutoFilter Field:=1, Criteria1:=Array("North", "South", "East", "West"), Operator:=xlFilterValues.
For better performance on very large datasets, disable screen updating at the start of your macro using Application.ScreenUpdating = False and re-enable it at the end. This prevents the screen from flickering and speeds up the execution of the filter.
Consider using a Select Case statement if you want one button to cycle through different filter views (e.g., clicking once for "Pending", twice for "Completed", and three times to "Clear All"). This creates a more interactive dashboard experience for the end user.
Troubleshooting
If the code runs but the table does not filter, first check if the sheet is protected. VBA cannot modify filters on a protected worksheet unless the sheet was protected with UserInterfaceOnly:=True. Unprotect the sheet and try again.
If you receive a "Subscript out of range" error, it almost always means the table name in your code (e.g., "Table1") does not exactly match the name of the table in the Table Design tab. Check for typos or extra spaces in the table name.
If the filter is applying to the wrong column, double-check your Field:= number. Remember that this number counts from the leftmost column of the table, regardless of where the table is positioned on the spreadsheet.
If you are filtering dates and nothing is showing up, try converting the date to a Long integer in your code. Excel stores dates as numbers, and sometimes the AutoFilter method fails to match a date string to the underlying numeric value. Using CLng(CDate("2023-01-01")) as the criteria often resolves this.
Frequently Asked Questions
Can I filter by multiple columns at once?
Yes. Simply add multiple AutoFilter lines one after another. For example, filter Field 1 for "North" and then filter Field 2 for "High Priority". Excel will treat these as "AND" logic, showing only rows that meet both conditions.
How do I filter for cells that contain a specific word?
Use wildcards. To filter for any cell that contains the word "Project", use Criteria1:="*Project*". The asterisks act as placeholders for any characters appearing before or after the keyword.
Does this work on Excel for Mac?
Yes, the AutoFilter method is standard across both Windows and Mac versions of Excel VBA, though the keyboard shortcuts to open the editor may differ.
Can I filter for blank cells?
Yes. To show only blank cells in a column, use Criteria1:="=". To hide blank cells and show only those with data, use Criteria1:="<>".
What is the difference between Range.AutoFilter and ListObject.AutoFilter?
Range.AutoFilter applies to a static block of cells. ListObject.AutoFilter is designed specifically for Excel Tables, making it more robust because it automatically adjusts as the table grows or shrinks.