Vba excel удалить фильтры

На чтение 4 мин. Просмотров 14.3k.

Итог: узнайте, как очистить все фильтры и фильтры в одном столбце с помощью макросов VBA. Включает примеры кода для регулярных диапазонов и таблиц Excel.

Уровень мастерства: Средний

VBA Code to Clear Filters in Excel

Содержание

  1. Скачать файл
  2. Очистить все фильтры из диапазона
  3. Ошибка метода ShowAllData
  4. Очистить все фильтры из таблицы Excel
  5. Очистить все фильтры во всех таблицах на листе
  6. Очистить фильтры в одной колонке
  7. Фильтры и типы данных

Скачать файл

Файл Excel, содержащий код, можно скачать ниже. Этот файл содержит код для фильтрации различных типов данных и типов фильтров. Пожалуйста, ознакомьтесь с моей статьей Фильтрация сводной таблицы или среза по самой последней дате или периоду для более подробной информации.

VBA AutoFilters Guide.xlsm (100.5 KB)

Очистить все фильтры из диапазона

Мы используем метод ShowAllData, чтобы очистить все фильтры,
примененные к диапазону.

Это аналогично нажатию кнопки «Очистить» на вкладке «Данные»
на ленте (сочетание клавиш: Alt, A, C)

Clear All Filters on Sheet or Table with ShowAllData Method in VBA

К рабочему листу может быть применен только один диапазон
фильтров, поэтому мы на самом деле очищаем фильтры на листе.

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.

VBA Clear Filters Error 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 и устанавливаем
значение для номера столбца, который мы хотим очистить.

Clear Filter on Single Column VBA AutoFilter Method Field Only

Sub Clear_Column_Filter_Range()
  
  ' Чтобы очистить фильтр от одного столбца, укажите
  ' Только номер поля и никаких других параметров
  Sheet1.Range("B3:G1000").AutoFilter Field:=4

End Sub

Поле — это номер столбца диапазона, к которому применяются
фильтры, а не номер столбца рабочего листа.

Field Parameter Value is Column Number of the Range or Table

Тот же метод используется для очистки фильтров, примененных
к столбцу в таблице. В этом случае метод 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

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.

Remove Filters V1.01.xlsb

Remove Filters V1.01.xlsb

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

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

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

VBA Code to Clear Filters in Excel

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)

Clear All Filters on Sheet or Table with ShowAllData Method in VBA

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.

VBA Clear Filters Error 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.

Clear Filter on Single Column VBA AutoFilter Method Field Only

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.

Field Parameter Value is Column Number of the Range or Table

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! 🙂

Добрый день!  

  Подскажите какой должен быть макрос чтобы снять все фильтра умной таблицы Ексель 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  

  Но, если столбцов таблицы много, то он достаточно долго выполняется. Есть альтернатива?

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!

alt text

Learn More!

Содержание

  1. Как очистить фильтры с помощью макросов VBA в Excel
  2. Скачать файл
  3. Очистить все фильтры из диапазона
  4. Ошибка метода ShowAllData
  5. Очистить все фильтры из таблицы Excel
  6. Очистить все фильтры во всех таблицах на листе
  7. Очистить фильтры в одной колонке
  8. Фильтры и типы данных
  9. How to Clear Filters with VBA Macros
  10. Download the File
  11. Clear All Filters from a Range
  12. ShowAllData Method Error
  13. Clear All Filters from an Excel Table
  14. Clear All Filter from All Tables on a Sheet
  15. Clear Filters on a Single Column
  16. Filters & Data Types
  17. Vba excel как снять все фильтры
  18. Как очистить фильтры при открытии, сохранении или закрытии книги в Excel?
  19. Remove Filters in an Excel Sheet using VBA
  20. Downloads

Как очистить фильтры с помощью макросов VBA в Excel

Итог: узнайте, как очистить все фильтры и фильтры в одном столбце с помощью макросов VBA. Включает примеры кода для регулярных диапазонов и таблиц Excel.

Уровень мастерства: Средний

Скачать файл

Файл Excel, содержащий код, можно скачать ниже. Этот файл содержит код для фильтрации различных типов данных и типов фильтров. Пожалуйста, ознакомьтесь с моей статьей Фильтрация сводной таблицы или среза по самой последней дате или периоду для более подробной информации.

