Return to VBA Code Examples
VBA – Turn Off AutoFilter / Clear Filters
In this Article
- Turn off AutoFilter in the Active Worksheet in VBA
- Turn on AutoFilter in the Active Worksheet in VBA
- Turn off AutoFilter in all Worksheets in VBA.
- Turn on AutoFilter in all Worksheets in VBA.
- Clear All Filters in the Active Worksheet in VBA
- Clear All Filters in all Worksheets in VBA
- Clear All Filters in a Table in VBA
- VBA Coding Made Easy
This tutorial will demonstrate how to turn off /clear AutoFilters in VBA.
AutoFilters can be turned on or off using VBA code.
Turn off AutoFilter in the Active Worksheet in VBA
The following code example turns off AutoFilter in the Active Sheet, checking first that it’s not Off already.
Public Sub KillFilter()
If ActiveSheet.AutoFilterMode Then
ActiveSheet.AutoFilterMode = False
End If
End Sub
Turn on AutoFilter in the Active Worksheet in VBA
The following code example turns on AutoFilter in the Active Sheet, checking first that it’s not on already.
Public Sub StartFilter()
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("A1").AutoFilter
End If
End Sub
Turn off AutoFilter in all Worksheets in VBA.
The following code example loops through each sheet in the entire workbook and turns off AutoFilter in each worksheet, checking first that the filter in the current worksheet is not on already.
Public Sub StopAllFilters()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.AutoFilterMode = True Then
ws.AutoFilterMode = False
End If
Next ws
End Sub
Turn on AutoFilter in all Worksheets in VBA.
Similarly, the following code example loops through the entire workbook and turns on AutoFilter in each sheet, checking first that the filter in the current worksheet is not already on.
Public Sub StartAllFilters()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If Not ws.AutoFilterMode Then
ws.Range("A1").AutoFilter
End If
Next ws
End Sub
Clear All Filters in the Active Worksheet in VBA
The following code example leaves the AutoFilter turned on in the Active Sheet, but clears any filter that are applied to the data.
Public Sub ClearFilter()
If ActiveSheet.FilterMode = True Then
ActiveSheet.ShowAllData
End If
End Sub
Clear All Filters in all Worksheets in VBA
Similarly, the following code example loops through the entire workbook and leaves the AutoFilter turned on in each sheet if it is already on, but clears any filter that are applied to the data.
Public Sub ClearAllFilters()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.FilterMode = True Then
ws.ShowAllData
End If
Next ws
End Sub
Clear All Filters in a Table in VBA
Should our worksheet contain a table object, we can adjust the code to just clear any filter that is applied to that filter, while leaving the AutoFilter switched on.
Sub ClearFilterFromTable()
Dim ws As Worksheet
Dim sTable As String
Dim loTable As ListObject
sTable = "Table1"
Set ws = ActiveSheet
Set loTable = ws.ListObjects(sTable)
loTable.AutoFilter.ShowAllData
End Sub
Should the table object be linked to a Pivot Table, then the Pivot table would refresh accordingly.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
{quote}{login=Электророзетка}{date=28.11.2008 04:50}{thema=}{post}Ребята, а зачем макрос для «Отобразить все»? Мы не ищем легких путей? :)) Не проще кнопку вынести на панель инструментов? Вот тут даже написано как это сделать:
http://www.planetaexcel.ru/tip.php?aid=45
(даже слишком подробно).
А если нужно не отобразить все, а вообще удалить автофильтр, то у меня кнопке назначен вот такой микромакрос:
Sub Remove_Autofilter()
Selection.AutoFilter
End Sub{/post}{/quote}
макрос — он для использования в других макросах.. это ВАм сразу ясно есть автофильтр на листе или нет, а макросы — они глупые..
хотя и к макросу можно кнопку прикрутить — в общем оно универсальнее..
VBA remove filter from table in Excel. In this tutorial we learn how to remove or clear or delete filter from table. We use AutoFilter and ShowAllData method. It helps to show or display complete data for table. Let us see syntax, different examples using VBA. Also find and learn step by step instructions to run vba example macro code.
Table of Contents:
- Objective
- VBA Syntax to Remove Filter from Table in Excel
- VBA Remove Filter from Table
- VBA Delete Filter on Single Column from Table
- Clear Filter on Multiple Columns From Table
- VBA Clear All Filters from All Tables on Worksheet
- Clear All Filters from All Tables on the Workbook
- Instructions to Run VBA Macro Code
- Other Useful Resources
VBA Syntax to Remove or Clear Filter from Table in Excel
Let us see the syntax to remove filter from table in Excel.
expression.AutoFilter.ShowAllData
Where
expression represents ListObject.
AutoFilter represents object.
ShowAllData represents method of the AutoFilter object.
VBA Remove Filter from Table
Here is a simple example macro to remove filter from table.
'Remove Filter from Table in Excel VBA Sub VBAF1_Remove_filter_from_Table() 'Declare Variables Dim oSheetName As Worksheet Dim sTableName As String Dim loTable As ListObject 'Define Variable sTableName = "MyTable" 'Define WorkSheet object Set oSheetName = Sheets("Table") 'Define Table Object Set loTable = oSheetName.ListObjects(sTableName) 'Add filter to table loTable.AutoFilter.ShowAllData End Sub
Delete Filter on Single Column from Table
Let us see another example delete filter on single column from table in Excel VBA. Here we have to specify column number to delete filter from table.
'VBA Delete Filter on Single Column from Table Sub VBAF1_Delete_filter_OnSingle_Column_from_table() 'Declare Variables Dim oSheetName As Worksheet Dim sTableName As String Dim loTable As ListObject 'Define Variable sTableName = "MyTable" 'Define WorkSheet object Set oSheetName = Sheets("Table") 'Define Table Object Set loTable = oSheetName.ListObjects(sTableName) 'Add filter to table loTable.Range.AutoFilter Field:=3 End Sub
Clear Filter on Multiple Columns From Table in Excel VBA
Here is one more example clear filter on multiple columns from table in Excel VBA. Here we have to specify multiple column numbers to clear filter from table.
'Clear Filter on Multiple Columns From Table Sub VBAF1_Clear_filter_OnMultiple_Columns_From_Table() 'Declare Variables Dim oSheetName As Worksheet Dim sTableName As String Dim loTable As ListObject 'Define Variable sTableName = "MyTable" 'Define WorkSheet object Set oSheetName = Sheets("Table") 'Define Table Object Set loTable = oSheetName.ListObjects(sTableName) loTable.Range.AutoFilter Field:=2 loTable.Range.AutoFilter Field:=3 End Sub
VBA Clear All Filters from All Tables on Worksheet in Excel
Let us see another example to clear filters from all tables on worksheet in Excel VBA. We loop through all the tables worksheets on the worksheet.
'VBA Clear All Filters from All Tables on Worksheet Sub VBAF1_Clear_All_Filters_From_All_Tables_OnWorksheet() 'Declare Variables Dim oSheetName As Worksheet Dim loTable As ListObject 'Define WorkSheet object Set oSheetName = Sheets("Table") 'Loop Through All Tables on the Worksheet For Each loTable In oSheetName.ListObjects 'Clear Filter from the Table loTable.AutoFilter.ShowAllData Next loTable End Sub
Clear All Filters from All Tables on the Workbook using VBA
One more example to clear filters from all tables on the worksheet using Excel VBA. We loop through all the tables in all worksheets on the worksheet.
'Clear All Filters from All Tables on the Workbook Sub VBAF1_Clear_All_Filters_From_All_Tables_InWorkbook() 'Declare Variables Dim oSheetName As Worksheet Dim loTable As ListObject 'Loop Through All Tables in the Workbook For Each oSheetName In Worksheets 'Loop Through All Tables on the Worksheet For Each loTable In oSheetName.ListObjects 'Clear Filter from the Table loTable.AutoFilter.ShowAllData Next loTable Next oSheetName End Sub
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel VBA Tables and ListObjects
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog
This thread is ancient, but I wasn’t happy with any of the given answers, and ended up writing my own. I’m sharing it now:
We start with:
Sub ResetWSFilters(ws as worksheet)
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This gets rid of "normal" filters - but tables will remain filtered
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
'And this gets rid of table filters
End Sub
We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook
Sub ResetAllWBFilters(wb as workbook)
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:
Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:Intel......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub
The one I use the most: Resetting all filters in the workbook that the module is stored in:
Sub ResetFilters()
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
Set wb = ThisWorkbook
'Set wb = ActiveWorkbook
'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
Содержание
- Отключите автофильтр на активном листе в VBA
- Включите автофильтр на активном листе в VBA
- Отключите автофильтр на всех листах в VBA.
- Отключите автофильтр на всех листах в VBA.
- Очистить все фильтры на активном листе в VBA
- Очистить все фильтры на всех листах в VBA
- Очистить все фильтры в таблице в VBA
В этом руководстве будет показано, как отключить / очистить автофильтры в VBA.
Автофильтры можно включить или выключить с помощью кода VBA.
В следующем примере кода автофильтр отключается на активном листе, сначала проверяя, что он еще не отключен.
12345 | Public Sub KillFilter ()Если ActiveSheet.AutoFilterMode, тоActiveSheet.AutoFilterMode = FalseКонец, еслиКонец подписки |
Включите автофильтр на активном листе в VBA
В следующем примере кода включается автофильтр на активном листе, сначала проверяя, что он еще не включен.
12345 | Общедоступный подпункт StartFilter ()Если не ActiveSheet.AutoFilterMode, тоActiveSheet.Range («A1»). АвтофильтрКонец, еслиКонец подписки |
Отключите автофильтр на всех листах в VBA.
В следующем примере кода выполняется цикл по каждому листу во всей книге и отключается автофильтр на каждом листе, сначала проверяя, что фильтр в текущей книге еще не включен.
12345678 | Публичная подпрограмма StopAllFilters ()Dim ws как рабочий листДля каждой страницы в ActiveWorkbook.WorksheetsЕсли ws.AutoFilterMode = True, тоws.AutoFilterMode = FalseКонец, еслиСледующий wsКонец подписки |
Отключите автофильтр на всех листах в VBA.
Точно так же в следующем примере кода выполняется цикл по всей книге и включается автофильтр на каждом листе, сначала проверяя, что фильтр в текущей книге еще не включен.
12345678 | Публичная подпрограмма StartAllFilters ()Dim ws как рабочий листДля каждой страницы в ActiveWorkbook.WorksheetsЕсли не ws.AutoFilterMode, тоws.Range («A1»). АвтофильтрКонец, еслиСледующий wsКонец подписки |
Очистить все фильтры на активном листе в VBA
В следующем примере кода автофильтр остается включенным на активном листе, но очищаются все фильтры, примененные к данным.
12345 | Public Sub ClearFilter ()Если ActiveSheet.FilterMode = True, тоActiveSheet.ShowAllDataКонец, еслиКонец подписки |
Очистить все фильтры на всех листах в VBA
Точно так же в следующем примере кода выполняется цикл по всей книге и оставляет включенным автофильтр на каждом листе, если он уже включен, но очищает любой фильтр, примененный к данным.
12345678 | Публичная подпрограмма ClearAllFilters ()Dim ws как рабочий листДля каждой страницы в ActiveWorkbook.WorksheetsЕсли ws.FilterMode = True, тоws.ShowAllDataКонец, еслиСледующий wsКонец подписки |
Очистить все фильтры в таблице в VBA
Если наш рабочий лист содержит объект таблицы, мы можем настроить код, чтобы просто очистить любой фильтр, примененный к этому фильтру, оставив автофильтр включенным.
123456789 | Подложка ClearFilterFromTable ()Dim ws как рабочий листDim sTable As StringDim loTable как ListObjectsTable = «Таблица1″Установить ws = ActiveSheetУстановите loTable = ws.ListObjects (sTable)loTable.AutoFilter.ShowAllDataКонец подписки |
Если объект таблицы будет связан со сводной таблицей, то сводная таблица обновится соответствующим образом.
Вы поможете развитию сайта, поделившись страницей с друзьями
Has your data import procedure ever failed due to users applying filters on the data? This happens quite often, especially when you distribute multiple files, which you then stack. Copying filtered data copies only the filtered rows. You end up loosing the hidden rows if users filtered data before saving the workbook. Let us take a look at how to remove filters in an Excel sheet using VBA.
Before we dive into how to remove filters, let us briefly take a look at the types of filtering capability Excel offers. Filtering in Excel comes in two flavours:
- Auto Filter
- Advanced Filter
Auto filter adds dropdown buttons to the columns, which offer you a variety of filtering and sorting options through an intuitive graphical interface. Advanced Filter on the other hand, lets you specify your filtering criteria in a range of cells.
Auto Filter is easy to spot visually; the dropdowns are hard to miss. However, Advanced Filter is a harder to spot. In both cases, if some of the Row Numbers to the left of a sheet appear blue instead of the regular black colour, filters have been applied on that sheet.
Mastering both these skills are essential for anybody who uses Excel at their workplace. There are a multitude of resources on the internet on these topics. I recommend you familiarise yourself with filtering data in Excel.
The ShowAllData method of the Worksheet object lets you remove any filters that were applied on the data. However, it throws a runtime error when filters have not been applied. One could simply supress the error and call it a day, but I’d loose sleep over resorting to such cowardice. Let us try to figure out a legitimate way of finding whether or not filters have been applied on a sheet.
The FilterMode property of the Worksheet object gets set to TRUE, when filters are applied either as Auto Filters or Advanced Filters. This is a Read-Only property. It can be used to check whether any filters are applied, before using the ShowAllData method. This will help us ensure a runtime error is not triggered when calling the ShowAllData method.
If you are interested in removing the Auto Filter Dropdown buttons as well, which is how I prefer it, you can use the AutoFilterMode property to turn it off. This property is not a Read-Only property, which means you can set it to TRUE to activate AutoFilters and vice versa.
Wrapping this all up, here is a Sub that I use very frequently, which you can use in your projects:
Sub RemoveFilters(ByRef WhichSheet As Worksheet) 'If data is filtered either using AutoFilters or Advanced Filters 'Show all the data If WhichSheet.FilterMode Then WhichSheet.ShowAllData 'Hide the AutoFilter DropDown Buttons If WhichSheet.AutoFilterMode Then WhichSheet.AutoFilterMode = False End Sub
Just pass a Worksheet to the above sub to remove filters without encountering a runtime error.
Note that having Excel Tables, also known List Objects in VBA, in the worksheet could throw these properties off, especially when the active cell is in a Table. If you are using Excel Tables, and I highly recommend that you do, you can deal with filters applied to a table specifically. We will reserve that discussion for another day.
Downloads
Click the link below to download a workbook with the above code. It also has a cover macro on removing filters in the active sheet.
Further Reading
- Advanced filters come in handy when you have to apply a rather complex filter criteria repeatedly. It is also easy to filter data using VBA if you create an appropriate criteria range. Coding the application of AutoFilters is rather cumbersome. Here is an introduction to using AutoFilters in Excel:
- Excel Advanced Filter Introduction – Debra Dalgleish
AutoFilters are a great feature in Excel. Often they are a quicker way of sorting and filtering data than looping through each cell in a range.
This post provides the main lines of code to apply and control the AutoFilter settings with VBA.
Adapting the code to your needs
Every code snippet below is applied to the ActiveSheet (i.e., whichever sheet which is currently in use at the time the macro runs). It is easy to apply the code to other sheets by changing the section of code which refers to the ActiveSheet.
'Apply to a specific sheet by name
Sheets("SheetName").AutoFilter...
'Apply to a specific sheet by it's position to the left most tab. 1 being the first tab.
Sheets(1).AutoFilter...
'Apply to a specific sheet by it's VBA Code Name 'VBA Code Name is the "(Name)" property of the worksheet Sheet1.Autofilter...
'Apply to a specific sheet in a different workbook.
Workbooks("AnotherWorkbook.xlsx").Sheets("Sheet1").AutoFilter...
AutoFilter Icons
When using AutoFilters, the icons at the top of the columns indicate whether any settings have been applied.
Check Auto Filter existence
Each worksheet can only contain one AutoFilter. The following code checks for the existence of an AutoFilter by checking the AutoFilterMode property of the sheet.
'Check if an AutoFilter already exists If ActiveSheet.AutoFilterMode = True Then 'Do something End If
Add / Remove an Auto Filter
'Apply filter to 'Current Region' which contains cell A1.
ActiveSheet.Range("A1").AutoFilter
The AutoFilter will be applied to the “current region” of the cells. The Current Region represents the cells surrounding the selected cell which are not separated by a blank row or column.
Trying to add an AutoFilter to an empty cell will trigger an error message.
'Remove AutoFilter ActiveSheet.AutoFilterMode = False
Hide / Display Auto Filter drop-down button
The drop-down buttons can be hidden, giving the appearance that there is no AutoFilter on the worksheet. This is great if using VBA to control the AutoFilter as part of a process; the user will not be able to apply their own settings.
'Hide the dropdown filter from Cells by field number, or by range ActiveSheet.Range("A1").AutoFilter Field:=1, Visibledropdown:=False ActiveSheet.Range("A1").AutoFilter Field:=2, Visibledropdown:=False
'Display the dropdown filter from Cells by field number, or by range ActiveSheet.Range("A1").AutoFilter Field:=1, Visibledropdown:=True ActiveSheet.Range("A1").AutoFilter Field:=2, Visibledropdown:=True
Count visible records
After applying a filter, counting the visible cells in the first column will show the number of records meeting the criteria applied.
'Count the number of rows which are visible in the AutoFilter
'including the Header (hence the -1 at the end)
MsgBox ActiveSheet.AutoFilter.Range.Columns(1). _
SpecialCells(xlCellTypeVisible).Count - 1
Get Auto Filter range
The code below will show you the range of cells which are covered by the AutoFilter.
'Get Range of AutoFilter, including the header row
MsgBox ActiveSheet.AutoFilter.Range.Address
Show everything
Showing everything in the AutoFilter will cause an error if a filter has not been applied.
'First check if a filter has been applied If ActiveSheet.FilterMode = True Then 'Show all the data ActiveSheet.ShowAllData End If
Apply text filter to a column
The example below shows how to apply a text filter for any value of “A” or “B”.
'Apply a text filter to a column
ActiveSheet.Range("A1").AutoFilter Field:=1, Criteria1:="=A", _
Operator:=xlOr, Criteria2:="=B"
Advanced filtering is one of the most useful features of AutoFilter. The examples show how to apply different criteria by using Wildcards.
Equals: Criteria1:="=Apple" Does Not Equal: Criteria1:="<>Apple" Begins with: Criteria1:="=*Apple" Ends with: Criteria1:="=Apple*" Contains: Criteria1:="=*Apple*" Does Not Contain: Criteria1:="<>*Apple*"
Operators allow multiple filters to be applied to a single column. Filters can be ‘and’ where both criteria are met, or ‘or’ where either criteria is met.
Or: Operator:=xlOr And: Operator:=xlAnd
Apply color filter to a column
AutoFilters allow cells to be filtered by color. The RGB color code below can be used to sort by any color.
'Apply color filter using an RGB color
ActiveSheet.Range("$A$1:$A$7").AutoFilter Field:=1, Criteria1:=RGB(255, 255, 0), _
Operator:=xlFilterCellColor
'Filter on no fill color
ActiveSheet.Range("$A$1:$A$7").AutoFilter Field:=1, Operator:=xlFilterNoFill
Clear an existing sort
'Clear the sorted field
ActiveSheet.AutoFilter.Sort.SortFields.Clear
Apply an alphabetical sort
'Clear the sorted field ActiveSheet.AutoFilter.Sort.SortFields.Clear 'Setting the sorting options ActiveSheet.AutoFilter.Sort.SortFields.Add Order:=xlAscending, _ SortOn:=xlSortOnValues, Key:=Range("A1:A7") 'Applying the sort ActiveSheet.AutoFilter.Sort.Apply
To apply descending sort, change the Order property to xlDescending:
Order:=xlDescending
Apply a custom sort order
Alphabetical and reverse alphabetical may be the most likely sort order, however any custom sort order can be applied. The example below will sort in the order of “L”, “J”, “B” then “Q”.
'Clear the sorted field ActiveSheet.AutoFilter.Sort.SortFields.Clear 'Set the sort to a Custom Order ActiveSheet.AutoFilter.Sort.SortFields.Add Key:=Range("A2:A7"), _ SortOn:=xlSortOnValues, Order:=xlAscending, _ CustomOrder:="L,J,B,Q" 'Applying the sort ActiveSheet.AutoFilter.Sort.Apply
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts: