На чтение 4 мин. Просмотров 14.3k.
Итог: узнайте, как очистить все фильтры и фильтры в одном столбце с помощью макросов VBA. Включает примеры кода для регулярных диапазонов и таблиц Excel.
Уровень мастерства: Средний
Содержание
- Скачать файл
- Очистить все фильтры из диапазона
- Ошибка метода ShowAllData
- Очистить все фильтры из таблицы Excel
- Очистить все фильтры во всех таблицах на листе
- Очистить фильтры в одной колонке
- Фильтры и типы данных
Скачать файл
Файл Excel, содержащий код, можно скачать ниже. Этот файл содержит код для фильтрации различных типов данных и типов фильтров. Пожалуйста, ознакомьтесь с моей статьей Фильтрация сводной таблицы или среза по самой последней дате или периоду для более подробной информации.
VBA AutoFilters Guide.xlsm (100.5 KB)
Очистить все фильтры из диапазона
Мы используем метод ShowAllData, чтобы очистить все фильтры,
примененные к диапазону.
Это аналогично нажатию кнопки «Очистить» на вкладке «Данные»
на ленте (сочетание клавиш: Alt, A, C)
К рабочему листу может быть применен только один диапазон
фильтров, поэтому мы на самом деле очищаем фильтры на листе.
Sub Clear_All_Filters_Range() ' Для очистки всех фильтров используйте метод ShowAllData ' для листа. Добавьте обработку ошибок, чтобы обойти ошибку, если ' фильтры не применяются. Не работает для таблиц. On Error Resume Next Sheet1.ShowAllData On Error GoTo 0 End Sub
Ошибка метода ShowAllData
Если к любому столбцу не применены фильтры, метод ShowAllData вызовет ошибку. Это ошибка времени выполнения ‘1004 с описанием:
Method ‘ShowAllData’ of object ‘_Worksheet’ failed.
Следующая строка On Error Resume Next будет игнорировать эту
ошибку. При ошибке GoTo 0 сбрасывается, поэтому ошибки возникают в любых
строках кода ниже.
Примечание. Когда метод ShowAllData упоминается как элемент листа, он НЕ очищает фильтры, которые применяются к таблицам Excel (ListObjects), если в таблице не выбрана ячейка. Поэтому лучше всего использовать приведенный ниже код для таблиц.
Чтобы очистить все фильтры таблицы Excel (ListObject), мы
также используем метод ShowAllData. В этом случае ShowAllData является членом
свойства AutoFilter объекта ListObject.
Sub Clear_All_Filters_Table() Dim lo As ListObject ' Установить ссылку на первую таблицу на листе Set lo = Sheet1.ListObjects(1) ' Очистить все фильтры для всей таблицы lo.AutoFilter.ShowAllData End Sub
Очистить все фильтры во всех таблицах на листе
Приведенный выше код удаляет фильтры только для одной
таблицы. Мы можем просмотреть таблицы на листе, чтобы удалить все фильтры из
каждой таблицы.
Sub Clear_All_Table_Filters_On_Sheet() Dim lo As ListObject ' Перебрать все таблицы на листе For Each lo In Sheet1.ListObjects ' Очистить все фильтры для всей таблицы lo.AutoFilter.ShowAllData Next lo End Sub
Очистить фильтры в одной колонке
Чтобы очистить фильтры для одного столбца, мы используем
метод AutoFilter. Мы ссылаемся только на параметр Field и устанавливаем
значение для номера столбца, который мы хотим очистить.
Sub Clear_Column_Filter_Range() ' Чтобы очистить фильтр от одного столбца, укажите ' Только номер поля и никаких других параметров Sheet1.Range("B3:G1000").AutoFilter Field:=4 End Sub
Поле — это номер столбца диапазона, к которому применяются
фильтры, а не номер столбца рабочего листа.
Тот же метод используется для очистки фильтров, примененных
к столбцу в таблице. В этом случае метод AutoFilter является членом объекта
Range объекта ListObject.
Sub Clear_Column_Filter_Table() Dim lo As ListObject ' Установить ссылку на первую таблицу на листе Set lo = Sheet1.ListObjects(1) ' Очистить фильтр в столбце одной таблицы, ' указав только параметр поля lo.Range.AutoFilter Field:=4 End Sub
Фильтры и типы данных
Параметры
раскрывающегося меню фильтра изменяются в зависимости от типа данных в столбце.
У нас есть разные фильтры для текста, чисел, дат и цветов. Это создает МНОГО
различных комбинаций операторов и критериев для каждого типа фильтра.
Я создал отдельные статьи для каждого из этих типов фильтров. Статьи содержат пояснения и примеры кода VBA.
- Как фильтровать числа с помощью VBA
- Как отфильтровать пустые и непустые ячейки
- Как фильтровать текст с помощью VBA
- Как отфильтровать даты по VBA
- Как отфильтровать цвета и значки с помощью VBA
Файл в разделе загрузок выше содержит все эти примеры кода в одном месте. Вы можете добавить его в свою личную книгу макросов и использовать макросы в своих проектах.
Пожалуйста, оставьте
комментарий ниже с любыми вопросами или предложениями. Спасибо!
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
Bottom line: Learn how to clear all filters, and filters on a single column with VBA macros. Includes code examples for regular ranges and Excel Tables.
Skill level: Intermediate
Download the File
The Excel file that contains the code can be downloaded below. This file contains code for filtering different data types and filter types. Please see my article on The Ultimate Guide to AutoFilters in VBA for more details.
Clear All Filters from a Range
We use the ShowAllData method to clear all filters applied to a range.
This is the same as clicking the Clear button on the Data tab of the ribbon (keyboard shorcut: Alt, A, C)
Only one filter range can be applied to a worksheet, so we are actually clearing the filters on the sheet.
Sub Clear_All_Filters_Range()
'To Clear All Fitlers use the ShowAllData method for
'for the sheet. Add error handling to bypass error if
'no filters are applied. Does not work for Tables.
On Error Resume Next
Sheet1.ShowAllData
On Error GoTo 0
End Sub
ShowAllData Method Error
If there are no filters are applied to any column, then the ShowAllData method will raise an error. It’s a Run-time ‘1004′ error with the description: Method ‘ShowAllData’ of object ‘_Worksheet’ failed.
The On Error Resume Next line will bypass that error. On Error GoTo 0 resets that so errors are raised in any lines of code below.
Note: When the ShowAllData method is referenced as a member of the sheet, it does NOT clear filters that are applied to Excel Tables (ListObjects) unless a cell is selected in the Table. Therefore, it’s best to use the code below for Tables.
Clear All Filters from an Excel Table
To clear all filters on an Excel Table (ListObject) we also use the ShowAllData method. In this case, ShowAllData is a member of the AutoFilter property of the ListObject object.
Sub Clear_All_Filters_Table()
Dim lo As ListObject
'Set reference to the first Table on the sheet
Set lo = Sheet1.ListObjects(1)
'Clear All Filters for entire Table
lo.AutoFilter.ShowAllData
End Sub
Clear All Filter from All Tables on a Sheet
The code above will only clear filters for a single Table. We can loop through the Tables on the sheet to clear all filters from each Table.
Sub Clear_All_Table_Filters_On_Sheet()
Dim lo As ListObject
'Loop through all Tables on the sheet
For Each lo In Sheet1.ListObjects
'Clear All Filters for entire Table
lo.AutoFilter.ShowAllData
Next lo
End Sub
Clear Filters on a Single Column
To clear filters on a single column we use the AutoFilter method. We only reference the Field parameter and set the value to the number of the column we want to clear.
Sub Clear_Column_Filter_Range()
'To clear the filter from a Single Column, specify the
'Field number only and no other parameters
Sheet1.Range("B3:G1000").AutoFilter Field:=4
End Sub
The Field is the column number of the range the filters are applied to, NOT the column number of the worksheet.
The same technique is use to clear filters applied to a column in a Table. In this case the AutoFilter method is a member of the Range object of the ListObject.
Sub Clear_Column_Filter_Table()
Dim lo As ListObject
'Set reference to the first Table on the sheet
Set lo = Sheet1.ListObjects(1)
'Clear filter on Single Table Column
'by specifying the Field parameter only
lo.Range.AutoFilter Field:=4
End Sub
Filters & Data Types
The filter drop-down menu options change based on what type of data is in the column. We have different filters for text, numbers, dates, and colors. This creates A LOT of different combinations of Operators and Criteria for each type of filter.
I created separate posts for each of these filter types. The posts contain explanations and VBA code examples.
- How to Filter for Blank & Non-Blank Cells
- How to Filter for Text with VBA
- How to Filter for Numbers with VBA
- How to Filter for Dates with VBA
- How to Filter for Colors & Icons with VBA
The file in the downloads section above contains all of these code samples in one place. You can add it to your Personal Macro Workbook and use the macros in your projects.
Please leave a comment below with any questions or suggestions. Thanks! 🙂
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!
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
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
Добрый день!
Подскажите какой должен быть макрос чтобы снять все фильтра умной таблицы Ексель 2007.
Я записал с помощью рекордера:
Private Sub CommandButton1_Click()
ActiveSheet.ListObjects(«Таблица1»).Range.AutoFilter Field:=2, Criteria1:= _
«Столбец 1»
End Sub
Private Sub CommandButton2_Click()
ActiveSheet.ListObjects(«Таблица1»).Range.AutoFilter Field:=2, Criteria1:= _
«Столбец 2»
End Sub
Private Sub CommandButton3_Click()
ActiveSheet.ListObjects(«Таблица1»).Range.AutoFilter Field:=2, Criteria1:= _
«Столбец 3»
End Sub
Но, если столбцов таблицы много, то он достаточно долго выполняется. Есть альтернатива?
I have a short piece of code to reset the filters applied to the columns on my worksheet.
Sub ResetFilters()
If ActiveSheet.FilterMode Then
Cells.AutoFilter
End If
End Sub
When I click the command button to run the macro, it works but the ‘Reset Filters’ command button disappears and the rest that I have on the sheet all stack up in the top left hand corner of the worksheet. They all have ‘Don’t move or size with cells’ set as their property but they still move…
Command Buttons — Before resetting filters
Command Buttons — After resetting
When I enter Design Mode, the ‘Reset Filters’ button reappears in the correct place… I am very confused — does anyone have any advice they can offer?
EDIT (14/06 16:41) — I have discovered that if I sort the data into ascending or descending order, the buttons stay where they are when I reset the filters. They only move if I have filtered out some of the data.
EDIT (14/06 17:58) — I have included a screenshot of what I am working with so that my filtering needs are clearer! I work in a school and teachers will analyse their data with this tool. They can filter any of the columns to analyse results and progress of specific children based on their characteristics or assessment results. As they can filter or sort many columns, it can be hard to reset the data without missing a column. I would like to add a ‘Reset’ button to make this job easier. (I will now likely add these to the ribbon as I have just created a bespoke school tab for this tool so that will remove the issue of the moving buttons. However, if there is a better method of resetting the filters, I would love to learn it.)
Screenshot of the data analysis tool
Many thanks.