Excel vba array filter

Фильтрация одномерного массива в 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

Return to VBA Code Examples

The VBA Filter Function allows you to quickly filter arrays. There are several settings to consider when filtering arrays. We will discuss them below.

Filter – Match

By default the VBA Filter Function will filter an array for matches. In the example below we will filter the array for matches with “Smith”.

Sub Filter_Match()

    'Define Array
    Dim strNames As Variant
    strNames = Array("Steve Smith", "Shannon Smith", "Ryan Johnson")

    'Filter Array
    Dim strSubNames As Variant
    strSubNames = Filter(strNames, "Smith")
    
    'Count Filtered Array
    MsgBox "Found " & UBound(strSubNames) - LBound(strSubNames) + 1 & " names."

End Sub

A couple important points:

  • The filtered array variable should be declared as data type variant to avoid defining the array size.
  • By default, the Filter function is case sensitive. So filtering on “smith” would give a different result than “Smith”. Below we will show you how to change this setting.

Filter – Case Insensitive

By default, VBA is Case Sensitive. This means that for text to match, the cases must be the same (ex. “smith” does not equal “Smith”). This is true of the Filter Function, as well as all (most?) other VBA functions or comparisons.

Personally, I never want VBA to be case sensitive, so I always add Option Compare Text to the top of all of my code modules. Option Compare Text tells VBA to ignore case so that it’s Case Insensitive:

Option Compare Text

Adding Option Compare Text to the top of your module will make the Filter Function case insensitive. Alternatively, you can tell the Filter Function itself to be case insensitive with the vbTextCompare argument:

strSubNames = Filter(strNames, "smith", , vbTextCompare)

Full example:

Sub Filter_MatchCase()

    'Define Array
    Dim strNames As Variant
    strNames = Array("Steve Smith", "Shannon Smith", "Ryan Johnson")

    'Filter Array
    Dim strSubNames As Variant
    strSubNames = Filter(strNames, "smith", , vbTextCompare)
    
    'Count Filtered Array
    MsgBox "Found " & UBound(strSubNames) - LBound(strSubNames) + 1 & " names."

End Sub

Filter – Does Not Match

The Filter Function can also be used to identify array items that DO NOT match the entered criteria by setting the Include argument to FALSE:

strSubNames = Filter(strNames, "Smith", False)

Full Example:

Sub Filter_NoMatch()

    'Define Array
    Dim strNames As Variant
    strNames = Array("Steve Smith", "Shannon Smith", "Ryan Johnson")

    'Filter Array
    Dim strSubNames As Variant
    strSubNames = Filter(strNames, "Smith", False)
    
    'Count Filtered Array
    MsgBox "Found " & UBound(strSubNames) - LBound(strSubNames) + 1 & " names."

End Sub

Filter Function

vba filter array function

The VBA Filter function returns an Array subset of a supplied string array.

The Filter Function Syntax is:

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

The Function arguments are:

  • SourceArray – The original Array to filter
  • Match – The string to search for
  • [Include]OPTIONAL TRUE (Returns matches), FALSE (Returns elements that do not match)
  • [Compare] – OPTIONAL vbBinaryCompare – binary comparison, vbTextCompare – text comparison, vbDatabaseCompare – database comparison

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!

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

The Excel VBA Filter function returns an array containing a subset of values that contain (or don’t) a substring against a provided array (Variant).

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

Parameters

sourcearray
The one dimensional array which you want to filter.

match
A string you want to find across all items in the array.

include
Optional. If True the Filter function will return a subset array that contain the match string. If False the Filter function will return a subset array that do not contain the match string. The default value is True.

compare
Optional. The type of comparison to be performed. vbBinaryCompare is the default value. VBA Constant values:

Constant Value Description
vbUseCompareOption -1 Uses option compare
vbBinaryCompare 0 Binary comparison (distinguishes letter case)
vbTextCompare 1 Textual comparison (ignores letter case)

Get all matches in a VBA Array

We will start with some simple examples. The code below will be used in most examples and only the VBA Filter function code line will change so I will omit the VBA For loop in other examples.

Dim arr As Variant, filterArr As Variant, aVal As Variant
arr = Array("Dragon", "Dog", "DRAGONfly", "Cat", "fly")
    
filterArr = Filter(arr, "Dragon")

