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

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

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

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.

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

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

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!

Добрый день!  

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Sub objedinenie()
Const strStartDir = "c:test" 'ïàïêà, ñ êîòîðîé íà÷àòü îáçîð ôàéëîâ
Const strSaveDir = "c:testresult" 'ïàïêà, â êîòîðóþ áóäåò ïðåäëîæåíî ñîõðàíèòü ðåçóëüòàò
Const blInsertNames = True 'âñòàâëÿòü ñòðîêó çàãîëîâêà (êíèãà, ëèñò) ïåðåä ñîäåðæèìûì ëèñòà
 
Dim wbTarget As New Workbook, wbSrc As Workbook, shSrc As Worksheet, shTarget As Worksheet, arFiles, _
i As Integer, stbar As Boolean, clTarget As Range
 
On Error Resume Next 'åñëè óêàçàííûé ïóòü íå ñóùåñòâóåò, îáçîð íà÷íåòñÿ ñ ïóòè ïî óìîë÷àíèþ
ChDir strStartDir
On Error GoTo 0
With Application 'ìåíüøå ïèñàíèíû
arFiles = .GetOpenFilename("Excel Files (*.xlsx), *.xlsx", , "Îáúåäèíèòü ôàéëû", , True)
If Not IsArray(arFiles) Then End 'åñëè íå âûáðàíî íè îäíîãî ôàéëà
Set wbTarget = Workbooks.Add(template:=xlWorksheet)
Set shTarget = wbTarget.Sheets(1)
.ScreenUpdating = False
stbar = .DisplayStatusBar
.DisplayStatusBar = True
 
For i = 1 To UBound(arFiles)
.StatusBar = "Îáðàáîòêà ôàéëà " & i & " èç " & UBound(arFiles)
Set wbSrc = Workbooks.Open(arFiles(i), ReadOnly:=True)
For Each shSrc In wbSrc.Worksheets
If IsNull(shSrc.UsedRange.Text) Then 'ëèñò íå ïóñòîé
Set clTarget = shTarget.Range("A1").Offset(shTarget.Range("A1").SpecialCells(xlCellTypeLastCell).Row, 0)
If blInsertNames Then
clTarget = ">>> " & wbSrc.Name & " -- " & shSrc.Name
Set clTarget = clTarget.Offset(1, 0)
End If
shSrc.UsedRange.Copy clTarget
End If
Next
wbSrc.Close False 'çàêðûòü áåç çàïðîñà íà ñîõðàíåíèå
Next
.ScreenUpdating = True
.DisplayStatusBar = stbar
.StatusBar = False
 
On Error Resume Next 'åñëè óêàçàííûé ïóòü íå ñóùåñòâóåò è åãî íå óäàåòñÿ ñîçäàòü,
'îáçîð íà÷íåòñÿ ñ ïîñëåäíåé èñïîëüçîâàííîé ïàïêè
If Dir(strSaveDir, vbDirectory) = Empty Then MkDir strSaveDir
ChDir strSaveDir
On Error GoTo 0
arFiles = .GetSaveAsFilename("Result", "Excel Files (*.xlsx), *.xlsx", , "Ñîõðàíèòü îáúåäèíåííóþ êíèãó")
 
If VarType(arFiles) = vbBoolean Then 'åñëè íå âûáðàíî èìÿ
GoTo save_err
Else
On Error GoTo save_err
wbTarget.SaveAs arFiles
End If
End
save_err:
MsgBox "Êíèãà íå ñîõðàíåíà!", vbCritical
End With
End Sub

Предположим, вы создали несколько фильтров на разных листах в книге 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 удалить строку в listbox
  • Vba excel удалить содержимое ячеек