VBA AutoFilters Guide.xlsm (100.5 KB)

Очистить все фильтры из диапазона

Мы используем метод ShowAllData, чтобы очистить все фильтры, примененные к диапазону.

Это аналогично нажатию кнопки «Очистить» на вкладке «Данные» на ленте (сочетание клавиш: Alt, A, C)

К рабочему листу может быть применен только один диапазон фильтров, поэтому мы на самом деле очищаем фильтры на листе.

Ошибка метода ShowAllData

Если к любому столбцу не применены фильтры, метод ShowAllData вызовет ошибку. Это ошибка времени выполнения ‘1004 с описанием:
Method ‘ShowAllData’ of object ‘_Worksheet’ failed.

Следующая строка On Error Resume Next будет игнорировать эту ошибку. При ошибке GoTo 0 сбрасывается, поэтому ошибки возникают в любых строках кода ниже.

Примечание. Когда метод ShowAllData упоминается как элемент листа, он НЕ очищает фильтры, которые применяются к таблицам Excel (ListObjects), если в таблице не выбрана ячейка. Поэтому лучше всего использовать приведенный ниже код для таблиц.

Очистить все фильтры из таблицы Excel

Чтобы очистить все фильтры таблицы Excel (ListObject), мы также используем метод ShowAllData. В этом случае ShowAllData является членом свойства AutoFilter объекта ListObject.

Очистить все фильтры во всех таблицах на листе

Приведенный выше код удаляет фильтры только для одной таблицы. Мы можем просмотреть таблицы на листе, чтобы удалить все фильтры из каждой таблицы.

Очистить фильтры в одной колонке

Чтобы очистить фильтры для одного столбца, мы используем метод AutoFilter. Мы ссылаемся только на параметр Field и устанавливаем значение для номера столбца, который мы хотим очистить.

Поле — это номер столбца диапазона, к которому применяются фильтры, а не номер столбца рабочего листа.

Тот же метод используется для очистки фильтров, примененных к столбцу в таблице. В этом случае метод AutoFilter является членом объекта Range объекта ListObject.

Фильтры и типы данных

Параметры раскрывающегося меню фильтра изменяются в зависимости от типа данных в столбце. У нас есть разные фильтры для текста, чисел, дат и цветов. Это создает МНОГО различных комбинаций операторов и критериев для каждого типа фильтра.

Я создал отдельные статьи для каждого из этих типов фильтров. Статьи содержат пояснения и примеры кода VBA.

Файл в разделе загрузок выше содержит все эти примеры кода в одном месте. Вы можете добавить его в свою личную книгу макросов и использовать макросы в своих проектах.

Пожалуйста, оставьте комментарий ниже с любыми вопросами или предложениями. Спасибо!

Источник

How to Clear Filters with VBA Macros

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.

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.

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.

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.

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.

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.

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! 🙂

Источник

Vba excel как снять все фильтры

Как очистить фильтры при открытии, сохранении или закрытии книги в Excel?

Предположим, у вас есть несколько рабочих листов, содержащих отфильтрованные данные в вашей книге. Чтобы очистить все фильтры, вам нужно проверить отфильтрованный список на разных листах, а затем очистить их вручную один за другим. Это раздражает! В этой статье мы покажем вам несколько способов очистки фильтров при открытии, сохранении или закрытии книги в Excel.

Удивительный! Использование эффективных вкладок в Excel, таких как Chrome, Firefox и Safari!
Экономьте 50% своего времени и сокращайте тысячи щелчков мышью каждый день!

В этом разделе рассказывается об очистке фильтров на всех листах при открытии книги. Пожалуйста, сделайте следующее.

1. В книге вам нужно автоматически очищать все фильтры при открытии, пожалуйста, нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окно, пожалуйста, дважды щелкните Эта рабочая тетрадь слева Проекты под застройку панели, а затем скопируйте и вставьте приведенный ниже код VBA в ThisWorkbook (Код) окно. Смотрите скриншот:

Код VBA: очистить все фильтры при открытии книги

3. нажмите другой + Q ключи для выхода из Microsoft Visual Basic для приложений окно.

4. Нажмите Файл > Сохранить как. В всплывающем Сохранить как диалоговом окне укажите папку для сохранения этой книги, назовите ее как вам нужно в Имя файла , затем выберите Excel Macro-Enabled Workbook из файла Сохранить как раскрывающийся список и, наконец, щелкните Сохраните кнопку.

