Фильтр vba excel примеры

Фильтрация одномерного массива в VBA Excel с помощью функции Filter. Синтаксис и параметры функции Filter. Пример фильтрации одномерного массива.

Filter – это функция, которая возвращает массив, содержащий строки исходного одномерного массива, соответствующие заданным условиям фильтрации.

Примечания

  • исходный (фильтруемый) массив должен быть одномерным и содержать строки;
  • индексация возвращенного массива начинается с нуля;
  • возвращенный массив содержит ровно столько элементов, сколько строк исходного массива соответствуют заданным условиям фильтрации;
  • переменная, которой присваивается возвращенный массив, должна быть универсального типа (As Variant) и объявлена не как массив (не myArray() со скобками, а myArray без скобок).

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

Синтаксис

Filter(sourcearray, match, [include], [compare])

Параметры

Параметр Описание
sourcearray Обязательный параметр. Одномерный массив, элементы которого требуется отфильтровать
match Обязательный параметр. Искомая строка.
include Необязательный параметр. Значение Boolean, которое указывает:

  • True – возвращаются строки, содержащие match (значение по умолчанию);
  • False – возвращаются строки, не содержащие match.
compare Необязательный параметр. Числовое значение (константа), указывающее тип сравнения строк. По умолчанию – 0 (vbBinaryCompare).

Compare (значения)

Параметр compare может принимать следующие значения:

Константа Значение Описание
vbUseCompareOption -1 используется тип сравнения, заданный оператором Option Compare
vbBinaryCompare 0 выполняется двоичное сравнение (регистр имеет значение)
vbTextCompare 1 выполняется текстовое сравнение (без учета регистра)

Пример фильтрации

Фильтрация списка в столбце «A» по словам, начинающимся с буквы «К», и загрузка результатов в столбец «B»:

Пример кода VBA Excel с функцией Filter:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub Primer()

    Dim arr1, arr2, arr3, i As Long

    ‘Присваиваем переменной arr1 массив значений столбца A

    arr1 = Range(«A1:A» & Range(«A1»).End(xlDown).Row)

    ‘Копируем строки двумерного массива arr1 в одномерный arr2

    ReDim arr2(1 To UBound(arr1))

        For i = 1 To UBound(arr1)

            arr2(i) = arr1(i, 1)

        Next

    ‘Фильтруем строки массива arr2 по вхождению подстроки «К»

    ‘и присваиваем отфильтрованные строки переменной arr3

    arr3 = Filter(arr2, «К»)

    ‘Копируем строки из массива arr3 в столбец «B»

        For i = 0 To UBound(arr3)

            Cells(i + 1, 2) = arr3(i)

        Next

End Sub

In this Article

  • Advanced Filter Syntax
  • Filtering Data In Place
  • Resetting the data
  • Filtering Unique Values
  • Using the CopyTo argument
  • Removing Duplicates from the data

This tutorial will explain the how to use the Advanced Filter method in VBA

Advanced Filtering in Excel is very useful when dealing with large quantities of data where you want to apply a variety of filters at the same time.  It can also be used to remove duplicates from your data.  You need to be familiar with creating an Advanced Filter in Excel before attempting to create an Advanced Filter from within VBA.

Consider the following worksheet.

vba advanced filtering database

You can see at a glance that there are duplicates that you might wish to remove.  The Type of account is a mixture of Saving, Term Loan and Check.

First you need to set up a criteria section for the advanced filter.  You can do this in a separate sheet.

vba advanced filtering criteriasheet

For ease of reference, I have named my data sheet ‘Database’ and my criteria sheet ‘Criteria’.

Advanced Filter Syntax

Expression.AdvancedFilter Action, CriteriaRange, CopyToRange, Unique

