Using VBA code to filter a list in Excel automates the process of showing only rows that meet specific criteria, saving time and reducing errors when working with large datasets. This method works directly within Excel’s built-in VBA editor and requires no add-ins or external tools. You need a structured table or range with headers, and Excel must allow macros to run.
What You'll Need
- Microsoft Excel 2010 or later (Windows or Mac)
- A data range with column headers (e.g., Name, Department, Status)
- Macros enabled in Excel (File > Options > Trust Center > Trust Center Settings > Macro Settings > Enable all macros or Enable macros for this session)
- Basic familiarity with the VBA Editor (Alt + F11)
Step-by-Step
- Open your Excel workbook containing the list you want to filter. Ensure your data has headers in the first row and no blank rows within the dataset.
- Press Alt + F11 to open the Visual Basic for Applications (VBA) Editor.
- In the Project Explorer pane on the left, find your workbook (e.g., VBAProject (YourWorkbook.xlsx)). Right-click it and select Insert > Module. This creates a new blank code module.
- Copy and paste the following basic VBA code into the module window:
Sub FilterList() Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") 'Change "Sheet1" to your sheet name 'Clear any existing filters If ws.AutoFilterMode Then ws.AutoFilterMode = False 'Apply filter to column 2 (e.g., Department) for value "Sales" ws.Range("A1:D100").AutoFilter Field:=2, Criteria1:="Sales" End SubReplace "Sheet1" with the actual name of your worksheet. Adjust the range "A1:D100" to match your data’s actual start and end cells. Change Field:=2 to the column number you want to filter (1 for A, 2 for B, etc.). Replace "Sales" with your desired filter value. - Save your workbook as a Macro-Enabled Workbook (.xlsm). Go to File > Save As, select "Excel Macro-Enabled Workbook (*.xlsm)" from the file type dropdown, then click Save.
- Close the VBA Editor and return to Excel.
- Press Alt + F8 to open the Macro dialog box. Select "FilterList" and click Run.
- Verify that only rows matching your criteria (e.g., Department = Sales) are visible. Other rows are hidden, not deleted.
- To filter by multiple criteria, modify the code. For example, to filter column 2 for "Sales" AND column 3 for "Active":
ws.Range("A1:D100").AutoFilter Field:=2, Criteria1:="Sales" ws.Range("A1:D100").AutoFilter Field:=3, Criteria1:="Active" - To clear the filter later, run this simple macro:
Sub ClearFilter() Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") If ws.AutoFilterMode Then ws.AutoFilterMode = False End Sub
Common Mistakes
- Using incorrect sheet names in the code — if your sheet is named "Data" but the code says "Sheet1", the macro will fail with a runtime error.
- Filtering a range that doesn’t include headers — AutoFilter requires headers to work. If your data starts at row 2, adjust the range to include row 1.
- Forgetting to save as .xlsm — if you save as .xlsx, the macro will be lost when you close the file.
- Using text criteria with extra spaces or inconsistent capitalization — "sales" ≠ "Sales". Use Trim() or wildcards like "*Sales*" if needed.
- Applying filters to a non-contiguous range — AutoFilter only works on a single contiguous block. Insert blank rows or columns within your data range will cause errors.
Tips
- Use named ranges instead of fixed cell references (e.g., Range("MyDataTable")). This makes your code more reusable if your data grows.
- For dynamic filtering based on user input, declare a variable: Dim filterVal As String: filterVal = InputBox("Enter department:"): then use Criteria1:=filterVal.
- To filter for multiple values in one column (e.g., Sales OR Marketing), use an array: Criteria1:=Array("Sales", "Marketing"), Operator:=xlFilterValues.
- Always test your macro on a copy of your data first. Filtering doesn’t delete data, but hiding rows can be confusing if you forget how to unfilter.
- Use Debug.Print to log values during development: Insert Debug.Print ws.Range("A1").Value to see what’s being read.
- Consider adding error handling: Wrap your code in On Error Resume Next and On Error GoTo 0 to prevent crashes if the sheet doesn’t exist.
Troubleshooting
- "Run-time error '9': Subscript out of range" — This means the sheet name in your code doesn’t match the actual worksheet name. Check spelling, case, and spaces. Use the exact name as shown at the bottom tab of Excel.
- Filter doesn’t appear or nothing changes — Confirm that the range you specified includes the header row. If the data starts at row 2, your range must be A1:D100, not A2:D100.
- Macro is grayed out in the Run dialog — Your workbook is not saved as .xlsm. Save it again with the correct file type.
- "AutoFilter method of Range class failed" — Your range may include merged cells or non-adjacent columns. Unmerge cells and ensure all columns in the range are contiguous.
- Filter works manually but not via VBA — Check if the worksheet is protected. Unprotect it (Review > Unprotect Sheet) before running the code, or add ws.Unprotect Password:="yourpassword" before the filter line.
- Code runs but filters nothing — The criteria value might not exist. Try filtering for "*" to see if any data is returned. If nothing shows, your data range might not include actual data.