Отныне при открытии этой книги с поддержкой макросов все фильтры в этой книге будут очищаться автоматически.

Вы можете очищать все фильтры из текущей книги каждый раз, когда сохраняете ее.

1. В книге вам необходимо автоматически удалить все фильтры, нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окно, пожалуйста, дважды щелкните Эта рабочая тетрадь слева Проекты под застройку панели, а затем скопируйте и вставьте приведенный ниже код VBA в ThisWorkbook (Код) окно. Смотрите скриншот:

Код VBA: очистить фильтры при сохранении книги

3. Нажмите другой + Q ключи для выхода из Microsoft Visual Basic для приложений окно.

Отныне при сохранении книги все фильтры будут очищаться автоматически.

В последнем разделе мы покажем вам, как очистить все фильтры на листах при закрытии или выходе из книги.

1. Откройте книгу, из которой необходимо автоматически очистить все фильтры, затем нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окно, пожалуйста, дважды щелкните Эта рабочая тетрадь слева Проекты под застройку панели, а затем скопируйте и вставьте приведенный ниже код VBA в ThisWorkbook (Код) окно. Смотрите скриншот:

Код VBA: очистить все фильтры на листах при закрытии / выходе из книги

Внимание: Если вы просто хотите очистить фильтры на текущем листе, используйте приведенный ниже код VBA.

Код VBA: очистить фильтр на активном листе при закрытии книги

3. Нажмите другой + Q ключи для выхода из Microsoft Visual Basic для приложений окно.

С этого момента все фильтры будут очищаться автоматически после нажатия кнопки «Закрыть» в книге.

Источник

Remove Filters in an Excel Sheet using VBA

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 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:

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.

Источник

Предположим, вы создали несколько фильтров на разных листах в книге Excel и теперь хотите очистить все эти фильтры сразу. Обычно вам нужно переходить к листу один за другим, чтобы проверить фильтр, а затем очистить его вручную. Есть ли удобный способ очистить фильтры со всех листов в активной книге? Пожалуйста, попробуйте метод, описанный в этой статье.

Очистить фильтры со всех листов в активной книге с кодом VBA


Очистить фильтры со всех листов в активной книге с кодом VBA

Запустите приведенный ниже сценарий VBA, чтобы очистить фильтры со всех листов в активной книге.

1. В книге, из которой нужно очистить фильтры, нажмите кнопку другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окна, нажмите Вставить > Модули. Затем скопируйте и вставьте приведенный ниже сценарий VBA в окно модуля. См. Снимок экрана ниже:

Код VBA: очистить фильтры со всех листов в активной книге

Sub Clear_fiter()()
'Updated by Extendoffice 20210625
    Dim xAF As AutoFilter
    Dim xFs As Filters
    Dim xLos As ListObjects
    Dim xLo As ListObject
    Dim xRg As Range
    Dim xWs As Worksheet
    Dim xIntC, xF1, xF2, xCount As Integer
    Application.ScreenUpdating = False
    On Error Resume Next
    For Each xWs In Application.Worksheets
        xWs.ShowAllData
        Set xLos = xWs.ListObjects
        xCount = xLos.Count
        For xF1 = 1 To xCount
         Set xLo = xLos.Item(xF1)
         Set xRg = xLo.Range
         xIntC = xRg.Columns.Count
         For xF2 = 1 To xIntC
            xLo.Range.AutoFilter Field:=xF2
         Next
        Next
    Next
    Application.ScreenUpdating = True

End Sub

3. нажмите F5 ключ для запуска кода. Затем все фильтры на всех листах в текущей книге немедленно очищаются.


Статьи по теме:

  • Как очистить кеш фильтра (старые элементы) из сводной таблицы в Excel?
  • Как очистить фильтры при открытии, сохранении или закрытии книги в Excel?
  • Как фильтровать данные по флажку в Excel?
  • Как заполнить ряд чисел в столбце отфильтрованного списка в Excel?

Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (11)


Оценок пока нет. Оцените первым!

Понравилась статья? Поделить с друзьями:
  • Vba excel удалить фильтр
  • Vba excel удалить файл без подтверждения
  • Vba excel удалить условное форматирование
  • Vba excel удалить текст до символа
  • Vba excel удалить строку содержащую