Поиск относительного положения элемента в массиве (диапазоне) с помощью метода VBA Excel WorksheetFunction.Match. Синтаксис, параметры, примеры.
WorksheetFunction.Match – это метод VBA Excel, который возвращает относительное положение элемента в массиве (диапазоне), соответствующее его порядковому номеру в массиве (диапазоне). Метод соответствует функции рабочего листа =ПОИСКПОЗ (поиск позиции).
Обратите внимание на то, что
- поиск позиции в массиве возможен, если он одномерный или двумерный, но с набором элементов только по одному измерению, например: myArray(8, 0) или myArray(1 To 1, 1 To 20);
- поиск позиции в диапазоне рабочего листа возможен, если он содержит только одну строку или один столбец;
- нумерация относительного положения элемента в массиве начинается с единицы, независимо от заданной индексации массива.
Синтаксис
Синтаксис метода WorksheetFunction.Match в VBA Excel:
WorksheetFunction.Match (Arg1, Arg2, [Arg3]) |
Параметры
Описание параметров метода WorksheetFunction.Match:
Параметр | Описание |
---|---|
Arg1 | Обязательный параметр. Значение элемента массива, по которому будет произведен поиск относительного положения элемента в массиве. |
Arg2 | Обязательный параметр. Непрерывный диапазон ячеек или массив, в котором будет произведен поиск позиции элемента, значение которого совпадет со значением параметра Arg1. |
Arg3 | Необязательный параметр. Задает тип сопоставления значения Arg1 со значениями в массиве Arg2. |
В параметре Arg1 можно использовать знаки подстановки для шаблонов, те же, что и для методов Find и Replace.
Значения параметра Arg3, задающие тип сопоставления:
Значение | Тип сопоставления |
---|---|
-1 | Метод WorksheetFunction.Match находит наименьшее значение элемента в Arg2, большее или равное Arg1. Значения элементов Arg2 должны быть расположены в убывающем порядке: [m, … 2, 1, 0, -1, -2, … -n], [z – a], [True, False] и т. д. |
0 | Метод WorksheetFunction.Match находит в Arg2 первое значение, равное Arg1. Значения элементов Arg2 могут быть расположены в любом порядке. |
1 | Значение по умолчанию. Метод WorksheetFunction.Match находит наибольшее значение элемента в Arg2, меньшее или равное Arg1. Значения элементов Arg2 должны быть расположены в возрастающем порядке: [-n, … -2, -1, 0, 1, 2, … m], [a – z], [False, True] и т. д. |
При сопоставлении строк регистр не учитывается.
Примеры
Пример 1
Поиск относительного положения элемента в массиве, индексация которого начинается с нуля:
Sub Primer1() Dim myArray As Variant, n As Long ‘заполнение массива значениями, нумерация элементов массива начинается с нуля myArray = Array(«Арка», 45, «Дуб», «Клуб», 85.37, «Литр», 103, «Небо», «Столб») ‘определяем относительное положение элемента в массиве, при чем ‘нумерация относительного положения начинается с единицы n = WorksheetFunction.Match(«Клуб», myArray) MsgBox n ‘Результат: 4 MsgBox myArray(n) ‘Результат: 85.37, так как нумерация массива начинается с нуля End Sub |
Пример 2
Определение индекса элемента в массиве по его относительному положению, возвращенному методом WorksheetFunction.Match:
Sub Primer2() Dim myArray(7 To 15) As Variant, i As Long, n As Long ‘заполнение элементов массива значениями For i = 7 To 15 myArray(i) = Choose(i, «», «», «», «», «», «», «Арка», 45, «Дуб», «Клуб», 85.37, «Литр», 103, «Небо», «Столб») Next n = WorksheetFunction.Match(«Клуб», myArray) MsgBox n ‘Результат: 4 ‘находим индекс элемента в массиве по его относительному положению n = n + LBound(myArray) — 1 MsgBox myArray(n) ‘Результат: Клуб End Sub |
Пример 3
Определение адреса ячейки на рабочем листе по найденному методом WorksheetFunction.Match относительному положению этой ячейки в заданном диапазоне:
Sub Primer3() Dim n As Long n = WorksheetFunction.Match(«Брелок», Range(«B1400:B1410»), 0) With Range(«B1400:B1410») MsgBox «Значение = « & .Cells(n) & vbNewLine & _ «Адрес = « & .Cells(n).Address & vbNewLine & _ «Строка = « & .Cells(n).Row & vbNewLine & _ «Столбец = « & .Cells(n).Column End With End Sub |
We have Index and Match in the worksheet as lookup functions. In addition, we can also use Match functions in VBA as a lookup function. This function is a worksheet function and the Application.Worksheet method. Since it is a worksheet function, the arguments for the Match function are similar to the worksheet function.
VBA Match Function
VBA Match function looks for the position or row number of the lookup value in the table array, i.e., in the main excel tableIn excel, tables are a range with data in rows and columns, and they expand when new data is inserted in the range in any new row or column in the table. To use a table, click on the table and select the data range.read more.
In a worksheet, lookup functionsThe LOOKUP excel function searches a value in a range (single row or single column) and returns a corresponding match from the same position of another range (single row or single column). The corresponding match is a piece of information associated with the value being searched.
read more are an integral part of Excel. Some important lookup functions are VLOOKUPThe VLOOKUP excel function searches for a particular value and returns a corresponding match based on a unique identifier. A unique identifier is uniquely associated with all the records of the database. For instance, employee ID, student roll number, customer contact number, seller email address, etc., are unique identifiers.
read more, HLOOKUP, INDEX, and MATCHThe MATCH function looks for a specific value and returns its relative position in a given range of cells. The output is the first position found for the given value. Being a lookup and reference function, it works for both an exact and approximate match. For example, if the range A11:A15 consists of the numbers 2, 9, 8, 14, 32, the formula “MATCH(8,A11:A15,0)” returns 3. This is because the number 8 is at the third position.
read more. Unfortunately, we do not have these functions as VBA functionsVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more. However, we can use them as worksheet functions in VBA.
In this article, we will show you how to use one of the worksheet lookup functions, MATCH in VBA, as a worksheet function.
Table of contents
- VBA Match Function
- How to Use MATCH Function in VBA Excel?
- Example #1
- Example #2 – VBA Match From Another Sheet
- Example #3 – VBA Match Function with Loops
- Recommended Articles
- How to Use MATCH Function in VBA Excel?
How to Use MATCH Function in VBA Excel?
We will show you a simple example of using the Excel MATCH function in VBA.
You can download this VBA Match Excel Template here – VBA Match Excel Template
Example #1
In VBA, we can use this MATCH formula in excelThe MATCH function looks for a specific value and returns its relative position in a given range of cells. The output is the first position found for the given value. Being a lookup and reference function, it works for both an exact and approximate match. For example, if the range A11:A15 consists of the numbers 2, 9, 8, 14, 32, the formula “MATCH(8,A11:A15,0)” returns 3. This is because the number 8 is at the third position.
read more as a worksheet function. Follow the below steps to use the MATCH function in VBA.
Step 1: Create a sub procedure by giving a Macro name.
Code:
Sub Match_Example1()
Step 2: In the E2 cell, we need the result, so start the code as Range (“E2”).Value =
Code:
Sub Match_Example1() Range("E2").Value = End Sub
Step 3: In E2, the cell value should result from the MATCH formula. So, to access the VBA MATCH function, we need to use the property “WorksheetFunction” first. In this property, we will get all the available worksheet function lists.
Step 4: Select the MATCH function here.
Code:
Sub Match_Example1() Range("E2").Value = WorksheetFunction.Match( End Sub
Step 5: The problem starts because we do not get the exact syntax name. Rather, we get syntax like “Arg1, Arg2, Arg3”. So, it would help if you were sure of the syntaxes here.
Our first argument is LOOKUP VALUE. Our LOOKUP VALUE is in cell D2, so select the cell as Range (“D2”).Value.
Code:
Sub Match_Example1() Range("E2").Value = WorksheetFunction.Match(Range("D2").Value, End Sub
Step 6: The second argument is Table Array. Our table array range is from A2 to A10. So, select the range as “Range (“A2: A10”).”
Code:
Sub Match_Example1() Range("E2").Value=WorksheetFunction.Match(Range("D2").Value,Range("A2:A10"), End Sub
Step 7: Now, the final argument is MATCH TYPE. We need an exact match, so enter the argument value as zero.
Code:
Sub Match_Example1() Range("E2").Value = WorksheetFunction.Match(Range("D2").Value, Range("A2:A10"), 0) End Sub
Run the Macro. We will get the position of whatever the year name is there in cell D2.
Example #2 – VBA Match From Another Sheet
Assume the same data set from the above is on two different sheets. For example, the table array is in the sheet name called “Data Sheet,” and Lookup Value is in the sheet name called “Result Sheet.”
In this case, we need to refer to worksheets by their name before we refer to the ranges. Below is the set of codes with sheet names.
Code:
Sub Match_Example2() Sheets("Result Sheet").Range("E2").Value = WorksheetFunction.Match(Sheets("Result Sheet").Range("D2").Value, Sheets("Data Sheet").Range("A2:A10"), 0) End Sub
Example #3 – VBA Match Function with Loops
If the result we want is in a single cell, then no problem, but if the result has to come in more than one cell, then we need to use a VBA loopA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more to get the result in all the cells.
Assume you have data like this.
Writing lengthy codes is arduous in these cases, so we switch to loops. Below is the set of codes that will do the job for us.
Code:
Sub Match_Example3() Dim k As Integer For k = 2 To 10 Cells(k, 5).Value = WorksheetFunction.Match(Cells(k, 4).Value, Range("A2:A10"), 0) Next k End Sub
This set of codes will get the result in just the blink of an eye.
Recommended Articles
This article has been a guide to Excel VBA Match Function. Here, we learned how to use the Match function in VBA and some simple to advanced examples. Below are some useful Excel articles related to VBA: –
- Use VBA Worksheet Function
- Format Number in VBA
- What does Index Function Do in Excel?
- Index Match in VBA
Excel VBA Match Function
VBA Match Function looks for the position or row number of the lookup value in the table array i.e. in the main excel table. For example, VLOOKUP, HLOOKUP, MATCH, INDEX, etc. These are the lookup functions that are more important than others. Regretfully, we don’t have the same functions available in VBA for making things easier. However, we can use these functions as worksheet functions under the VBA script to make our lives easier.
Today, we are about to learn the MATCH function which can be used as a worksheet function under VBA.
VBA Match has the same use as the Match formula in Excel. This function in MS Excel VBA finds a match within an array with reference to the lookup value and prints its position. This function becomes useful when you need to evaluate the data based on certain values. For example, VBA MATCH is helpful if you have the salary data of employees and you need to find out the numeric position of an employee in your data who has salary less than/greater than/equals to a certain value. It is really helpful in analyzing the data and also one line of code can automate the things for you.
Syntax of Match Function in Excel VBA
VBA Match has the following syntax:
Where,
- Arg1 – Lookup_value – The value you need to lookup in a given array.
- Arg2 – Lookup_array – an array of rows and columns which contain possible Lookup_value.
- Arg3 – Match_type – The match type which takes value -1, 0 or 1.
If match_type = -1 means that the MATCH function will find out the smallest value which is greater than or equals to the lookup_value. For this to happen, the lookup_array must be sorted in descending order.
If match_type = 0 means that the MATCH function will find out the value which is exactly the same as that of the lookup_value.
If match_type = +1 it means that the MATCH function will find out the largest value which is lesser than or equals to the lookup_value. For this to happen, the lookup_array must be sorted in ascending order. The default value for the match type is +1.
How to Use Excel VBA Match Function?
We will learn how to use a VBA Match Excel function with few examples.
You can download this VBA Match Excel Template here – VBA Match Excel Template
VBA Match Function – Example #1
Suppose we have data as shown below:
We need to find who from this list have salary € 30,000 along with position in Excel.
Though in this data set we can manually configure this, please think on a broader picture, what if you have millions of rows and columns?
Follow the below steps to use MATCH function in VBA.
Step 1: Define a sub-procedure by giving a name to macro.
Code:
Sub exmatch1() End Sub
Step 2: Now, we want our output to be stored in cell E2. Therefore, start writing the code as Range(“E2”).Value =
This defines the output range for our result.
Code:
Sub exmatch1() Range("E2").Value = End Sub
Step 3: Use WorksheetFunction to be able to use VBA functions.
Code:
Sub exmatch1() Range("E2").Value = WorksheetFunction End Sub
Step 4: WorksheetFunction has a variety of functions that can be accessed and used under VBA. After “WorksheetFunction”, put a dot (.) and then you’ll be able to access the functions. Choose the MATCH function from the dropdown list.
Code:
Sub exmatch1() Range("E2").Value = WorksheetFunction.Match End Sub
Step 5: Now, give the arguments to the MATCH function. Like Lookup_value. Our Lookup_value is stored in cell D2 as shown in the below screenshot. You can access it under the MATCH function using Range function.
Code:
Sub exmatch1() Range("E2").Value = WorksheetFunction.Match(Range("D2").Value, End Sub
Step 6: The Second argument is Lookup_array. This is the table range within which you want to find out the position of Lookup_value. In our case, it is (B1:B11). Provide this array using the Range function.
Code:
Sub exmatch1() Range("E2").Value = WorksheetFunction.Match(Range("D2").Value, Range("B1:B11"), End Sub
Step 7: The Last argument for this code to work out is Match_type. We wanted to have an exact match for Lookup_value in given range> Therefore, give Zero (0) as a matching argument.
Code:
Sub exmatch1() Range("E2").Value = WorksheetFunction.Match(Range("D2").Value, Range("B1:B11"), 0) End Sub
Step 8: Run this code by hitting F5 or Run button and see the output.
You can see in Cell E2, there is a numeric value (6) which shows the position of the value from cell D2 through range B1:B11.
Example #2 – VBA Match Function with Loops
It is easy when you have only one value to lookup for in the entire range. But, what if you need to check the position for a number of cells? It would be harsh on a person who is adding to ask him to write the separate codes for each cell.
In such cases, MATCH function can be used with loop (especially For loop in our case). See the following steps to get an idea of how we use MATCH function with loop.
Step 1: Define a subprocedure by giving a name to macro.
Code:
Sub Example2() End Sub
Step 2: Define an integer that can hold the value for multiple cells in the loop.
Code:
Sub Example2() Dim i As Integer End Sub
Step 3: Use For loop on the integer to use the different lookup values whose position can be stored in column E.
Code:
Sub Example2() Dim i As Integer For i = 2 To 6 End Sub
Step 4: Now, use the same method we used in example 1, just instead of Range, we will use the Cells function and will be using a two-dimensional array (Rows and columns) in contrast to the first example.
Code:
Sub Example2() Dim i As Integer For i = 2 To 6 Cells(i, 5).Value = WorksheetFunction.Match(Cells(i, 4).Value, Range("B2:B11"), 0) Next i End Sub
Here, Cells(i, 5).Value = stores the value of resulting positions in each row from 2 to 6 (row i) in column E (column number 5). Under Match function, Cells(i, 4).Values checks for each Lookup_value present in row 2 to 6 in the 4th column. This lookup value then searched in Array B2:B11 in excel sheet where data is present and relative positions can be stored in each row of column 5 (column E).
Step 5: Run this code by hitting F5 or Run button simultaneously and see the result. It will almost pull out the magic in a piece of code with a single line.
In this article, we learned how we can use MATCH function under VBA as a special case of WorksheetFunction.
Things to Remember
- Lookup_value can be number/text/logical value or can be a cell reference to a number, text or logical value.
- By default, Match_type can be considered as 1, if omitted/not mentioned.
- As similar to Excel MATCH function, VBA MATCH also gives the relative position of a Lookup_value under Lookup_array and not the value itself.
- If a match is not found, a relative excel cell will be filled with #N/A.
- If MATCH function is used on Text values, it is not able to differentiate between lowercases and uppercases. For Example, Lalit and lalit are same. So do LALIT and lalit.
- Wildcard characters can be used if you are finding out the exact match (i.e. match type is zero). Wildcard character asterisk (*) can be used to find out a series of characters. While a question mark (?) can be used to find out a single character.
Recommended Articles
This is a guide to VBA Match Function. Here we discuss VBA Match and how to use Excel VBA Match Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA On Error
- VBA Number Format
- VBA VLOOKUP
- VBA Function
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
WorksheetFunction.Match method (Excel) |
vbaxl10.chm137114 |
vbaxl10.chm137114 |
excel |
Excel.WorksheetFunction.Match |
901cdd78-e8fc-f149-66ff-5887f7099c96 |
05/24/2019 |
medium |
WorksheetFunction.Match method (Excel)
Returns the relative position of an item in an array that matches a specified value in a specified order. Use Match instead of one of the Lookup functions when you need the position of an item in a range instead of the item itself.
Syntax
expression.Match (Arg1, Arg2, Arg3)
expression A variable that represents a WorksheetFunction object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Arg1 | Required | Variant | Lookup_value: the value that you use to find the value that you want in a table. |
Arg2 | Required | Variant | Lookup_array: a contiguous range of cells containing possible lookup values. Lookup_array must be an array or an array reference. |
Arg3 | Optional | Variant | Match_type: the number -1, 0, or 1. Match_type specifies how Microsoft Excel matches lookup_value with values in lookup_array. |
Return value
Double
Remarks
Lookup_value is the value that you want to match in lookup_array. For example, when you look up a number in a telephone book, you are using the person’s name as the lookup value, but the telephone number is the value that you want.
Lookup_value can be a value (number, text, or logical value) or a cell reference to a number, text, or logical value.
If match_type is 1, Match finds the largest value that is less than or equal to lookup_value. Lookup_array must be placed in ascending order: …-2, -1, 0, 1, 2, …, A-Z, FALSE, TRUE.
If match_type is 0, Match finds the first value that is exactly equal to lookup_value. Lookup_array can be in any order. Note that Match is case-insensitive.
If match_type is -1, Match finds the smallest value that is greater than or equal to lookup_value. Lookup_array must be placed in descending order: TRUE, FALSE, Z-A, …2, 1, 0, -1, -2, …, and so on.
If match_type is omitted, it is assumed to be 1.
Match returns the position of the matched value within lookup_array, not the value itself. For example, MATCH("b",{"a","b","c"},0)
returns 2, the relative position of «b» within the array {"a","b","c"}
.
Match does not distinguish between uppercase and lowercase letters when matching text values.
If Match is unsuccessful in finding a match, it returns the #N/A error value.
If match_type is 0 and lookup_value is text, you can use the wildcard characters, question mark (?) and asterisk (*), in lookup_value. A question mark matches any single character; an asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) before the character.
Example
For each value in the first column of the first worksheet, this example searches through the entire workbook for a matching value. If the macro finds a matching value, it sets the original value on the first worksheet to be bold.
Sub HighlightMatches() Application.ScreenUpdating = False 'Declare variables Dim var As Variant, iSheet As Integer, iRow As Long, iRowL As Long, bln As Boolean 'Set up the count as the number of filled rows in the first column of Sheet1. iRowL = Cells(Rows.Count, 1).End(xlUp).Row 'Cycle through all the cells in that column: For iRow = 1 To iRowL 'For every cell that is not empty, search through the first column in each worksheet in the 'workbook for a value that matches that cell value. If Not IsEmpty(Cells(iRow, 1)) Then For iSheet = ActiveSheet.Index + 1 To Worksheets.Count bln = False var = Application.Match(Cells(iRow, 1).Value, Worksheets(iSheet).Columns(1), 0) 'If you find a matching value, indicate success by setting bln to true and exit the loop; 'otherwise, continue searching until you reach the end of the workbook. If Not IsError(var) Then bln = True Exit For End If Next iSheet End If 'If you don't find a matching value, don't bold the value in the original list; 'if you do find a value, bold it. If bln = False Then Cells(iRow, 1).Font.Bold = False Else Cells(iRow, 1).Font.Bold = True End If Next iRow Application.ScreenUpdating = True End Sub
[!includeSupport and feedback]