Vba excel worksheetfunction vlookup

Поиск значения в таблице (диапазоне, массиве) по значению в первом столбце таблицы с помощью метода 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 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.

vlookup formula

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:

vlookup value

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.

vlookup 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.

vlookup notfound

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:

vlookup-xlookkup

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.

“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:

VBA VLookup

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.

VBA Lookup

 
VBA Lookup

 
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

  1. lookup_value – The value to look up. It must be in the first column of the range.
  2. table_array – This is the range to search. This can also be a VBA array although it very slow using this.
  3. col_index_num – This contains the column number of the return value. Starts at column number one.
  4. 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:

  1. If the number is stored as text then the search value must be a string.
  2. 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

VBA Lookup

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.

VBA Lookup

© 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

VBA VLookup

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

VBA VLookup 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:

  1. Ensure the Table/Range is correct.
  2. Ensure the Table/Range does not include the header(VBA will think list is unsorted).
  3. Ensure the Table/Range is using the correct worksheet.
  4. If searching for a number use a long or double data type in the lookup_value parameter. See lookup_value section above
  5. If searching for a number stored as text use a string data type in the lookup_value parameter.
  6. 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:

  1. 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.)

VLOOKUP is a worksheet function in Excel, but we can also use it in VBA. The functionality of VLOOKUP is similar to the functionality in VBA and worksheets. As it is a worksheet function, the method to use VLOOKUP in VBA is through Application.WorksheetFunction method and the arguments remain the same.

VLOOKUP Function in Excel VBA

The VLOOKUP function in ExcelThe 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
searches a value in an array and returns its corresponding value from another column. The value to search should be present in the first column. It is also required to mention whether to look for an exact or approximate match. We can use the worksheet function VLOOKUP in VBA coding. However, the function is not built-in VBA. Thus, we can only call using the worksheet.

The VLOOKUP function in Excel has the following syntax:

Vlookup formula

In which lookup_value is the value to look for, table_arrray is the table, col_index_num is the column number of the return value, and range_lookup signifies if the match is exact or approximate. The range_lookup can be TRUE/FALSE or 0/1.

In VBA code, one can use the VLOOKUP function:

Application.WorksheetFunction.vlookup(lookup_value, table_array, col_index_num, range_lookup)

Table of contents
  • VLOOKUP Function in Excel VBA
    • How to Use VLookup in Excel VBA?
      • VLookup Code in Excel VBA Example #1
      • VLookup Code in Excel VBA Example #2
      • VLookup Code in Excel VBA Example #3
    • Things to Remember About VLookup in Excel VBA
    • Recommended Articles

How to Use VLookup in Excel VBA?

Below are some examples of the VLOOKUP code in Excel VBA.

You can download this VLookup in Excel VBA Template here – VLookup in Excel VBA Template

VLookup Code in Excel VBA Example #1

Let us see how we can call the worksheet function VLOOKUP in Excel VBA.

Suppose you have the data on students’ IDs, names, and average marks.

Vlookup with Vba Example 1

Now, you want to look up the marks obtained by a student with ID 11004.

To lookup for the value, follow the following steps:

  • Go to the “Developer” tab and click on “Visual Basic.”

Vlookup with Vba Example 1-1

  • Under the VBA window, go to “Insert” and click on “Module.”

Vlookup with Vba Example 1-2

  • Now, write the VBA VLOOKUP code. For example, we can use the following VBA VLOOKUP code.

Sub vlookup1()
Dim student_id As Long
Dim marks As Long
student_id = 11004
Set myrange = Range(“B4:D8”)
marks = Application.WorksheetFunction.VLookup(student_id, myrange, 3, False)
End Sub

Firstly, define a student ID, which is the lookup value. Therefore, we define:

student_id = 11004

Next, we define the range in which the value and the return value exist. Since our data is present in the cells B4:D8, we define a range- myrange as:

Set myrange = Range(“B4:D8”)

Finally, we input the VLOOKUP function using the Worksheet function in a variable marks as:

marks = Application.WorksheetFunction.VLookup(student_id, myrange, 3, False)

To print the marks in a message box, let us use the following command:

MsgBox “Student with ID:” & student_id & ” obtained ” & marks & ” marks”

Vlookup with Vba Example 1-3

It will return:

A student with ID:11004 obtained 85 marks.

Now, click the run button.

You will notice that a message box will appear in the Excel sheet.

Vlookup with Vba Example 1-4

VLookup Code in Excel VBA Example #2

Suppose you have the data on the names of employees and their salaries. The data is in columns B and C. Next, you must write a VBA VLOOKUP code, given the employee’s name in cell F4. It will return the employee’s salary in cell G4.

Vlookup with Vba Example 2

Let us write the VBA VLOOKUP code.

  1. Define the range in which the values are present, i.e., columns B and C.

Set myrange = Range (“B:C”)

  1. Define the employee’s name and input the name from cell F4.

Set name = Range (“F4”)

  1. Define salary as cell G4.

Set salary = Range (“G4”)

  1. Now, call the VLOOKUP function using WorksheetFunction in VBA and input it in salary.Value. It will return the value (output of the VLOOKUP function) in cell G4. We can use the following syntax:

salary.Value = Application.WorksheetFunction.VLookup(name, myrange, 2, False)

Vlookup with Vba Example 2-1

  1. Now, run the module. Cell G4 will contain the employee’s salary after you run the VBA VLOOKUP code.

Vlookup with Vba Example 2-2

Suppose you change the value of cell F4 to “David” in the worksheet and re-run the code, which will return David’s salary.

Vlookup with Vba Example 2-3

VLookup Code in Excel VBA Example #3

Suppose you have your company’s employees’ data, ID, names, Department, and salary. Using VLOOKUP in VBA, you want to get the salary details of an employee using his name and department.