'Print the contents of the filtered Array
For Each aVal In filterArr 
    Debug.Print aVal
Next aVal
'Result: Dragon

Because the default values of the optional parameters are True for include and vbBinaryCompare for compare the Filter function returned a subset array including only the item which matched the exact lettercase for the word Dragon.

In above example I also used the VBA Array function to quickly define a VBA Array of strings.

Matches in a VBA Array w/o letter case

To get all matches regardless of the lettercase change the compare parameter to vbTextCompare:

Dim arr As Variant, filterArr As Variant
arr = Array("Dragon", "Dog", "DRAGONfly", "Cat", "fly")
    
filterArr = Filter(arr, "Dragon", Compare:=vbTextCompare) 'Result: "Dragon", "DRAGONfly"

Get all items that DO NOT match

The VBA Filter function can be also used to get a subset array that does not contain the match string.

Dim arr As Variant, filterArr As Variant
arr = Array("Dragon", "Dog", "DRAGONfly", "Cat", "fly")
    
filterArr = Filter(arr, "Dragon", False, vbTextCompare) 'Result: "Dog", "Cat", "fly"

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.

Содержание

  1. Функция filter
  2. Синтаксис
  3. Параметры
  4. См. также
  5. Поддержка и обратная связь
  6. Filter function
  7. Syntax
  8. Settings
  9. See also
  10. Support and feedback
  11. VBA Array Filter Function in Excel
  12. Syntax of VBA Array Filter Function
  13. Includes all filtered strings – case sensitive
  14. Extract all filtered strings – not a case sensitive
  15. Excludes or doesn’t contain filtered string – Case Sensitive
  16. Instructions to Run VBA Macro Code or Procedure:
  17. Other Useful Resources:
  18. VBA Filter Arrays
  19. Filter – Match
  20. Filter – Case Insensitive
  21. Filter – Does Not Match
  22. Filter Function
  23. VBA Coding Made Easy
  24. VBA Code Examples Add-in
  25. Using the VBA Array Filter Function
  26. The VBA Tutorials Blog
  27. VBA Array Filter Parameters
  28. The Required Parameters
  29. The SourceArray Argument
  30. The Match String
  31. A Picky Match
  32. The Optional Parameters
  33. The Include Boolean
  34. The Comparison Type
  35. Conclusion

Функция filter

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

Синтаксис

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

Синтаксис функции Filter содержит следующие именованные аргументы:

Part Описание
sourcearray Обязательно. Одномерный массив искомых строк.
Матч Обязательно. Искомая строка.
include Необязательный параметр. Значение Boolean указывает, следует ли возвращать подстроки, включающие или исключающие match. Если include имеет значение True, Filter возвращает подмножество массива, содержащего match в качестве подстроки. Если include имеет значение False, Filter возвращает подмножество массива, не содержащего match в качестве подстроки.
compare Необязательно. Числовое значение, указывающее тип сравнения строк. Значения см. в разделе «Значения».

Параметры

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

Константа Значение Описание
vbUseCompareOption –1 Выполняет сравнение, используя параметр оператора Option Compare.
vbBinaryCompare 0 Выполняется двоичное сравнение.
vbTextCompare 1 Выполняется текстовое сравнение.
vbDatabaseCompare 2 Только Microsoft Access. Выполняется сравнение на основе сведений из базы данных.

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

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Filter function

Returns a zero-based array containing a subset of a string array based on a specified filter criteria.

Syntax

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

The Filter function syntax has these named arguments:

Part Description
sourcearray Required. One-dimensional array of strings to be searched.
match Required. String to search for.
include Optional. Boolean value indicating whether to return substrings that include or exclude match. If include is True, Filter returns the subset of the array that contains match as a substring. If include is False, Filter returns the subset of the array that does not contain match as a substring.
compare Optional. Numeric value indicating the kind of string comparison to use. See Settings section for values.

Settings

The compare argument can have the following values:

Constant Value Description
vbUseCompareOption -1 Performs a comparison by using the setting of the Option Compare statement.
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.

The array returned by the Filter function contains only enough elements to contain the number of matched items.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Array Filter Function in Excel

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

Syntax of VBA Array Filter Function

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

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.

Here is the screenshot of above vba macro code.

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.

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.

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.

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

