Поиск значения в таблице (диапазоне, массиве) по значению в первом столбце таблицы с помощью метода VBA Excel WorksheetFunction.VLookup. Синтаксис, параметры, примеры.
WorksheetFunction.VLookup – это метод VBA Excel, который ищет значение в крайнем левом столбце таблицы (диапазона, двумерного массива) и возвращает значение ячейки (элемента массива), находящейся в указанном столбце той же строки. Метод соответствует функции рабочего листа =ВПР (вертикальный просмотр).
Синтаксис
Синтаксис метода WorksheetFunction.VLookup в VBA Excel:
WorksheetFunction.VLookup(Arg1, Arg2, Arg3, Arg4) |
Параметры
Описание параметров метода WorksheetFunction.VLookup:
Параметр | Описание |
---|---|
Arg1 (Lookup_value) | Обязательный параметр. Значение, которое необходимо найти в первом столбце таблицы. |
Arg2 (Table_array) | Обязательный параметр. Таблица с двумя или более столбцами данных. Используется ссылка на диапазон, имя диапазона или массив. |
Arg3 (Col_index_num) | Обязательный параметр. Номер столбца, значение из которого возвращается. |
Arg4 (Range_lookup) | Необязательный параметр. Логическое значение, указывающее, должен ли метод VLookup искать точное совпадение или приблизительное. |
Значения параметра Arg4 (Range_lookup), задающие точность сопоставления:
Значение | Точность сопоставления |
---|---|
True | Значение по умолчанию. Метод WorksheetFunction.VLookup находит точное или приблизительное совпадение Arg1 со значением в первом столбце. Если точное совпадение не найдено, используется самое большое значение, меньшее Arg1. Значения в первом столбце таблицы должны быть отсортированы по возрастанию. |
False | Метод WorksheetFunction.VLookup находит только точное совпадение. Сортировка значений первого столбца таблицы не требуется. Если точное совпадение не найдено, генерируется ошибка. |
Если значение параметра Arg1 является текстом, а Arg4=False, тогда в строке Arg1 можно использовать знаки подстановки (спецсимволы): знак вопроса (?) и звездочку (*). Знак вопроса заменяет один любой символ, а звездочка соответствует любой последовательности символов. Чтобы знак вопроса (?) и звездочка (*) обозначали сами себя, перед ними указывается тильда (~).
Примеры
Примеры обкатывались на следующей таблице:
Поиск значения в таблице
Sub Primer1() Dim x x = «Смартфон: « & WorksheetFunction.VLookup(7, Range(«A2:D11»), 2, False) MsgBox x End Sub |
Результат работы кода:
Поиск значения в массиве
Sub Primer2() Dim x, y x = Range(«A2:D11») y = «Смартфон: « & WorksheetFunction.VLookup(8, x, 2, False) & vbNewLine _ & «Разрешение экрана: « & WorksheetFunction.VLookup(8, x, 3, False) & vbNewLine _ & «Емкость аккумулятора: « & WorksheetFunction.VLookup(8, x, 4, False) & » мАч» MsgBox y End Sub |
Результат работы кода:
Да, здесь можно немного улучшить структуру кода, применив оператор With...End With
:
Sub Primer3() Dim x, y x = Range(«A2:D11») With WorksheetFunction y = «Смартфон: « & .VLookup(8, x, 2, False) & vbNewLine _ & «Разрешение экрана: « & .VLookup(8, x, 3, False) & vbNewLine _ & «Емкость аккумулятора: « & .VLookup(8, x, 4, False) & » мАч» End With MsgBox y End Sub |
In my earlier post, I had written about VLOOKUP in Excel. It was a massive post of around 2500 words, it explains most of the things about the vertical lookup function in excel. Today’s post is an extension to that post and here we will understand how to apply a VLOOKUP in VBA.
If you haven’t read that post then I would strongly recommend you read that post before going any further. [Read Here]
Assuming that you have basic knowledge of the VLOOKUP function we will move further.
Note: To perform these programs yourself, you may need to enable macros in excel. Read this post to know how to do this.
Syntax of VBA VLOOKUP
You can use VLookUp in macros by following any of the below ways:
Application.VLOOKUP(lookup_value, table_array, column_index, range_lookup)
Or
Application.WorksheetFunction.VLOOKUP(lookup_value, table_array, column_index, range_lookup)
Note: If you are searching for something similar to the VLOOKUP function for Access then probably you should use DLOOKUP.
5 Examples of Using VLOOKUP in VBA
Now let’s move to some practical examples of using VLookUp in VBA codes.
Example 1
Using VLookUp find the monthly salary of “Justin Jones” from the below table. Display the salary using a dialog box.
Below is the code for this:
Sub FINDSAL()
Dim E_name As String
E_name = "Justin Jones"
Sal = Application.WorksheetFunction.VLookup(E_name, Sheet1.Range("B3:D13"), 3, False)
MsgBox "Salary is : $ " & Sal
End Sub
Explanation: In this code, we have used a variable ‘E_name
’ to store the employee name whose salary is to be fetched. After this, we have simply supplied the employee name and other required arguments to the VLOOKUP and it returns the salary of the corresponding Employee.
Example 2
Now make the above program a little customizable by accepting the Employee name from the user. If the user enters any Employee name that is not present in the table then the program should be able to convey this clearly to the user.
To accomplish this we can use the below code:
Sub FINDSAL()
On Error GoTo MyErrorHandler:
Dim E_name As String
E_name = InputBox("Enter the Employee Name :")
If Len(E_name) > 0 Then
Sal = Application.WorksheetFunction.VLookup(E_name, Sheet1.Range("B3:D13"), 3, False)
MsgBox "Salary is : $ " & Sal
Else
MsgBox ("You entered an invalid value")
End If
Exit Sub
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Employee Not Present in the table."
End If
End Sub
Explanation: In this code, we are accepting the user input using an InputBox function. If the Employee name entered by the user is found, then VLookUp returns its corresponding salary. However, if the employee name is not present in the table then VLOOKUP throws a “1004 Error”.
And, we have created an error handler to catch such cases for conveying the user that entered employee name doesn’t exist.
Example 3
In this example we will try to write a code that adds the Department field from the Employee Table 1 to our old Employee Table.
As you can see that in both these tables there is only one common column i.e. Employee_ID
. So, in this case, we will have to apply the VLookUp based on the Employee ID.
Below is the code to do this:
Sub ADDCLM()
On Error Resume Next
Dim Dept_Row As Long
Dim Dept_Clm As Long
Table1 = Sheet1.Range("A3:A13") ' Employee_ID Column from Employee table
Table2 = Sheet1.Range("H3:I13") ' Range of Employee Table 1
Dept_Row = Sheet1.Range("E3").Row ' Change E3 with the cell from where you need to start populating the Department
Dept_Clm = Sheet1.Range("E3").Column
For Each cl In Table1
Sheet1.Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 2, False)
Dept_Row = Dept_Row + 1
Next cl
MsgBox "Done"
End Sub
Explanation: This code takes each ‘lookup_value
’ from the Employee ID field (one at a time), looks up its corresponding Department, and then populates the corresponding department value at the appropriate place.
Please note that in this code we have just pasted the result of the VLOOKUP formula, and not the VLookUp formula itself (Refer Example 5).
Example 4
In this example we will try to write a code that displays all the details of an employee from the Employee table (as shown below) when its Employee ID is entered.
Below is the code that can accomplish this:
Sub FETCH_EMP_DETAILS()
On Error GoTo MyErrorHandler:
Dim E_id As Long
E_id = InputBox("Enter the Employee ID :")
Det = "Employee ID : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 1, False)
Det = Det & vbNewLine & "Employee Name : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 2, False)
Det = Det & vbNewLine & "Employee SSN : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 3, False)
Det = Det & vbNewLine & "Monthly Salary : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 4, False)
Det = Det & vbNewLine & "Department : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 5, False)
MsgBox "Employee Details : " & vbNewLine & Det
Exit Sub
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Employee Not Present in the table."
ElseIf Err.Number = 13 Then
MsgBox "You have entered an invalid value."
End If
End Sub
Explanation: In this example, we have asked the user to enter the Employee Id
and then we have used multiple VLookUp Statements and concatenated their outputs to show all the details in a single message box.
Example 5
Redo example 3 but this time paste the whole VLookUp formula instead of pasting only the result.
Below is the code for doing this:
Sub ADDCLM()
On Error Resume Next
Dim Dept_Row As Long
Dim Dept_Clm As Long
ctr = 0
Table1 = Sheet1.Range("A3:A13") ' Employee_ID Column from Employee table
Table2 = Sheet1.Range("H3:I13") ' Range of Employee Table 1
Dept_Row = Sheet1.Range("E3").Row ' Change E3 with the cell from where you need to start populating the Department
Dept_Clm = Sheet1.Range("E3").Column
For Each cl In Table1
Sheet1.Cells(Dept_Row, Dept_Clm).FormulaR1C1 = "=VLOOKUP(RC[-4], R3C8:R13C9, 2, False)"
Dept_Row = Dept_Row + 1
ctr = ctr + 1
Next cl
MsgBox "Done"
End Sub
Explanation: This code is very similar to the one that we have discussed in Example 3, the only difference between these formulas is that here we are copying the VLookUp formula directly in the cells.
In this code, we have applied the VLOOKUP in R1C1 form. So, the formula =VLOOKUP(RC[-4], R3C8:R13C9, 2, False) means =VLOOKUP(<4 cells to the left of current cell>, <Range of Employee Table 1>, <column to be fetched>, <exact match>).
One thing that is worth noting here is: the square brackets ( [ ] ) in your R1C1 formula indicate that you are specifying a relative range. If you want to specify an absolute range, you need to specify the R1C1 cells without brackets; e.g. R3C8:R13C9.
So, this was all about VBA VLOOKUP .
“Constant effort and frequent mistakes are the stepping stones to genius” – Elbert Hubbard
A Quick Guide to the VBA VLookup
Parameters | Type |
---|---|
Lookup value | The value you are searching for |
Table array | The range you are searching through |
Column index | The column number of the value to return. |
Range look up | Optional — set to False for exact match only. |
Introduction
The VLookup function can be a useful Excel function. Even though it is straightforward to use can often be confusing when used in VBA. In this post, I am going to show how anyone can easily use the VLookup function. I’ll also cover the pitfalls and how to avoid them. Of course, no post would be complete without a ton of examples that you can try for yourself.
If you are not familiar with VLookup in Excel then this page provides a great introduction.
Notes: I use the Underscore character(_) in the code examples. In VBA this allows you to split a line over multiple lines e.g.
' One line sResult = Application.VLookup("Apricot", Sheet1.Range("A10:B10000"), 1)
' Split up with underscore sResult = Application.VLookup( _ "Apricot", Sheet1.Range("A10:B10000"), 1)
A Simple VBA VLookup example
Note: The variable shData in the examples refers to the worksheet by the code name. You can replace this with the code name of the worksheet you are using.
Take a look at the following data:
Use this code to generate this data on any worksheet:
' Use this sub to generate the data ' https://excelmacromastery.com Sub GenerateData() ' Change the sheet name as required With ThisWorkbook.Worksheets("Sheet1") .Range("A1").CurrentRegion.ClearContents .Range("A1:A7").Value = WorksheetFunction.Transpose(Array("Fruit", "Apple", "Apricot", "Orange", "Peach", "Pair", "Plum")) .Range("B1:B7").Value = WorksheetFunction.Transpose(Array("Price", 1.56, 2.33, 1.45, 2.28, 1.67, 1.22)) End With End Sub
The code below will return the price for the Pear i.e. 1.45
' https://excelmacromastery.com/ Sub SimpleVLookup() Dim sRes As String sRes = Application.VLookup("Pear",shData.Range("A2:B7"),2) ' This will print 1.67 to the Immediate Window(Ctrl + G) Debug.Print sRes End Sub
The code looks for the text Pear in the range A2:B7. When it finds the text it returns a value from the same row as the text. The value in determined by the column number argument. We used 2 in this example.
Let’s look at some more examples and results
' Returns 1.45 sRes = Application.VLookup("Orange",shData.Range("A2:B7"),2) ' Returns 1.56 sRes = Application.VLookup("Apple",shData.Range("A2:B7"),2) ' Returns 1.22 sRes = Application.VLookup("Plum",shData.Range("A2:B7"),2) ' Returns Orange as column is 1 sRes = Application.VLookup("Orange",shData.Range("A2:B7"),1) ' Returns Apple as column is 1 sRes = Application.VLookup("Apple",shData.Range("A2:B7"),1) ' Returns Plum as column is 1 sRes = Application.VLookup("Plum",shData.Range("A2:B7"),1)
The Parameters
In this section we will look at the four parameters. These are
- lookup_value – The value to look up. It must be in the first column of the range.
- table_array – This is the range to search. This can also be a VBA array although it very slow using this.
- col_index_num – This contains the column number of the return value. Starts at column number one.
- range_lookup(optional) – Use True(default) to find closest match. Use False to find exact match. Using True assumes that the first columnis sorted alphabetically or numerically.
We will look at these parameters individually starting with the lookup_value parameter.
Parameter 1: lookup_value
This is the value that you are looking up. It must be in the first column of the Range. If you are using the range C4:X10 then the lookup value must be in column C. If you are using the range Z1:AB5 then the lookup value must be in column Z.
The type of value you search for will normally be a string as this example shows
' https://excelmacromastery.com/ Sub StringVLookup() Dim sFruit As String sFruit = "Plum" Dim sRes As Variant sRes = Application.VLookup( _ sFruit, shData.Range("A2:B7"), 2, False) End Sub
We can also search for a number but you have to be careful here:
- If the number is stored as text then the search value must be a string.
- If the number is stored as a number then the search value must be a number.
For example in this data we have the lookup column stored as numbers
In this case, the lookup value must be a Long or you will get an error message.
' https://excelmacromastery.com/ Sub NumberVLookup() Dim num As Long num = 7 Dim sRes As Variant sRes = Application.VLookup( _ num, shData.Range("F2:G7"), 2, True) Debug.Print sRes End Sub
You can also use the Double data type if you are looking up a decimal value. As in the case of an integer it must be stored as a number if you want to use Double.
Using VLookup on a Date Type
Using a Date type is a tricky business. VBA has a Date data type but the worksheet does not.
So the date type needs to be converted to a Long as the following examples show
theDate = CLng(#1/14/2017#) theDate = CLng(CDate("1/14/2017")) theDate = CLng(shData.Range("H10"))
You can then use it as normal in the VLookup function when the search column contains dates
' https://excelmacromastery.com/ Sub DateVLookup() Dim theDate As Long theDate = CLng(#1/14/2017#) Dim sRes As Variant sRes = Application.VLookup( _ theDate, shData.Range("I2:J7"), 2, False) Debug.Print sRes End Sub
Parameter 2: table_array
This parameter refers to the range of the data we are looking up. You will normally use a range for this as we have seen in the examples so far.
If you are using a worksheet table you can use the range of the table.
' https://excelmacromastery.com/ Sub SimpleVLookupTable() Dim sRes As Variant ' Get the table Dim table As ListObject Set table = shData.ListObjects("Table1") ' Use the table for the table_array parameter sRes = Application.VLookup( _ "Plum", table.Range, 2, False) Debug.Print sRes End Sub
You can also use a VBA array with VLookup but this tends to be very slow.
Parameter 3: col_index-num
This parameter refers to the column which contains the value you want to return. Column 1 is the leftmost column of the table_array.
If the column number is greater than the number of columns in the range you will get an error. See The VLookup Error Types section below.
© BigStockPhoto.com
Parameter 4: range_lookup
This is an optional parameter. If it is not used then it takes True as the default value.
False means that an exact match must be found.
True means that an approximate match will be returned. The first column must be ordered numerically or alphabetically for this to work correctly.
Let’s look at the sample data again
The following code shows some examples of how this parameter works:
' https://excelmacromastery.com/ Sub SimpleVLookup() Dim rg As Range Set rg = shData.Range("A2:B7") Dim sRes As Variant ' Stops at Orange - the last item before a P item sRes = Application.VLookup("P", rg, 2, True) ' Stops at Orange - the last item before a Pea item sRes = Application.VLookup("Pea", rg, 2, True) ' Stops at Peach - the last item before a Pead item sRes = Application.VLookup("Pead", rg, 2, True) ' Error - no exact match found sRes = Application.VLookup("Pea", rg, 2, False) End Sub
Dealing with Errors
© BigStockPhoto.com
We can use VLookup in two ways in VBA. With Application or with WorksheetFunction
Application.WorksheetFunction.VLookup Application.VLookup
The difference between them is how we handle errors. Let’s look at each of these in turn.
Using WorksheetFunction
Using WorksheetFunction.VLookup requires us to use On Error to trap the error. We can then check the error number Err.Number to see if the value is valid.
' https://excelmacromastery.com/ Sub UseWorksheetFunction() Dim sRes As Variant ' Turn on error trapping On Error Resume Next Err.Clear sRes = Application.WorksheetFunction.VLookup _ ("Plum", shData.Range("A2:B7"), 2, False) ' Check if value found If Err.Number = 0 Then Debug.Print "Found item. The value is " & sRes Else Debug.Print "Could not find value: " & "Plum" End If End Sub
Using Application
Using Application.VLookup we can simply check the return value to see if there was an error
' https://excelmacromastery.com/ Sub UsingApplication() Dim sRes As Variant sRes = Application.VLookup _ ("Plum", shData.Range("A2:B7"), 2, False) ' Check if value found If IsError(sRes) = False Then Debug.Print "Found item. The value is " & sRes Else Debug.Print "Could not find value: " & "Plum" End If End Sub
VLookup Error Types
The following table shows a list of the Excel cell error numbers and what they mean. These are the error numbers we get when we use Application.VLookup. This is taken from this MSDN Page
Constant | Error number | Cell error value |
---|---|---|
xlErrDiv0 | 2007 | #DIV/0 |
xlErrNA | 2042 | #N/A |
xlErrName | 2029 | #NAME? |
xlErrNull | 2000 | #NULL! |
xlErrNum | 2036 | #NUM! |
xlErrRef | 2023 | #REF! |
xlErrValue | 2015 | #VALUE! |
Errors and Causes
The following table shows some common errors you may encounter with VLookup. If you’re having trouble with a particular VLookup error then it is a good idea to try it in Excel first.
Error | Cell | Possible causes |
---|---|---|
Error 2015 | #VALUE! | The column number is less than one. |
Error 2015 | #VALUE! | You used a string instead of a range for the table_array parameter. |
Error 2023 | #REF! | The column number is greater than the number of columns. |
Error 2042 | #N/A | The value is not found. See possible causes below. |
If you cannot find the value then check the following:
- Ensure the Table/Range is correct.
- Ensure the Table/Range does not include the header(VBA will think list is unsorted).
- Ensure the Table/Range is using the correct worksheet.
- If searching for a number use a long or double data type in the lookup_value parameter. See lookup_value section above
- If searching for a number stored as text use a string data type in the lookup_value parameter.
- If searching for a date convert it to a long(see Date Type above) in the lookup_value parameter.
If you are getting the wrong value then check the following:
- If the range_lookup parameter is True or not used, then ensure the first column is sorted alphabetically or numerically (see range_lookup above)
VBA VLookup Speed
Sometimes you may need to perform a large number of lookups. In these cases, VLookup could be too slow. The VBA Dictionary is faster when dealing with a large number of lookups. The following code shows an example of using the Dictionary.
' https://excelmacromastery.com/ Sub UseDictionary() ' Get the range of values Dim rg As Range Set rg = shData.Range("M1:N20000") ' Create the dictionary Dim dict As Object Set dict = CreateObject("Scripting.Dictionary") ' Fill the dictionary Dim cell As Range For Each cell In rg dict(cell.Value) = cell.Offset(0, 1).Value Next ' Perform the Lookups For Each cell In rg Debug.Print dict(cell.Value) Next End Sub
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
In this Article
- VLOOKUP
- Application.WorksheetFunction.VLookup
- Application.VLookup vs Application.WokrsheetFunction.VLookup
- WorksheetFunction.XLOOKUP
This article will demonstrate how to use the VLOOKUP and XLOOKUP functions in VBA.
The VLOOKUP and XLOOKUP functions in Excel are extremely useful. They can also be used in VBA Coding.
VLOOKUP
There are two ways to call the VLOOKUP Function in VBA:
- Application.WorksheetFunction.Vlookup
- Application.Vlookup
The two methods worked identically, except for how they handle errors.
Application.WorksheetFunction.VLookup
This example will demonstrate the first method.
Here we’ve created a VLOOKUP formula in Excel that we will replicate in VBA:
Sub LookupPrice()
ActiveCell = Application.WorksheetFunction.VLookup(Range("E3"), Range("B2:C6"), 2, False)
End Sub
This will result in the following:
Note that the actual result was written to cell F3 instead of the formula!
If we wish to return a formula to Excel instead of a value, write the VLOOKUP into a formula:
Sub LookupPrice()
ActiveCell = "=VLOOKUP(E3,B2:C6,2,FALSE)"
End Sub
Or you can write the formula to a cell using R1C1 notation, which creates a formula with relative references that can be used over a range of cells:
Sub LookupPrice()
ActiveCell = "=VLOOKUP(RC[-1],RC[-4]:R[3]C[-3],2,FALSE)"
End Sub
You can also use variables to define the VLOOKUP inputs:
Sub LookupPrice()
Dim strProduct As String
Dim rng As Range
strProduct = Range("E3")
Set rng = Range("B2:C6")
ActiveCell = Application.WorksheetFunction.VLookup(strProduct, rng, 2, False)
End Sub
Of course, instead of writing the results of the function to a cell, you can write the results to a variable:
Sub LookupPrice()
Dim strProduct As String
Dim rng As Range
Dim strResult as String
strProduct = Range("E3")
Set rng = Range("B2:C6")
strResult = Application.WorksheetFunction.VLookup(strProduct, rng, 2, False)
End Sub
Application.VLookup vs Application.WokrsheetFunction.VLookup
In the examples above, we can use either of the methods and they will return the same result. However what if we were looking up a Product that doesn’t exist – what result would this return? Each function would return a very different result.
Normally when using VLOOKUP in Excel, if the Lookup does not find the correct answer, it returns #N/A back to the cell. However, if we use the example above and look for a product that does not exist, we will end up with a VBA Error.
We can trap for this error in our code and return a more user friendly message when the item we are looking for is not found.
Sub LookupPrice()
On Error GoTo eh
ActiveCell = Application.WorksheetFunction.VLookup(Range("E3"), Range("B2:C6"), 2, False)
Exit Sub
eh:
MsgBox "Product not found - please try another product"
End Sub
Alternatively, we can amend our VBA code to use Application.Vlookup instead of Application.WorksheetFunction.VLookup.
Sub LookupPrice()
ActiveCell = Application.VLookup(Range("E3"), Range("B2:C6"), 2, False)
End Sub
When we do this, the #N/A that we have come to expect when a lookup value is not found, is returned to the cell.
WorksheetFunction.XLOOKUP
The XLOOKUP function has been designed to replace the VLOOKUP and HLOOKUP functions in Excel. It is only available to Office 365 so using this function is quite restrictive is some of your users are using older versions of Excel.
It works in much the same ways in VBA as the VLOOKUP function.
Sub LookupPriceV()
ActiveCell = Application.WorksheetFunction.XLookup(Range("E3"), Range("B2:B6"), Range("C2:C6"))
End Sub
OR
Sub LookupPriceV()
ActiveCell = Application.XLookup(Range("E3"), Range("B2:B6"), Range("C2:C6"))
End Sub
Once again, if we wish to use variables, we can write the following code
Sub LookupPriceV()
Dim strProduct As String
Dim rngProduct As Range
Dim rngPrice As Range
strProduct = Range("E3")
Set rngProduct = Range("B2:B6")
Set rngPrice = Range("C2:C6")
ActiveCell = Application.WorksheetFunction.XLookup(strProduct, rngProduct, rngPrice)
End Sub
If we wish to return a formula to Excel instead of a value, we would need to write the formula into Excel with the VBA code.
Sub LookupPrice()
ActiveCell = "=XLOOKUP(E3,B3:B6,C3:C6)"
End Sub
Or you can write the formula to a cell using R1C1 notation.
Sub LookupPrice()
ActiveCell.Formula2R1C1 = "=XLOOKUP(RC[-1],RC[-4]:R[3]C[-4],RC[-3]:R[3]C[-3])"
End Sub
One of the major advantages of using XLOOKUP vs VLOOKUP is the ability to lookup a range of columns, and return the value in each column.
Lets look at the following example:
We have created the formula in cell H3 where it is looking up the values in the range C2:E6. Due to the fact that these are multiple columns, it will automatically populate columns I and J with the matching results found. The formula SPILLS over into columns I and J without us having to use CTRL+SHIFT for an array formula – this ability for the formula to SPILL across is one of the new additions for Excel 365.
To replicate this with VBA code, we can type the following in our macro:
Sub LookupPrice()
ActiveCell.Formula2R1C1 = "=XLOOKUP(RC[-1],RC[-6]:R[3]C[-6],RC[-5]:R[3]C[-3])"
End Sub
Where the formula is using the R1C1 (rows and columns) syntax instead of the A1 (range) syntax. This will result in the formulas being entered into Excel as shown in the graphic above.
You cannot lookup multiple columns if you are using the WorksheetFunction method.
In this VBA Tutorial, you learn how to use the VLookup function within your macros.
This VBA VLookup Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get immediate free access to this example workbook by clicking the button below.
Use the following Table of Contents to navigate to the section you’re interested in.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn about the Excel VBA Object Model here.
- Learn about using variables here.
- Learn about VBA data types here.
- Learn about working with worksheet functions within VBA here.
- Practical VBA applications and macro examples: Learn about working with worksheets here.
You can find additional VBA and Macro Tutorials in the Archives.
VBA Code to do a VLookup
To do a VLookup and assign the result to a variable, use a statement with the following structure:
VLookupResult = WorksheetFunction.vlookup(LookupValue, TableArray, ColumnIndex, False)Process Followed by VBA Code
VBA Statement Explanation
- Item: VLookupResult.
- VBA Construct: Variable.
- Description: Variable to which you assign the value returned by WorksheetFunction.VLookup.
If you explicitly declare a variable to represent VLookupResult, ensure that the data type you use can handle the possible values returned by WorksheetFunction.VLookup.
- Item: =.
- VBA Construct: = operator.
- Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
- Item: WorksheetFunction.vlookup.
- VBA Construct: WorksheetFunction.VLookup method.
- Description: Searches for a value in the first column of TableArray and returns a value in the same row but in column number ColumnIndex of TableArray.
- Item: LookupValue.
- VBA Construct: Arg1 (Lookup_value) parameter of WorksheetFunction.VLookup.
- Description: The value WorksheetFunction.VLookup searches in the first column of TableArray.
You can usually work with the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue. A question mark (?) represents any single character. An asterisk (*) represents any sequence of characters. If you want to include an actual question mark or asterisk (not as a wildcard) within LookupValue, add a tilde (~) immediately before the question mark (~?) or asterisk (~*).
Always ensure that there are no data type inconsistencies between LookupValue and the data stored in the first column of TableArray.
For these purposes, the main consideration is that, if LookupValue is of a numeric data type, the data stored within the first column of TableArray must not be stored as Text. Further considerations apply in more specific circumstances. For example, when dealing with a LookupValue of the Date data type, you can usually use the CLng type conversion function to convert the date LookupValue to the Long data type.
If you explicitly declare a variable to represent LookupValue, ensure that the data type you use can handle the value you look for.
- Item: TableArray.
- VBA Construct: Arg2 (Table_array) parameter of WorksheetFunction.VLookup.
- Description: Table (2 or more columns) with data. WorksheetFunction.VLookup searches for LookupValue in the first column of TableArray. The value returned by WorksheetFunction.VLookup is that located in the same row as LookupValue but column number ColumnIndex of TableArray.
If you explicitly declare a variable to represent TableArray, use a Range object variable.
- Item: ColumnIndex.
- VBA Construct: Arg3 (Col_index_num) parameter of WorksheetFunction.VLookup.
- Description: Column number within TableArray where WorksheetFunction.VLookup finds the value to return. For example:
- If you set ColumnIndex to 1, WorksheetFunction.VLookup returns a value from the first column of TableArray.
- If you set ColumnIndex to 2, WorksheetFunction.VLookup returns a value from the second column of TableArray.
- …
- If you set ColumnIndex to #, WorksheetFunction.VLookup returns a value from the #th column of TableArray.
If you explicitly declare a variable to represent ColumnIndex, use the Long data type.
- Item: False.
- VBA Construct: Arg4 (Range_lookup) parameter of WorksheetFunction.VLookup.
- Description: When set to False, Arg4 (Range_lookup) specifies that WorksheetFunction.VLookup looks only for an exact match of LookupValue in the first column of TableArray.
If WorksheetFunction.VLookup doesn’t find an exact match, it returns an error. If there are several exact matches, WorksheetFunction.VLookup returns the first value it finds.
You can set Arg4 (Range_lookup) to True. In such case, VBA looks for an approximate match. If WorksheetFunction.VLookup doesn’t find an exact match, it returns the next largest value that is less than LookupValue.
If you set Arg4 (Range_lookup) to True:
- The first column of TableArray must be organized in ascending order.
- You can’t generally use the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue.
Macro Example
The macro below does a VLookup according to the following conditions:
- LookupValue: “Raymond Allen” (myLookupValue variable).
- TableArray: The range of cells (within the active worksheet) defined by the following rows and columns:
- First row: 6 (myFirstRow variable).
- Last row: 305 (myLastRow variable).
- First column: 2 (myFirstColumn variable).
- Last column: 3 (myLastColumn variable).
- ColumnIndex: 2.
The value returned by WorksheetFunction.VLookup is assigned to the myVLookupResult variable. The macro displays a message box (MsgBox) which, among other information, includes the value held by myVLookupResult.
Sub basicVLookup() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-vlookup/ Dim myLookupValue As String Dim myFirstColumn As Long Dim myLastColumn As Long Dim myColumnIndex As Long Dim myFirstRow As Long Dim myLastRow As Long Dim myVLookupResult As Long Dim myTableArray As Range myLookupValue = "Raymond Allen" myFirstColumn = 2 myLastColumn = 3 myColumnIndex = 2 myFirstRow = 6 myLastRow = 305 With ActiveSheet Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With myVLookupResult = WorksheetFunction.vlookup(myLookupValue, myTableArray, myColumnIndex, False) MsgBox "Sales by " & myLookupValue & " are " & Format(myVLookupResult, "#,##0") End SubEffects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, the macro looks for “Raymond Allen” in the first column (Full Name) and returns the corresponding value in the second column (Sales) of the table with data.
#2: VLookup in Another Worksheet
VBA Code to do a VLookup in Another Worksheet
To do a VLookup in another (specific) worksheet and assign the result to a variable, use a statement with the following structure:
VLookupResult = WorksheetFunction.vlookup(LookupValue, Worksheet.TableArray, ColumnIndex, False)Process Followed by VBA Code
VBA Statement Explanation
- Item: VLookupResult.
- VBA Construct: Variable.
- Description: Variable to which you assign the value returned by WorksheetFunction.VLookup.
If you explicitly declare a variable to represent VLookupResult, ensure that the data type you use can handle the possible values returned by WorksheetFunction.VLookup.
- Item: =.
- VBA Construct: = operator.
- Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
- Item: WorksheetFunction.vlookup.
- VBA Construct: WorksheetFunction.VLookup method.
- Description: Searches for a value in the first column of TableArray and returns a value in the same row but in column number ColumnIndex of TableArray.
- Item: LookupValue.
- VBA Construct: Arg1 (Lookup_value) parameter of WorksheetFunction.VLookup.
- Description: The value WorksheetFunction.VLookup searches in the first column of TableArray.
You can usually work with the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue. A question mark (?) represents any single character. An asterisk (*) represents any sequence of characters. If you want to include an actual question mark or asterisk (not as a wildcard) within LookupValue, add a tilde (~) immediately before the question mark (~?) or asterisk (~*).
Always ensure that there are no data type inconsistencies between LookupValue and the data stored in the first column of TableArray.
For these purposes, the main consideration is that, if LookupValue is of a numeric data type, the data stored within the first column of TableArray must not be stored as Text. Further considerations apply in more specific circumstances. For example, when dealing with a LookupValue of the Date data type, you can usually use the CLng type conversion function to convert the date LookupValue to the Long data type.
If you explicitly declare a variable to represent LookupValue, ensure that the data type you use can handle the value you look for.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet that contains TableArray.
- Item: TableArray.
- VBA Construct: Arg2 (Table_array) parameter of WorksheetFunction.VLookup.
- Description: Table (2 or more columns) with data within Worksheet. WorksheetFunction.VLookup searches for LookupValue in the first column of TableArray. The value returned by WorksheetFunction.VLookup is that located in the same row as LookupValue but column number ColumnIndex of TableArray.
If you explicitly declare a variable to represent TableArray, use a Range object variable. In such case, include Worksheet in the reference you use to assign a Range object to the object variable.
- Item: ColumnIndex.
- VBA Construct: Arg3 (Col_index_num) parameter of WorksheetFunction.VLookup.
- Description: Column number within TableArray where WorksheetFunction.VLookup finds the value to return. For example:
- If you set ColumnIndex to 1, WorksheetFunction.VLookup returns a value from the first column of TableArray.
- If you set ColumnIndex to 2, WorksheetFunction.VLookup returns a value from the second column of TableArray.
- …
- If you set ColumnIndex to #, WorksheetFunction.VLookup returns a value from the #th column of TableArray.
If you explicitly declare a variable to represent ColumnIndex, use the Long data type.
- Item: False.
- VBA Construct: Arg4 (Range_lookup) parameter of WorksheetFunction.VLookup.
- Description: When set to False, Arg4 (Range_lookup) specifies that WorksheetFunction.VLookup looks only for an exact match of LookupValue in the first column of TableArray.
If WorksheetFunction.VLookup doesn’t find an exact match, it returns an error. If there are several exact matches, WorksheetFunction.VLookup returns the first value it finds.
You can set Arg4 (Range_lookup) to True. In such case, VBA looks for an approximate match. If WorksheetFunction.VLookup doesn’t find an exact match, it returns the next largest value that is less than LookupValue.
If you set Arg4 (Range_lookup) to True:
- The first column of TableArray must be organized in ascending order.
- You can’t generally use the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue.
Macro Example
The macro below does a VLookup according to the following conditions:
- LookupValue: “Raymond Allen” (myLookupValue variable).
- TableArray: The range of cells (within the worksheet named “VBA VLookup” in the active workbook) defined by the following rows and columns:
- First row: 6 (myFirstRow variable).
- Last row: 305 (myLastRow variable).
- First column: 2 (myFirstColumn variable).
- Last column: 3 (myLastColumn variable).
- ColumnIndex: 2.
The value returned by WorksheetFunction.VLookup is assigned to the myVLookupResult variable. The macro displays a message box (MsgBox) which, among other information, includes the value held by myVLookupResult.
Sub vLookupAnotherWorksheet() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-vlookup/ Dim myLookupValue As String Dim myFirstColumn As Long Dim myLastColumn As Long Dim myColumnIndex As Long Dim myFirstRow As Long Dim myLastRow As Long Dim myVLookupResult As Long Dim myTableArray As Range myLookupValue = "Raymond Allen" myFirstColumn = 2 myLastColumn = 3 myColumnIndex = 2 myFirstRow = 6 myLastRow = 305 With Worksheets("VBA VLookup") Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With myVLookupResult = WorksheetFunction.vlookup(myLookupValue, myTableArray, myColumnIndex, False) MsgBox "Sales by " & myLookupValue & " are " & Format(myVLookupResult, "#,##0") End SubEffects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, the macro looks for “Raymond Allen” in the first column (Full Name) and returns the corresponding value in the second column (Sales) of the table with data. In this example, the table with data is in a worksheet (VBA VLookup) that is different from the active worksheet (Blank Active Sheet).
#3: VLookup in Another Workbook
VBA Code to do a VLookup in Another Workbook
To do a VLookup in another (specific) workbook and assign the result to a variable, use a statement with the following structure:
VLookupResult = WorksheetFunction.vlookup(LookupValue, Workbook.Worksheet.TableArray, ColumnIndex, False)Process Followed by VBA Code
VBA Statement Explanation
- Item: VLookupResult.
- VBA Construct: Variable.
- Description: Variable to which you assign the value returned by WorksheetFunction.VLookup.
If you explicitly declare a variable to represent VLookupResult, ensure that the data type you use can handle the possible values returned by WorksheetFunction.VLookup.
- Item: =.
- VBA Construct: = operator.
- Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
- Item: WorksheetFunction.vlookup.
- VBA Construct: WorksheetFunction.VLookup method.
- Description: Searches for a value in the first column of TableArray and returns a value in the same row but in column number ColumnIndex of TableArray.
- Item: LookupValue.
- VBA Construct: Arg1 (Lookup_value) parameter of WorksheetFunction.VLookup.
- Description: The value WorksheetFunction.VLookup searches in the first column of TableArray.
You can usually work with the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue. A question mark (?) represents any single character. An asterisk (*) represents any sequence of characters. If you want to include an actual question mark or asterisk (not as a wildcard) within LookupValue, add a tilde (~) immediately before the question mark (~?) or asterisk (~*).
Always ensure that there are no data type inconsistencies between LookupValue and the data stored in the first column of TableArray.
For these purposes, the main consideration is that, if LookupValue is of a numeric data type, the data stored within the first column of TableArray must not be stored as Text. Further considerations apply in more specific circumstances. For example, when dealing with a LookupValue of the Date data type, you can usually use the CLng type conversion function to convert the date LookupValue to the Long data type.
If you explicitly declare a variable to represent LookupValue, ensure that the data type you use can handle the value you look for.
- Item: Workbook.
- VBA Construct: Application.Workbooks property.
- Description: Returns a Workbook object representing the workbook that contains Worksheet.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet (within Workbook) that contains TableArray.
- Item: TableArray.
- VBA Construct: Arg2 (Table_array) parameter of WorksheetFunction.VLookup.
- Description: Table (2 or more columns) with data within Worksheet. WorksheetFunction.VLookup searches for LookupValue in the first column of TableArray. The value returned by WorksheetFunction.VLookup is that located in the same row as LookupValue but column number ColumnIndex of TableArray.
If you explicitly declare a variable to represent TableArray, use a Range object variable. In such case, include Workbook and Worksheet in the reference you use to assign a Range object to the object variable.
- Item: ColumnIndex.
- VBA Construct: Arg3 (Col_index_num) parameter of WorksheetFunction.VLookup.
- Description: Column number within TableArray where WorksheetFunction.VLookup finds the value to return. For example:
- If you set ColumnIndex to 1, WorksheetFunction.VLookup returns a value from the first column of TableArray.
- If you set ColumnIndex to 2, WorksheetFunction.VLookup returns a value from the second column of TableArray.
- …
- If you set ColumnIndex to #, WorksheetFunction.VLookup returns a value from the #th column of TableArray.
If you explicitly declare a variable to represent ColumnIndex, use the Long data type.
- Item: False.
- VBA Construct: Arg4 (Range_lookup) parameter of WorksheetFunction.VLookup.
- Description: When set to False, Arg4 (Range_lookup) specifies that WorksheetFunction.VLookup looks only for an exact match of LookupValue in the first column of TableArray.
If WorksheetFunction.VLookup doesn’t find an exact match, it returns an error. If there are several exact matches, WorksheetFunction.VLookup returns the first value it finds.
You can set Arg4 (Range_lookup) to True. In such case, VBA looks for an approximate match. If WorksheetFunction.VLookup doesn’t find an exact match, it returns the next largest value that is less than LookupValue.
If you set Arg4 (Range_lookup) to True:
- The first column of TableArray must be organized in ascending order.
- You can’t generally use the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue.
Macro Example
The macro below does a VLookup according to the following conditions:
- LookupValue: “Raymond Allen” (myLookupValue variable).
- TableArray: The range of cells (within the worksheet named “VBA VLookup” in the workbook named “Excel VBA VLookup”) defined by the following rows and columns:
- First row: 6 (myFirstRow variable).
- Last row: 305 (myLastRow variable).
- First column: 2 (myFirstColumn variable).
- Last column: 3 (myLastColumn variable).
- ColumnIndex: 2.
The value returned by WorksheetFunction.VLookup is assigned to the myVLookupResult variable. The macro displays a message box (MsgBox) which, among other information, includes the value held by myVLookupResult.
Sub vLookupAnotherWorkbook() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-vlookup/ Dim myLookupValue As String Dim myFirstColumn As Long Dim myLastColumn As Long Dim myColumnIndex As Long Dim myFirstRow As Long Dim myLastRow As Long Dim myVLookupResult As Long Dim myTableArray As Range myLookupValue = "Raymond Allen" myFirstColumn = 2 myLastColumn = 3 myColumnIndex = 2 myFirstRow = 6 myLastRow = 305 With Workbooks("Excel VBA VLookup").Worksheets("VBA VLookup") Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With myVLookupResult = WorksheetFunction.vlookup(myLookupValue, myTableArray, myColumnIndex, False) MsgBox "Sales by " & myLookupValue & " are " & Format(myVLookupResult, "#,##0") End SubEffects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, the macro looks for “Raymond Allen” in the first column (Full Name) and returns the corresponding value in the second column (Sales) of the table with data. In this example, that data is in a workbook (Excel VBA VLookup) that is different from the active workbook (Book1).
#4: VLookup Error Handling when Using the Application.WorksheetFunction Property
VBA Code to Handle VLookup Errors when Using the Application.WorksheetFunction Property
To handle VLookup errors when using the Application.WorksheetFunction property, use a macro with the following statement structure:
On Error Resume Next VLookupResult = WorksheetFunction.vlookup(LookupValue, TableArray, ColumnIndex, False) If Err.Number = 0 Then StatementsIfNoError Else StatementsIfError End IfProcess Followed by VBA Code
VBA Statement Explanation
Line #1: On Error Resume Next
- Item: On Error Resume Next.
- VBA Construct: On Error Resume Next statement.
- Description: Specifies that, when a run-time error occurs, control goes to the statement following the statement where the error occurs.
The error-handler in this line #1 is necessary to handle the possible run-time errors that line #2 below (with WorksheetFunction.VLookup) can generate.
When using the On Error Resume Next statement within your macros, consider whether it’s appropriate to later disable the error handler explicitly by, for example, using the On Error GoTo 0 statement.
Line #2: VLookupResult = WorksheetFunction.vlookup(LookupValue, TableArray, ColumnIndex, False)
- Item: VLookupResult.
- VBA Construct: Variable.
- Description: Variable to which you assign the value returned by WorksheetFunction.VLookup.
If you explicitly declare a variable to represent VLookupResult, ensure that the data type you use can handle the possible values returned by WorksheetFunction.VLookup.
- Item: =.
- VBA Construct: = operator.
- Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
- Item: WorksheetFunction.vlookup.
- VBA Construct: WorksheetFunction.VLookup method.
- Description: Searches for a value in the first column of TableArray and returns a value in the same row but in column number ColumnIndex of TableArray.
- Item: LookupValue.
- VBA Construct: Arg1 (Lookup_value) parameter of WorksheetFunction.VLookup.
- Description: The value WorksheetFunction.VLookup searches in the first column of TableArray.
You can usually work with the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue. A question mark (?) represents any single character. An asterisk (*) represents any sequence of characters. If you want to include an actual question mark or asterisk (not as a wildcard) within LookupValue, add a tilde (~) immediately before the question mark (~?) or asterisk (~*).
Always ensure that there are no data type inconsistencies between LookupValue and the data stored in the first column of TableArray.
For these purposes, the main consideration is that, if LookupValue is of a numeric data type, the data stored within the first column of TableArray must not be stored as Text. Further considerations apply in more specific circumstances. For example, when dealing with a LookupValue of the Date data type, you can usually use the CLng type conversion function to convert the date LookupValue to the Long data type.
If you explicitly declare a variable to represent LookupValue, ensure that the data type you use can handle the value you look for.
- Item: TableArray.
- VBA Construct: Arg2 (Table_array) parameter of WorksheetFunction.VLookup.
- Description: Table (2 or more columns) with data. WorksheetFunction.VLookup searches for LookupValue in the first column of TableArray. The value returned by WorksheetFunction.VLookup is that located in the same row as LookupValue but column number ColumnIndex of TableArray.
If you explicitly declare a variable to represent TableArray, use a Range object variable.
- Item: ColumnIndex.
- VBA Construct: Arg3 (Col_index_num) parameter of WorksheetFunction.VLookup.
- Description: Column number within TableArray where WorksheetFunction.VLookup finds the value to return. For example:
-
- If you set ColumnIndex to 1, WorksheetFunction.VLookup returns a value from the first column of TableArray.
- If you set ColumnIndex to 2, WorksheetFunction.VLookup returns a value from the second column of TableArray.
- …
- If you set ColumnIndex to #, WorksheetFunction.VLookup returns a value from the #th column of TableArray.
If you explicitly declare a variable to represent ColumnIndex, use the Long data type.
-
- Item: False.
- VBA Construct: Arg4 (Range_lookup) parameter of WorksheetFunction.VLookup.
- Description: When set to False, Arg4 (Range_lookup) specifies that WorksheetFunction.VLookup looks only for an exact match of LookupValue in the first column of TableArray.
If WorksheetFunction.VLookup doesn’t find an exact match, it returns an error. If there are several exact matches, WorksheetFunction.VLookup returns the first value it finds.
You can set Arg4 (Range_lookup) to True. In such case, VBA looks for an approximate match. If WorksheetFunction.VLookup doesn’t find an exact match, it returns the next largest value that is less than LookupValue.
If you set Arg4 (Range_lookup) to True:
- The first column of TableArray must be organized in ascending order.
- You can’t generally use the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue.
Line #3: If Err.Number = 0 Then
- Item: If … Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statements within the If… Then block (line #4 below) if the condition specified by item #3 below is met. If the condition isn’t met, the statements following the Else clause (line #6 below) are executed.
- Item: Err.Number.
- VBA Construct: Err object and Number property.
- Description: The Err object holds information about run-time errors. The Number property returns a numeric value that identifies the error that occurred.
- Item: Err.Number = 0.
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is a numeric expression that evaluates to True or False as follows:
- True: When the Number property of the Err object (Err.Number) returns 0. This is the case when there’s no error.
- False: When the Number property of the Err object (Err.Number) returns a number other than 0. This is the case when an error occurs.
Line #4: StatementsIfNoError
- Item: StatementsIfNoError.
- VBA Construct: Statements within If… Then… Else statement.
- Description: Statements that VBA executes if the condition tested in the opening line of the If… Then… Else statement (line #3 above) is met and returns True. Therefore, these are 1 or more statements that are executed when there’s no error (Err.Number = 0).
Line #5: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statement(s) following the Else clause (line #6 below) are executed if the condition tested in the opening line of the If… Then… Else statement (line #3 above) isn’t met and returns False (Err.Number isn’t 0).
Line #6: StatementsIfError
- Item: StatementsIfError.
- VBA Construct: Else Statements of If… Then… Else statement.
- Description: Statements that VBA executes if the condition tested in the opening line of the If… Then… Else statement (line #3 above) isn’t met and returns False (Err.Number isn’t 0). Therefore, these are 1 or more statements that are executed when there’s an error.
Line #7: End If
- Item: End If.
- VBA Construct: Closing line of If… Then… Else statement.
- Description: Closes the If… Then… Else statement that opened in line #3 above.
Macro Example
The macro below does a VLookup according to the following conditions:
- LookupValue: “Jorge A. Gomez” (myLookupValue variable).
- TableArray: The range of cells (within the worksheet named “VBA VLookup” in the workbook containing the VBA code) defined by the following rows and columns:
- First row: 6 (myFirstRow variable).
- Last row: 305 (myLastRow variable).
- First column: 2 (myFirstColumn variable).
- Last column: 3 (myLastColumn variable).
- ColumnIndex: 2.
The value returned by WorksheetFunction.VLookup is assigned to the myVLookupResult variable. The macro displays a message box (MsgBox) whose contents depend on whether an error has occurred:
- If no error occurs, the message box displays, among other information, the value held by myVLookupResult.
- If an error occurs, the message box displays a confirmation that it didn’t found a match for the LookupValue within the first column of TableArray.
Sub vLookupHandleError() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-vlookup/ Dim myLookupValue As String Dim myFirstColumn As Long Dim myLastColumn As Long Dim myColumnIndex As Long Dim myFirstRow As Long Dim myLastRow As Long Dim myVLookupResult As Long Dim myTableArray As Range myLookupValue = "Jorge A. Gomez" myFirstColumn = 2 myLastColumn = 3 myColumnIndex = 2 myFirstRow = 6 myLastRow = 305 With ThisWorkbook.Worksheets("VBA VLookup") Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With On Error Resume Next myVLookupResult = WorksheetFunction.vlookup(myLookupValue, myTableArray, myColumnIndex, False) If Err.Number = 0 Then MsgBox "Sales by " & myLookupValue & " are " & Format(myVLookupResult, "#,##0") Else MsgBox "The Table doesn't contain sales data for " & myLookupValue End If End SubEffects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, the macro looks for “Jorge A. Gomez” in the first column (Full Name). The macro handles the error caused by the fact that no match for this LookupValue is found in that first column.
#5: VLookup Error Handling when Using the Application Object
VBA Code to Handle VLookup Errors when Using the Application Object
To handle VLookup errors when using the Application object, use a macro with the following statement structure:
Dim VLookupResult As Variant VLookupResult = Application.vlookup(LookupValue, TableArray, ColumnIndex, False) If IsError(VLookupResult) = False Then StatementsIfNoError Else StatementsIfError End IfProcess Followed by VBA Code
VBA Statement Explanation
Line #1: Dim VLookupResult As Variant
- Item: Dim myVLookupResult As Variant.
- VBA Construct: Dim statement.
- Description:
- Declares a new variable (VLookupResult) as of the Variant data type.
- VLookupResult is the variable to which you assign the value returned by Application.VLookup in line #2 below.
- Declaring the VLookupResult variable as of the Variant data type allows the variable to hold an error value if Application.VLookup in line #2 below returns an error.
Line #2: VLookupResult = Application.vlookup(LookupValue, TableArray, ColumnIndex, False)
- Item: VLookupResult.
- VBA Construct: Variable of the Variant data type.
- Description: Variable to which you assign the value returned by Application.VLookup.
- Item: =.
- VBA Construct: = operator.
- Description: Assigns the value returned by Application.VLookup to the VLookupResult variable.
- Item: Application.vlookup.
- VBA Construct: WorksheetFunction.VLookup method.
- Description: Searches for a value in the first column of TableArray and returns a value in the same row but in column number ColumnIndex of TableArray.
- Item: LookupValue.
- VBA Construct: Arg1 (Lookup_value) parameter of Application.VLookup.
- Description: The value Application.VLookup searches in the first column of TableArray.
You can usually work with the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue. A question mark (?) represents any single character. An asterisk (*) represents any sequence of characters. If you want to include an actual question mark or asterisk (not as a wildcard) within LookupValue, add a tilde (~) immediately before the question mark (~?) or asterisk (~*).
Always ensure that there are no data type inconsistencies between LookupValue and the data stored in the first column of TableArray.
For these purposes, the main consideration is that, if LookupValue is of a numeric data type, the data stored within the first column of TableArray must not be stored as Text. Further considerations apply in more specific circumstances. For example, when dealing with a LookupValue of the Date data type, you can usually use the CLng type conversion function to convert the date LookupValue to the Long data type.
If you explicitly declare a variable to represent LookupValue, ensure that the data type you use can handle the value you look for.
- Item: TableArray.
- VBA Construct: Arg2 (Table_array) parameter of Application.VLookup.
- Description: Table (2 or more columns) with data. Application.VLookup searches for LookupValue in the first column of TableArray. The value returned by Application.VLookup is that located in the same row as LookupValue but column number ColumnIndex of TableArray.
If you explicitly declare a variable to represent TableArray, use a Range object variable.
- Item: ColumnIndex.
- VBA Construct: Arg3 (Col_index_num) parameter of Application.VLookup.
- Description: Column number within TableArray where Application.VLookup finds the value to return. For example:
-
- If you set ColumnIndex to 1, Application.VLookup returns a value from the first column of TableArray.
- If you set ColumnIndex to 2, Application.VLookup returns a value from the second column of TableArray.
- …
- If you set ColumnIndex to #, Application.VLookup returns a value from the #th column of TableArray.
If you explicitly declare a variable to represent ColumnIndex, use the Long data type.
-
- Item: False.
- VBA Construct: Arg4 (Range_lookup) parameter of Application.VLookup.
- Description: When set to False, Arg4 (Range_lookup) specifies that Application.VLookup looks only for an exact match of LookupValue in the first column of TableArray.
If Application.VLookup doesn’t find an exact match, it returns an error. If there are several exact matches, Application.VLookup returns the first value it finds.
You can set Arg4 (Range_lookup) to True. In such case, VBA looks for an approximate match. If Application.VLookup doesn’t find an exact match, it returns the next largest value that is less than LookupValue.
If you set Arg4 (Range_lookup) to True:
- The first column of TableArray must be organized in ascending order.
- You can’t generally use the wildcard characters question mark (?) and asterisk (*) when specifying a text LookupValue.
Line #3: If IsError(VLookupResult) = False Then
- Item: If … Then.
- VBA Construct: Opening line of If… Then… Else statement.
- Description: Conditionally executes the statements within the If… Then block (line #4 below) if the condition specified by item #3 below is met.
- Item: IsError (VLookupResult).
- VBA Construct: IsError Function.
- Description: IsError returns a Boolean (True or False) indicating whether the applicable expression (VLookupResult) in an error value.
VLookupResult holds the value returned by Application.VLookup in line #2 above. If Application.VLookup returns an error, VLookupResult holds that error.
- Item: IsError(VLookupResult) = False.
- VBA Construct: Condition of If… Then… Else statement.
- Description: This condition is a numeric expression that evaluates to True or False as follows:
- True: When IsError returns False. This is the case when Application.VLookup doesn’t return an error.
- False: When IsError returns True. This is the case when Application.VLookup returns an error.
Line #4: StatementsIfNoError
- Item: StatementsIfNoError.
- VBA Construct: Statements within If… Then… Else statement.
- Description: Statements that VBA executes if the condition tested in the opening line of the If… Then… Else statement (line #3 above) is met and returns True. Therefore, these are 1 or more statements that are executed when there’s no error (IsError(VLookupResult) = False).
Line #5: Else
- Item: Else.
- VBA Construct: Else clause of If… Then… Else statement.
- Description: The statement(s) following the Else clause (line #6 below) are executed if the condition tested in the opening line of the If… Then… Else statement (line #3 above) isn’t met and returns False (IsError(VLookupResult) isn’t False).
Line #6: StatementsIfError
- Item: StatementsIfError.
- VBA Construct: Else Statements of If… Then… Else statement.
- Description: Statements that VBA executes if the condition tested in the opening line of the If… Then… Else statement (line #3 above) isn’t met and returns False (IsError(VLookupResult) isn’t False). Therefore, these are 1 or more statements that are executed when there’s an error.
Line #7: End If
- Item: End If.
- VBA Construct: Closing line of If… Then… Else statement.
- Description: Closes the If… Then… Else statement that opened in line #3 above.
Macro Example
The macro below does a VLookup according to the following conditions:
- LookupValue: “Jorge A. Gomez” (myLookupValue variable).
- TableArray: The range of cells (within the worksheet named “VBA VLookup” in the workbook containing the VBA code) defined by the following rows and columns:
- First row: 6 (myFirstRow variable).
- Last row: 305 (myLastRow variable).
- First column: 2 (myFirstColumn variable).
- Last column: 3 (myLastColumn variable).
- ColumnIndex: 2.
The value returned by WorksheetFunction.VLookup is assigned to the myVLookupResult variable. The macro displays a message box (MsgBox), whose contents depend on whether an error has occurred:
- If no error occurs, the message box displays, among other information, the value held by myVLookupResult.
- If an error occurs, the message box displays a confirmation that it didn’t found a match for the LookupValue within the first column of TableArray.
Sub vLookupHandleErrorAlternative() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-vlookup/ Dim myLookupValue As String Dim myFirstColumn As Long Dim myLastColumn As Long Dim myColumnIndex As Long Dim myFirstRow As Long Dim myLastRow As Long Dim myVLookupResult As Variant Dim myTableArray As Range myLookupValue = "Jorge A. Gomez" myFirstColumn = 2 myLastColumn = 3 myColumnIndex = 2 myFirstRow = 6 myLastRow = 305 With ThisWorkbook.Worksheets("VBA VLookup") Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn)) End With myVLookupResult = Application.vlookup(myLookupValue, myTableArray, myColumnIndex, False) If IsError(myVLookupResult) = False Then MsgBox "Sales by " & myLookupValue & " are " & Format(myVLookupResult, "#,##0") Else MsgBox "The Table doesn't contain sales data for " & myLookupValue End If End SubEffects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, the macro looks for “Jorge A. Gomez” in the first column (Full Name). The macro handles the error caused by the fact that no match for this LookupValue is found in that first column.
Learn more about Excel VBA VLookup
You can get immediate free access to the example Excel workbook that accompanies this Excel VBA VLookup Tutorial by clicking the button below.