vba advanced filtering syntax

  • The Expression represents the range object – and can be set as a Range (eg Range(“A1:A50”) – or the Range can be assigned to a variable and that variable can be used.
  • The Action argument is required and will either be xlFilterInPlace or xlFilterCopy
  • The Criteria Range argument  is where you are getting the Criteria to filter from (our Criteria sheet above).  This is optional as you would not need a criteria if you were filtering for unique values for example.
  • The CopyToRange argument  is where you are going to put your filter results – you can filter in place or you can have your filter result copied to an alternative location.  This is also an optional argument.
  • The Unique argument is also optional – True is to filter on unique records only, False is to filter on all the records that meet the criteria – if you omit this, the default will be False.

Filtering Data In Place

Using the criteria shown above in the criteria sheet – we want to find all the accounts with a type of ‘Savings’ and ‘Current’.   We are filtering in place.

Sub CreateAdvancedFilter()
   Dim rngDatabase As Range
   Dim rngCriteria As Range
'define the database and criteria ranges
   Set rngDatabase = Sheets("Database").Range("A1:H50")
   Set rngCriteria = Sheets("Criteria").Range("A1:H3")
'filter the database using the criteria
   rngDatabase.AdvancedFilter xlFilterInPlace, rngCriteria
End Sub

vba advanced filtering in place

The code will hide the rows that do not meet the criteria.

In the above VBA procedure, we did not include the CopyToRange or Unique arguments.

Resetting the data

Before we run another filter, we have to clear the current one.  This will only work if you have filtered your data in place.

Sub ClearFilter()
   On Error Resume Next
'reset the filter to show all the data
   ActiveSheet.ShowAllData
End Sub

Filtering Unique Values

In the procedure below, I have included the Unique argument but omitted the CopyToRange argument.  If you leave this argument out, you EITHER have to put a comma as a place holder for the argument

Sub UniqueValuesFilter1()
   Dim rngDatabase As Range
   Dim rngCriteria As Range
'define the database and criteria ranges
   Set rngDatabase = Sheets("Database").Range("A1:H50")
   Set rngCriteria = Sheets("Criteria").Range("A1:H3")
'filter the database using the criteria
   rngDatabase.AdvancedFilter xlFilterInPlace, rngCriteria,,True
End Sub

OR you need to use named arguments as shown below.

Sub UniqueValuesFilter2()
   Dim rngDatabase As Range
   Dim rngCriteria As Range
'define the database and criteria ranges
   Set rngDatabase = Sheets("Database").Range("A1:H50")
   Set rngCriteria = Sheets("Criteria").Range("A1:H3")
'filter the database using the criteria
   rngDatabase.AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:=rngCriteria, Unique:=True
End Sub

Both of the code examples above will run the same filter, as shown below – the data with only unique values.

vba advanced filtering unique

Using the CopyTo argument

Sub CopyToFilter() 
   Dim rngDatabase As Range 
   Dim rngCriteria As Range 
'define the database and criteria ranges 
   Set rngDatabase = Sheets("Database").Range("A1:H50") 
   Set rngCriteria = Sheets("Criteria").Range("A1:H3") 
'copy the filtered data to an alternative location
    rngDatabase.AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=rngCriteria, CopyToRange:=Range("N1:U1"), Unique:=True
End Sub

Note that we could have omitted the names of the arguments in the Advanced Filter line of code, but using named arguments does make the code easier to read and understand.

This line below is identical to the line in the procedure shown above.

rngDatabase.AdvancedFilter xlFilterCopy, rngCriteria, Range("N1:U1"), True

Once the code is run, the original data is still shown with the filtered data shown in the destination location specified in the procedure.

vba advanced filtering copy to location

Removing Duplicates from the data

We can remove duplicates from the data by omitting the Criteria argument, and copying the data to a new location.

Sub RemoveDuplicates()
   Dim rngDatabase As Range
'define the database
   Set rngDatabase = Sheets("Database").Range("A1:H50")
'filter the database to a new range with unique set to true
rngDatabase.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("N1:U1"), Unique:=True
End Sub

vba filtering remove duplicates

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!
vba save as

Learn More!

На чтение 11 мин. Просмотров 34.4k.

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

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

Automate Filters with VBA Macros - AutoFilter Guide

Содержание

  1. Скачать файл
  2. Написание макросов для фильтров
  3. Макро-рекордер — твой друг (или враг)
  4. Метод автофильтрации
  5. Написание кода автофильтра
  6. Автофильтр не является дополнением
  7. Как установить номер поля динамически
  8. Используйте таблицы Excel с фильтрами
  9. Фильтры и типы данных
  10. Почему метод автофильтрации такой сложный?

Скачать файл

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

VBA AutoFilters Guide.xlsm (100.5 KB)

Написание макросов для фильтров

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

How Often Do You Apply Excel Filters

Фильтрация также может быть трудоемким процессом. Особенно,
когда мы применяем фильтры к нескольким столбцам на больших листах или фильтруем
данные, чтобы затем копировать / вставлять их в другие листы или книги.

В этой статье объясняется, как создавать макросы для
автоматизации процесса фильтрации. Это обширное руководство по методу
автофильтра в VBA.

У меня также есть статьи с примерами для различных фильтров и типов данных, в том числе: пробелы, текст, числа, даты, цвета и значки, и очищающие фильтры.

Макро-рекордер — твой друг (или враг)

Мы можем легко получить код VBA для фильтров, включив
макро-рекордер, а затем применив один или несколько фильтров к диапазону /
таблице.

Вот шаги для создания макроса фильтра с помощью устройства
записи макросов:

  1. Включите рекордер макросов:
    1. Вкладка «Разработчик»> «Запись макроса».
    2. Дайте макросу имя, выберите, где вы хотите сохранить код, и нажмите ОК.
  2. Примените один или несколько фильтров, используя раскрывающиеся меню фильтров.
  3. Остановите рекордер.
  4. Откройте редактор VB (вкладка «Разработчик»> Visual Basic) для просмотра кода.

Если вы уже использовали макрос-рекордер для этого процесса,
то вы знаете, насколько он может быть полезен. Тем более, что наши критерии
фильтрации становятся более сложными.

Код будет выглядеть примерно так:

Sub Filters_Macro_Recorder()
'
' Filters_Macro_Recorder Macro
'

'
    ActiveSheet.ListObjects("tblData").Range.AutoFilter Field:=4, Criteria1:= _
        "Product 2"
    ActiveSheet.ListObjects("tblData").Range.AutoFilter Field:=4
    ActiveSheet.ListObjects("tblData").Range.AutoFilter Field:=5, Criteria1:= _
        ">=500", Operator:=xlAnd, Criteria2:="<=1000"
End Sub

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

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

Метод автофильтрации

Метод AutoFilter используется для очистки и применения
фильтров к одному столбцу в диапазоне или таблице в VBA. Он автоматизирует
процесс применения фильтров через выпадающие меню фильтров и делает, чтобы  все работало.

VBA AutoFilter Automates Filter Drop-down Menus

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

Написание кода автофильтра

Вот пошаговые инструкции по написанию строки кода для автофильтра.

Шаг 1: Ссылка на диапазон или таблицу

Метод AutoFilter является частью объекта Range. Поэтому мы
должны ссылаться на диапазон или таблицу, к которым применяются фильтры на
листе. Это будет весь диапазон, к которому применяются фильтры.

AutoFilter Method is Member of Range Object

Следующие примеры включают / отключают фильтры в диапазоне B3: G1000 на листе автофильтра.

Sub AutoFilter_Range()
'Автофильтр является членом объекта Range
  
  'Ссылка на весь диапазон, к которому применяются фильтры
  'Автофильтр включает / выключает фильтры, когда параметры не указаны.
  Sheet1.Range("B3:G1000").AutoFilter
  
  'Полностью квалифицированный справочник, начиная с уровня Workbook
  ThisWorkbook.Worksheets("AutoFilter Guide").Range("B3:G1000").AutoFilter

End Sub

Вот пример использования таблиц Excel.

Sub AutoFilter_Table()
'Автофильтры на таблицах работают одинаково.

Dim lo As ListObject 'Excel Table

  'Установить переменную ListObject (Table)
  Set lo = Sheet1.ListObjects(1)
  
  'Автофильтр является членом объекта Range
  'Родителем объекта Range является объект List
  lo.Range.AutoFilter
  
End Sub

Метод AutoFilter имеет 5 необязательных параметров, которые
мы рассмотрим далее. Если мы не укажем ни один из параметров, как в приведенных
выше примерах, метод AutoFilter включит / выключит фильтры для указанного
диапазона. Это переключение. Если фильтры включены, они будут выключены, и
наоборот.

Диапазоны или таблицы?

Фильтры работают одинаково как для обычных диапазонов, так и для таблиц
Excel
.

AutoFilter on Regular Range or Excel Table

Я отдаю предпочтение методу использования таблиц, потому что
нам не нужно беспокоиться об изменении ссылок на диапазон при увеличении или
уменьшении таблицы. Однако код будет одинаковым для обоих объектов. В остальных
примерах кода используются таблицы Excel, но вы можете легко изменить это для
обычных диапазонов.

5 (или 6) параметров автофильтра

Метод
AutoFilter имеет 5 (или 6) необязательных параметров, которые используются для
указания критериев фильтрации для столбца. Вот список параметров.

AutoFilter Parameters Optional Screentip in VB Editor VBA

Фильтры на VBA (AutoFilter Method) читать подробное руководство

Страница справки MSDN

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

Шаг 2: Параметр поля

Первый параметр — это Field. Для параметра Field мы указываем число, которое является номером столбца, к которому будет применяться фильтр. Это номер столбца в диапазоне фильтра, который является родителем метода AutoFilter. Это НЕ номер столбца на рабочем листе.

В приведенном ниже примере поле 4 является столбцом
«Продукт», поскольку это 4-й столбец в диапазоне фильтра / таблице.

Field Parameter Value is Column Number of the Range or Table

Фильтр столбца очищается, когда мы указываем только параметр
Field, а другие критерии отсутствуют.

Field Parameter Only Clears Single Column Filter

Мы также можем использовать переменную для параметра Field и
установить ее динамически. Я объясню это более подробно ниже.

Шаг 3: Параметры критериев

Существует два параметра, которые можно использовать для указания фильтра Критерии, Criteria1 и Criteria2 . Мы используем комбинацию этих параметров и параметра Operator для разных типов фильтров. Здесь все становится сложнее, поэтому давайте начнем с простого примера.

'Фильтровать столбец «Продукт» для одного элемента
lo.Range.AutoFilter Field:=4, Criteria1:="Product 2"

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

VBA AutoFilter Code to Filter for Single Item in Filter Drop-down Menu

Общие правила для Criteria1 и Criteria2

Значения, которые мы указываем для Criteria1 и Criteria2,
могут быть хитрыми. Вот несколько общих рекомендаций о том, как ссылаться на
значения параметра Criteria.

  • Значением критерия является строка, заключенная в кавычки. Есть несколько исключений, когда критерии являются постоянными для периода времени даты и выше / ниже среднего.
  • При указании фильтров для отдельных чисел или дат форматирование чисел должно соответствовать форматированию чисел, применяемому в диапазоне / таблице.
  • Оператор сравнения больше / меньше чем также включен в кавычки перед числом.
  • Кавычки также используются для фильтров для пробелов «=» и не пробелов «<>».

General Rules for Criteria Parameters

'Фильтр на дату, большую или равную 1 января 2015 г.
lo.Range.AutoFilter Field:=1, Criteria1:=">=1/1/2015"

' Оператор сравнения> = находится внутри кавычек
' для параметра Criteria1.

' Форматирование даты в коде соответствует форматированию
' применяется к ячейкам на листе.

Шаг 4: Параметр оператора

Что если мы хотим выбрать несколько элементов из
раскрывающегося списка фильтров? Или сделать фильтр для диапазона дат или
чисел?

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

Фильтры на VBA (AutoFilter Method) читать подробное руководство

Вот ссылка на страницу справки MSDN, которая содержит список констант для перечисления XlAutoFilterOperator.

Operator используется в сочетании с Criteria1 и / или Criteria2, в зависимости от типа данных и типа фильтра. Вот несколько примеров.

'Фильтр для списка нескольких элементов, оператор - xlFilterValues
lo.Range.AutoFilter _
          Field:=iCol, _
          Criteria1:=Array("Product 4", "Product 5", "Product 6"), _
          Operator:=xlFilterValues
'Фильтр для диапазона дат (между датами), оператор xlAnd
lo.Range.AutoFilter _
          Field:=iCol, _
          Criteria1:=">=1/1/2014", _
          Operator:=xlAnd, _
          Criteria2:="<=12/31/2015"

Это основы написания строки кода для метода AutoFilter. Будет сложнее с различными типами данных.

Итак, я привел много примеров ниже, которые содержат большинство комбинаций критериев и операторов для разных типов фильтров.

Автофильтр не является дополнением

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

Это означает, что это не дополнение. Следующие 2 строки НЕ создадут фильтр для Продукта 1 и Продукта 2. После запуска макроса столбец Продукт будет отфильтрован только для Продукта 2.

'Автофильтр НЕ ДОБАВЛЯЕТ. Это сначала любые фильтры, применяемые
'в столбце перед применением нового фильтра
lo.Range.AutoFilter Field:=4, Criteria1:="Product 3"
  
'Эта строка кода отфильтрует столбец только для продукта 2
'Фильтр для Продукта 3 выше будет очищен при запуске этой линии.
lo.Range.AutoFilter Field:=4, Criteria1:="Product 2"

Если вы хотите применить фильтр с несколькими критериями к одному столбцу, вы можете указать это с помощью параметров
Criteria и Operator .

Как установить номер поля динамически

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

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

Use Variable for Filter Field Column Number in VBA with Index Property

Sub Dynamic_Field_Number()
'Методы, чтобы найти и установить поле на основе имени столбца.
  
Dim lo As ListObject
Dim iCol As Long
  
  'Установить ссылку на первую таблицу на листе
  Set lo = Sheet1.ListObjects(1)
  
  'Установить поле фильтра
  iCol = lo.ListColumns("Product").Index
  
  'Использовать функцию соответствия для регулярных диапазонов
  'iCol = WorksheetFunction.Match("Product", Sheet1.Range("B3:G3"), 0)

  'Использовать переменную для значения параметра поля
  lo.Range.AutoFilter Field:=iCol, Criteria1:="Product 3"

End Sub

Номер столбца будет найден при каждом запуске макроса. Нам
не нужно беспокоиться об изменении номера поля при перемещении столбца. Это
экономит время и предотвращает ошибки (беспроигрышный вариант)!

Используйте таблицы Excel с фильтрами

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

  • Нам не нужно переопределять диапазон в VBA, поскольку диапазон данных изменяет размер (строки / столбцы добавляются / удаляются). На всю таблицу ссылается объект ListObject.
  • Данные в таблице легко ссылаться после применения фильтров. Мы можем использовать свойство DataBodyRange для ссылки на видимые строки для копирования / вставки, форматирования, изменения значений и т.д.
  • Мы можем иметь несколько таблиц на одном листе и, следовательно, несколько диапазонов фильтров. С обычными диапазонами у нас может быть только один отфильтрованный диапазон на лист.
  • Код для очистки всех фильтров в таблице легче написать.

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

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

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

  • Как очистить фильтры с помощью VBA
  • Как отфильтровать пустые и непустые клетки
  • Как фильтровать текст с помощью VBA
  • Как фильтровать числа с помощью VBA
  • Как отфильтровать даты с помощью VBA
  • Как отфильтровать цвета и значки с помощью VBA

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

Почему метод автофильтрации такой сложный?

Этот пост был вдохновлен вопросом от Криса, участника The
VBA Pro Course. Комбинации Критерии и Операторы могут быть запутанными и
сложными. Почему это?

Ну, фильтры развивались на протяжении многих лет. Мы увидели много новых типов фильтров, представленных в Excel 2010, и эта функция продолжает улучшаться. Однако параметры метода автофильтра не изменились. Они отлично подходят для совместимости со старыми версиями, но также означает, что новые типы фильтров работают с существующими параметрами.

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

Я надеюсь, что вы можете использовать эту статью и файл Excel в качестве руководства по написанию макросов для фильтров. Автоматизация фильтров может сэкономить нам и нашим пользователям массу времени, особенно при использовании этих методов в более крупном проекте автоматизации данных.

Excel VBA Filter

VBA Filter tool one can use to sort out or fetch the specific data desired. For example, one can use the Autofilter function as a worksheet function. However, this function has other arguments with it which are optional, and the only mandatory argument is the expression that covers the range. For example, worksheets(“Sheet1”).Range(“A1”).Autofilter will apply the filter on the first column.

Filter in VBA works the same way it works in the worksheet. The only thing different is we can automate the routine task of filtering the data through coding.

Table of contents
  • Excel VBA Filter
    • Examples to Filter Data using VBA
      • Example #1 – Apply or Remove Filter to the Data
        • Step 1: Supply data range
        • Step 2: Then access AutoFilter function
        • Step 3: Run the code to enable the filter
      • Example #2 – Filter Specific Values
        • Step 1: Select Range and Open Autofilter Function
        • Step 2: Then Select Field
        • Step 3: Now Mention Criteria
        • Step 4: And run the code
      • Example #3 – Usage of OPERATOR Argument
        • Step 1: Select Range and Autofilter Field
        • Step 2: Enter Criteria 1 as Math
        • Step 3: Use Operator xl
        • Step 4: Enter Criteria 2 as Politics
      • Example #4 – Filter Numbers with Operator Symbols
      • Example #5 – Apply Filter for More Than One Column
    • Things to Remember
    • Recommended Articles

VBA-Filter

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Filter Data (wallstreetmojo.com)

The AutoFilter is a function that includes many syntax values. Below are the parameters involved in the AutoFilter function.

AutoFilter Syntax

  • The range is the first thing we need to supply to use the “AutoFilter” option. After that, it is simply for which range of cells we need to apply the filter, for example, Range (“A1:D50”).
  • The field is the first argument in the function. Once we select the range of cells through the VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more, we need to mention for which column of the range we want to apply the filter for.
  • Criteria 1 is nothing, but in the selected Field, the value that you want to filter out.
  • The operator we may use if we want to use the Criteria 2 argument. In this option, we can use the below options.
    xlAnd, xlOr, xlBottom10Items, xlTop10Items, xlTop10Percent, xlBottom10Percent, xlFilterCellColor, xlFilterDynamic, xlFilterFontColor, xlFilterIcon, xlFilterValues
  • Visible Dropdown displays a filter symbol in the filter applied column. If you want to display it, you can supply the argument as TRUE or else FALSE.

Examples to Filter Data using VBA

You can download this VBA Filter Excel Template here – VBA Filter Excel Template

Example #1 – Apply or Remove Filter to the Data

If you want to apply the filter option to the data, then we can turn it off and on this option. For example, look at the below data image.

Remove Filter to Data 1

Step 1: Supply data range

To activate the filter option first, we need to supply what is our data range. For example, in the above image, our data is spread from A1 to G31. So, supply this range using a RANGE object.

Code:

Sub Filter_Example()

  Range ("A1:G31")

End Sub

Remove Filter to Data 1-1

Step 2: Then access AutoFilter function

Now, access the AutoFilter function for this range.

Code:

Sub Filter_Example()

  Range("A1:G31").AutoFilter

End Sub

Remove Filter to Data 1-2

Step 3: Run the code to enable the filter

That is all. Run this code to enable the AutoFilter.

Remove Filter to Data 1-3.

This code works as a toggle. If the filter is not applied, it will apply. If already applied, then it will be removed.

Example #2 – Filter Specific Values

Now, we will see how to use the parameters of the AutoFilter option. Take the same data as above. For example, we must filter out all “Male” gender names.

Step 1: Select Range and Open Autofilter Function

Filter Specific Values 1

Step 2: Then Select Field

In the function’s first argument, i.e., Field, we need to mention the column reference we would like to filter out. In this example, we need to filter only “Male” candidates, column “C,” so the column number is 3.

Filter Specific Values 1-1

Step 3: Now Mention Criteria

Now for this supplied Field, we need to mention  Criteria 1, i.e., what value we need to filter in the  Field. We need to filter “Male” from this column.

Code:

Sub Filter_Example()

  Range("A1:G31").AutoFilter Field:=3, Criteria1:="Male"

End Sub

Filter Specific Values 1-2

Step 4: And run the code

Ok, that’s all. So this code will filter only “Male” candidates now.

Filter Specific Values 1-3

Example #3 – Usage of OPERATOR Argument

When you want to filter out more than one value from the column, we need to use the “Operator” argument. For example, from the column “Major,” we need to filter only “Math & Politics,” then we need to use this argument.

Step 1: Select Range and Autofilter Field

First, supply the Range of cells and fields.

Code:

Sub Filter_Example()

 Range("A1:G31").AutoFilter Field:=5,

End Sub

Use of OPERATOR Argument 1

Step 2: Enter Criteria 1 as Math

For the mentioned field, we need to supply Criteria 1 as “Math.”

Code:

Sub Filter_Example()

 Range("A1:G31").AutoFilter Field:=5, Criteria1:="Math",

End Sub

Use of OPERATOR Argument 1-1

Step 3: Use Operator xl

Since we need to filter one more value from the same column or field, use the operator symbol as “xlOr.”

Code:

Sub Filter_Example()

  Range("A1:G31").AutoFilter Field:=5, Criteria1:="Math", 
  Operator:=xlOr

End Sub

Use of OPERATOR Argument 1-2

Step 4: Enter Criteria 2 as Politics

And for Criteria 2 argument, mention the value as “Politics.”

Code:

Sub Filter_Example()

 Range("A1:G31").AutoFilter Field:=5, Criteria1:="Math",
 Operator:=xlOr, Criteria2:="Politics"

End Sub

Use of OPERATOR Argument 1-3

It will filter out both “Math” and “Politics” from column “Major.”

Use Row Function Example 1-6

Example #4 – Filter Numbers with Operator Symbols

For example, if you want to filter numbers, we can filter a specific number and numbers above, below, or between specific values and a range of values.

For example, if you want to filter persons aged more than 30, then we can write the code below from the age column.

Code:

Sub Filter_Example()

 Range("A1:G31").AutoFilter Field:=7, Criteria1:=">30"

End Sub

It will filter all the values that are more than 30.

Excel VBA Filter Numbers 1

Now, if you want to filter values between 21 and 31, we can use the code below.

Code:

Sub Filter_Example()

 Range("A1:G31").AutoFilter Field:=7, Criteria1:=">21", 
 Operator:=xlAnd, Criteria2:="<31"

End Sub

It will filter persons aged between 21 and 30.

Excel VBA Filter Numbers 1-1

Example #5 – Apply Filter for More Than One Column

We need to use a slightly different technique if you want to filter values from more than one column criteria.

If you want to filter “Student Status” as “Graduate” and “Country” as “US,” then first, we need to supply the RANGE of cells under the WITH statement.

Code:

Sub Filter_Example()

  With Range("A1:G31")

  End With

End Sub

Example 5

Inside the WITH statement, supply the first criteria to be filtered.

Code:

Sub Filter_Example()

 With Range("A1:G31")
  .AutoFilter Field:=4, Criteria1:="Graduate"
 End With

End Sub

Example 5-1

Now, in the next line, do the same for “Country” by changing “Field” to six and “Criteria” to “US.”

Code:

Sub Filter_Example()

 With Range("A1:G31")
  .AutoFilter Field:=4, Criteria1:="Graduate"
  .AutoFilter Field:=6, Criteria1:="US"
 End With

End Sub

Example 5-2

Now, this will filter “Graduate” only for the country “US.”

Example 5-3

Things to Remember

  • It will apply the first thing only for the mentioned range of cells filter.
  • The field is nothing in which column you want to filter the data.
  • If filtering values from more than one column, use the With statement.

Recommended Articles

This article is a guide to VBA Filter. Here we learn how to apply a filter to data, some VBA examples, and download an Excel template. Below are some useful Excel articles related to VBA: –

  • VBA AutoFilter
  • VBA Do Loop
  • How to Enable Solver in VBA?
  • Add Filter in Excel
  • VBA Paste Values

VBA Array Filter Function in Excel. The filter function returns an array, which contains subset of string based on specified criteria.

Table of Contents:

  • Objective
  • Syntax of VBA Filter Function in Excel
  • Includes all filtered strings – case sensitive
  • Extract all filtered strings – not a case sensitive
  • Excludes or doesn’t contain filtered string – Case Sensitive
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Here is the Syntax of the Filter Function in Excel VBA.

Filter(SourceArray, Match, [Include], [Compare] ) 

Where SourceArray: Required parameter. The array of strings to be searched. It shouldn’t be null. If it is null then returns an error.
Match: Required parameter. The string to search for.
Include: An optional Boolean parameter. It represents to include or exclude the matching string.
Compare: An optional parameter. It represents type of comparison(Binary or Textual or Database). Default value is ‘0’ i.e vbBinaryCompare.

VBA Constant Value Explanation
vbUseCompareOption -1 Performs a comparison using the ‘option compare’
vbBinaryCompare 0 Performs a Binary comparison
vbTextCompare 1 Performs a Textual comparison
vbDatabaseCompare 2 Microsoft Access only. Performs a comparison based on information in your database.

Includes all filtered strings – case sensitive

Let us see the example vba macro code using array filter function in Excel. In the below example we have specified an array with values. We are filtering or extracting substrings values which are case sensitive.

'Case: Case Sensitive and includes all filtered data
Sub VBA_Array_Filter_Function_Ex1()

    'Variable declaration
    Dim myArray As Variant
    Dim SubStringArray As Variant
    Dim FilterValue As Variant
    
    'Create an Array
    myArray = Array("Sunday", "MonDay", "Tuesday", "WednesDay", "Thursday", "FriDay", "Saturday")
    
    'Etract string contains 'Day' from specified array
    SubStringArray = Filter(myArray, "day")
    'or
    'SubStringArray = Filter(myArray, "day", True)
    'or
    'SubStringArray = Filter(myArray, "day", True,vbBinaryCompare)
    
    'Loop through array values
    For Each FilterValue In SubStringArray
        Debug.Print FilterValue
    Next

End Sub

Here is the screenshot of above vba macro code.

Extract all filtered strings – not a case sensitive

Let us see the example vba macro code using array filter function in Excel. In the below example we have specified an array with values. We are filtering or extracting substrings values which are not a case sensitive.

'Case: Ignores Case Sensitive while filtering data
Sub VBA_Array_Filter_Function_Ex2()

    'Variable declaration
    Dim myArray As Variant
    Dim SubStringArray As Variant
    Dim FilterValue As Variant
    
    'Create an Array
    myArray = Array("Sunday", "MonDay", "Tuesday", "WednesDay", "Thursday", "FriDay", "Saturday")
    
    'Ignores Case Sensitive while filtering data
    SubStringArray = Filter(myArray, "day", True, vbTextCompare)
    
    'Loop through array values
    For Each FilterValue In SubStringArray
        Debug.Print FilterValue
    Next

End Sub

Here is the screenshot of above vba macro code.

Excludes or doesn’t contain filtered string – Case Sensitive

Let us see the example vba macro code using array filter function in Excel. In the below example we have specified an array with values. We are filtering or extracting sub-strings which are not containing specified filter sub-string.

'Case: Excludes or doesn't contain filtered string and Case Sensitive
Sub VBA_Array_Filter_Function_Ex3()

    'Variable declaration
    Dim myArray As Variant
    Dim SubStringArray As Variant
    Dim FilterValue As Variant
    
    'Create an Array
    myArray = Array("Sunday", "MonDay", "Tuesday", "WednesDay", "Thursday", "FriDay", "Saturday")
    
    'Excludes filtered string which contains 'day' from specified array
    SubStringArray = Filter(myArray, "Day", False)
    'or
    'SubStringArray = Filter(myArray, "day", False, vbBinaryCompare)
    
    'Loop through array values
    For Each FilterValue In SubStringArray
        Debug.Print FilterValue
    Next

End Sub

Here is the screenshot of above vba macro code.

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 VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Home / VBA / Top VBA Functions / VBA FILTER Function (Syntax + Example)

The VBA FILTER function is listed under the array category of VBA functions. When you use it in a VBA code, it can return strings from an array of strings based on the string you have specified as a subset. In simple words, it can specify a string and it will look for all those values where that string is a part of the main string.

Filter(SourceArray,Match,[Include],[Compare])

Arguments

  • SourceArray: The array with strings that want to filter.
  • Match: The string you want to filter in the SourceArray.
  • [Include]: This is a Boolean to define if the weather to filter value which includes the Match, or doesn’t include [This is an optional argument and if omitted VBA takes TRUE by default].
  • [Compare]: A string value to define the comparison to make while filtering the array [This is an optional argument and if omitted VBA takes vbBinaryCompare by default].
    • vbBinaryCompare: For binary comparison.
    • vbTextCompare: For text comparison.
    • vbDatabaseCompare: For Database Comparison.

Example

To practically understand how to use the VBA FILTER function, you need to go through the below example where we have written a vba code by using it:

Sub example_FILTER()
Dim nameAry As Variant
Dim myAry(0 To 4) As String
myAry(0) = Range("A1").Value
myAry(1) = Range("A2").Value
myAry(2) = Range("A3").Value
myAry(3) = Range("A4").Value
myAry(4) = Range("A5").Value
nameAry = Filter(myAry, "Sh")
End Sub

In the above code, we have used FILTER to get the value from the array (myAry has values from the cells we have defined) that includes “Sh” in it, and now, “nameAry” includes the “Jay Sh” and “Peter Sh” as both have “Sh” in it.

Notes

  • If the source array which you have supplied is NULL then VBA will return an error.
  • The array returned by the filter will always be a one-dimensional and zero-based array.

Понравилась статья? Поделить с друзьями:
  • Фильтр excel по первой букве
  • Фильтр excel по множеству значений
  • Фильтр excel по количеству слов
  • Фильтр excel по английски
  • Фильтр excel первая строка