Источник

VBA Filter Arrays

In this Article

The VBA Filter Function allows you to quickly filter arrays. There are several settings to consider when filtering arrays. We will discuss them below.

Filter – Match

By default the VBA Filter Function will filter an array for matches. In the example below we will filter the array for matches with “Smith”.

A couple important points:

  • The filtered array variable should be declared as data type variant to avoid defining the array size.
  • By default, the Filter function is case sensitive. So filtering on “smith” would give a different result than “Smith”. Below we will show you how to change this setting.

Filter – Case Insensitive

By default, VBA is Case Sensitive. This means that for text to match, the cases must be the same (ex. “smith” does not equal “Smith”). This is true of the Filter Function, as well as all (most?) other VBA functions or comparisons.

Personally, I never want VBA to be case sensitive, so I always add Option Compare Text to the top of all of my code modules. Option Compare Text tells VBA to ignore case so that it’s Case Insensitive:

Adding Option Compare Text to the top of your module will make the Filter Function case insensitive. Alternatively, you can tell the Filter Function itself to be case insensitive with the vbTextCompare argument:

Filter – Does Not Match

The Filter Function can also be used to identify array items that DO NOT match the entered criteria by setting the Include argument to FALSE:

Filter Function

The VBA Filter function returns an Array subset of a supplied string array.

The Filter Function Syntax is:

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

The Function arguments are:

  • SourceArray – The original Array to filter
  • Match – The string to search for
  • [Include]OPTIONAL TRUE (Returns matches), FALSE (Returns elements that do not match)
  • [Compare]OPTIONAL vbBinaryCompare – binary comparison, vbTextCompare – text comparison, vbDatabaseCompare – database comparison

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 Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Using the VBA Array Filter Function

The VBA Tutorials Blog

In this tutorial, we’ll take a look at the VBA Array Filter function, which lets you find a subset of elements in an array based on a filtered search criteria. The Array Filter function is somewhat like the pure VBA equivalent of the AutoFilter function. AutoFilter filters lists in the spreadsheet while the Filter function filters directly on array objects in VBA.

While we could use mathematical expressions with AutoFilter, the plain Filter function is meant to work seamlessly with arrays of strings. You can use it to find numbers, but it is not the most robust way to do it and the results may not be what you expected. Bottom line is the filter function is excellent at filtering string arrays, and not so good at filtering anything else.

VBA Array Filter Parameters

Let’s start off by looking at the parameters that the Filter function accepts. There are two required arguments and two optional ones.

Required
SourceArray The Array to be searched
Match The String you want to find
Optional
Include A binary parameter to search for the presence or absence of the matching string
Compare Comparison type (binary or textual)

The Required Parameters

The first two arguments are both required. They are the meat of the VBA Filter function and are almost always the only arguments you’ll need.

The SourceArray Argument

Our first input should be an array of strings. It can technically also be a variant array. If it’s a Variant array, the Array Filter function will convert each entry to a string before comparing. Then, when the output array is created, the entry will be typed as a string, as we can see in the Locals window here:


The Integer-typed 375 appears as a String variable in the Output Array

(Open the Locals Window by going to View > Locals Window or Alt+V > S by keyboard shortcut).

If you’re interested, the code below is a reproduction of the picture above and it demonstrates the basic array filtering syntax:

Make powerful macros with our free VBA Developer Kit

It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.

This basic array filtering example is nice, but to become really good at using arrays, you’ll need to grab a copy of our comprehensive VBA Arrays Cheat Sheet with over 20 pre-built macros and dozens of tips designed to make it easy for you to handle arrays.

The Match String

The second required argument is the Match as String argument, which takes a string as its input and matches it to some entry in the original array. The purpose is to use this argument to return a subset of elements in your array containing that string.

In other words, the Filter function returns a second array with each matching entry in the original array having its own “slot” in the resultant array. It’s important to note that the output items will contain the entire item in the original array. Take this, for example. The following macro…

…will produce an array with two elements:


The filter window searches for substrings in a string

Each element of the SourceArray is searched until the Match string is found. The Match string can be anywhere in your array elements.

This means that if we store both given and family names together in the same entry, we can expect to get back both the given and family names in our output.

Consider a code block like this:

This will output two people, James Madison and James Monroe . On many occasions, though, we only want first or only last names. You can either attempt some head-spinning string manipulation or RegEx testing, or you can simply split all the names up in your data structure from the beginning, like this:

In some instances, this array is better suited for post-processing, since each entry is a single word. Furthermore, the structure indicates the given name is always associated with an even number and the family name is always associated with an odd number. This doesn’t really have anything to do with VBA array filtering, but it’s a little tip you might find useful one day.

A Picky Match

In our ish example earlier, if “ish” were used as the matching string, we got the two languages with “ish” in their names. However, if we added a space before the word, like “ ish”, we would end up with no matches.

This kind of “picky” matching makes the arrays a good candidates for string manipulation functions. You might need to cut off leading or trailing white space from values extracted from the spreadsheet before you try filtering your arrays. As any programmer knows, users type the darndest things!

The Optional Parameters

The Include Boolean

The first optional parameter is [Include] , a Boolean argument that defaults to TRUE. When Include is set to TRUE, the Match string must be found somewhere in the entry to be included in the output. Conversely, if Include is FALSE, the Match string must not appear in the output.

In other words, you use the Include argument to tell the Filter function if you want to find all the values containing your string or find all the values not containing your string. The ability to find array elements that don’t contain a substring is actually a really powerful feature and it’s one I find myself using quite often.

With our extremely short example, we could use this rather silly code for finding the number of L1 (native) speakers of these languages:

Notice the word False in the third argument to the Filter function. Since all three languages contain the letter n , they are excluded from our output array and we will only get the three numbers back from the Filter function.

If we added German, Korean, French, Italian, Russian and Hindi, our output array would still only contain numbers!

But don’t get too arrogant. Let this be a lesson in deeply-thought-out, logical coding and not change-and-run-until-it-works coding. Once we include Portuguese, our output_arr contains the word “Portuguese” along with the numbers we were hoping to extract. This is because the string Portuguese does not contain the letter n . I suppose if we used “Brazilian Portuguese” we would be fine…

Side note: designing a logical structure, like language and number of speakers in alternating fashion, is invaluable for proper and clever coding. A simple piece of code that takes advantage of the alternating structure would be

this would yield the number of speakers every time, and in their Variant/Integer or Variant/Double-typed forms, as well. A similar logic could be used on the first and last names of the Presidents in the example above.

The Comparison Type

The last parameter, also optional, is [Compare] as VbCompareMethod . You have three choices here:

  1. vbBinaryCompare
  2. vbTextCompare
  3. vbDatabaseCompare.

The vbDatabaseCompare option is really only useful for Access, so we’ll focus on the first two.

The most important difference here is that vbBinaryCompare compares in a case-sensitive manner and it’s the default option. The vbTextCompare option only checks that the letters are the same (e.g. A = a). Thus output_arr = filter(langs, «N», True, vbBinaryCompare) will give us nothing unless the language starts with a capital N, like Norwegian.

However, using vbTextCompare will give us English, Spanish, and Chinese, based on our original array, since vbTextCompare doesn’t care about the letter cases. It performs a case-insensitive comparison.

Numbers, of course, have no case, so if you are trying to use the Filter function to find certain numbers, it doesn’t matter. However, using the Filter function for finding numbers is not the best approach, since there is little flexibility in the function and it’s designed to operate on strings, not numbers.

The vbBinaryCompare option is an efficient way to check if a value is in an array, especially if you have an array of strings. It’s a pretty good alternative to our Is In Array VBA Function.

Conclusion

The Filter function is a nice way to filter an array of strings based on whether or not the elements of your array contain some substring. There’s not a lot of variability or flexibility for the VBA Filter function, and it doesn’t even allow you to do mathematical operations, but when you just need to get some matching strings, it is a quick, intuitive function to get the job done.

You can’t use the VBA Array Filter function to return the position of an element in an array, but that’s okay. We have our own function for that.

That’s all for this tutorial. When you’re ready to take your VBA to the next level, subscribe using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

This article was written by Cory Sarver, a contributing writer for The VBA Tutorials Blog. Visit him on LinkedIn and his personal page.

Источник

Понравилась статья? Поделить с друзьями:
  • Excel vba array add
  • Excel vba argument not optional что это
  • Excel vba applies to
  • Excel tutorial for beginners
  • Excel turn on macros