Vlookup with Vba Example 3

Since the VLOOKUP function in Excel searches the lookup_value in only a single column, which is the first column of the table_array. It would help if you first made a column containing each employee’s “Name” and “Department.”

In VBA, let us insert the values “Name” and “Department” in column B of the worksheet.

To do this, go to the “Developer” tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more and click “Visual Basic.” Then, go to “Insert” and click on “Module” to start a new module.

Let us now write code such that column B contains the values of column D (name) and column E.

The syntax is:

Vlookup with Vba Example 3-1

Firstly, use a ‘for’ loop from i = 4 since the values start from the 4th row in this case. The loop will continue until the end of the last row of column C. So, we can use the variable as a row number inside the ‘for’ loop.

Then, enter the value to assign for Cell (row_number, column B), which we can give as Cells (i, “B”).Value, as Cell (row_number, column D) & “_” & Cell (row_number, column E).

Suppose you want to assign the cell B5 = D5 & “_” & E5. Then, you can simply use the code as:

Cells(5, “B”).Value = Cells(5, “D”).Value & “_” & Cells(5, “E”).Value

Vlookup with Vba Example 3-2

Now, let’s look for the lookup value in the array B5:E24. You need first to enter the lookup value. Let us take the value (Name and Department) from the user. To do this,

  1. Define three variables: name, department, and lookup_val as a string.
  2. Take the name input from the user. Use the code:

name = InputBox (“Enter the name of the employee”)

The content in the input box “Enter the ..” will be displayed in the prompt box when you run the code. The string entered in the prompt will be assigned to the name variable.

  1. Take the department from the user. We can do this similarly as above.

department = InputBox (“Enter the department of the employee”)

  1. Assign the name and department with “_” as a separator to the variable lookup_val using the following syntax:

lookup_val = name & “_” & department

Vlookup with Vba Example 3-3

  1. Write the VLOOKUP syntax to search for the lookup_val in range B5:E24 and return it in a variable salary.

Initialize the variable salary:

Dim salary As Long

Use the VLOOKUP function to find the lookup_val. We can give the table_array as Range(“B:F”), and the salary is in the 5th column. We can thus use the following syntax:

salary = Application.WorksheetFunction.VLookup(lookup_val, Range (“B:F”), 5, False)

  1. To print the salary in a message box, use the syntax:

MsgBox (The salary of the employee is ” & salary)

Vlookup with Vba Example 3-4

Now, run the code. A prompt box will appear in the worksheet where you can enter the name after you enter the name (Say “Sashi”) and click “OK.”

Vlookup with Vba Example 3-5

It will open another box in which you can enter the department. After you enter the department, say IT.

Example 3-6

It will print the salary of the employee.

Example 3-7

If VLOOKUP can’t find any employee with the name and department, it will give an error. For example, suppose you give the name “Vishnu” and the department “IT,” it will return “Run-time error ‘1004’.”

Example 3-8

To address this issue, you can specify that on this type of error, print “Value not found” instead. To do this,

  1. Before using the vlookup syntax, use the following code:

On Error GoTo Message

Check:

The trailing code (of Check:) will be monitored, and if it receives an error, it will go to the “message” statement

  1. At the end of the code (Before End Sub), specify that if the error number is 1004VBA 1004 Error is a runtime error in VBA that is also known as an application-defined or object-defined error. Because Excel has a limited number of columns, we get a 1004 error when our code gives the command to go out of range.read more, then print in the message box, “Employee data not present.” One can do this using the syntax:

Message:

If Err.Number = 1004 Then

MsgBox (“Employee data not present”)

End If

Example 3-9

Example 3-10

Module 1:

Sub vlookup3()
For i = 4 To Cells(Rows.Count, “C”).End(xlUp).Row
Cells(i, “B”).Value = Cells(i, “D”).Value & “_” & Cells(i, “E”).Value
Next iDim name As String
Dim department As String
Dim lookup_val As String
Dim salary As Longname = InputBox(“Enter the name of the employee”)
department = InputBox(“Enter the department of the employee”)
lookup_val = name & “_” & departmentOn Error GoTo Message
check:
salary = Application.WorksheetFunction.VLookup(lookup_val, Range (“B:F”), 5, False)
MsgBox (“The salary of the employee is ” & salary)Message:
If Err.Number = 1004 Then
MsgBox (“Employee data not present”)
End IfEnd Sub

Things to Remember About VLookup in Excel VBA

  • The VLOOKUP function can be called in Excel VBA by using WorksheetFunction.
  • The syntax of the VLOOKUP function remains the same in Excel VBA.
  • When the VBA VLOOKUP code cannot find the lookup_value, it will give a “1004 error.”
  • We can manage the error in the VLOOKUP function using a GoTo statement if it returns an error.

Recommended Articles

This article has been a guide to VLOOKUP in VBA. Here, we discuss writing VLOOKUP code in Excel VBA, practical examples, and a downloadable Excel template. You may learn more about Excel from the following articles: –

  • Top Alternatives to Vlookup
  • IFERROR with VLOOKUP in Excel
  • VLOOKUP with Two Criteria
  • Multiple Criteria of VLookup

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.

VLOOKUP in VBA Example 1

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

Example 1 Message Box

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.

VLookup Employee Tables Example 3

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

VBA VLOOKUP Example 4

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.

VLookup For Example 4

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

Message Box Output Example 4

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.

VLookup Employee Tables Example 3

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

VLOOKUP in VBA paste formula

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 .

Понравилась статья? Поделить с друзьями:
  • Vba excel worksheetfunction countif
  • Vba excel worksheet visible
  • Vba excel worksheet selectionchanged
  • Vba excel активировать папку
  • Vba excel userform убрать кнопку закрыть