Vba excel это впр

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

Excel VBA Tutorial about how to use the VLookup function in macros

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.

Get immediate free access to the Excel VBA VLookup file example

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

Look for LookupValue in first column; return value

VBA Statement Explanation

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

  2. Item: =.
    • VBA Construct: = operator.
    • Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
  3. 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.
  4. 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.

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

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

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

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

Macro does VLookup

#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

Look for LookupValue in first column in another worksheet; return value

VBA Statement Explanation

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

  2. Item: =.
    • VBA Construct: = operator.
    • Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
  3. 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.
  4. 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.

  5. Item: Worksheet.
    • VBA Construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the worksheet that contains TableArray.
  6. 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.

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

  8. 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 Sub

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

Macro does VLookup in another worksheet

#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

Look for VLookup value in another workbook; return value

VBA Statement Explanation

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

  2. Item: =.
    • VBA Construct: = operator.
    • Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
  3. 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.
  4. 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.

  5. Item: Workbook.
    • VBA Construct: Application.Workbooks property.
    • Description: Returns a Workbook object representing the workbook that contains Worksheet.
  6. Item: Worksheet.
    • VBA Construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the worksheet (within Workbook) that contains TableArray.
  7. 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.

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

  9. 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 Sub

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

Macro does VLookup in another workbook

#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 If

Process Followed by VBA Code

Enable error-handling; look for LookupValue; return value; test if error occurred

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)

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

  2. Item: =.
    • VBA Construct: = operator.
    • Description: Assigns the value returned by WorksheetFunction.VLookup to the VLookupResult variable.
  3. 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.
  4. 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.

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

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

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

  1. 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.
  2. 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.
  3. 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 Sub

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

Macro does VLookup and handles error

#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 If

Process Followed by VBA Code

Declare VLookupResult as Variant variable; look for LookupValue; return value; test if VLookupResult holds errors

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)

  1. Item: VLookupResult.
    • VBA Construct: Variable of the Variant data type.
    • Description: Variable to which you assign the value returned by Application.VLookup.
  2. Item: =.
    • VBA Construct: = operator.
    • Description: Assigns the value returned by Application.VLookup to the VLookupResult variable.
  3. 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.
  4. 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.

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

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

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

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

  3. 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 Sub

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

Macro handles VLookup error

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.

Get immediate free access to the Excel VBA VLookup file example

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 .

“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

VBA VLOOKUP Function

VBA VLOOKUP Function (Table of Contents)

  • Where to Write Macros?
  • How to Use VBA VLOOKUP in Excel?

What is VBA VLOOKUP Function?

Vlookup function of excel can be used in the VBA as well with the same syntax that we used in Excel.  Open a module in VBA and define a variable for Lookup value and then declare the cell where we will be applying Vlookup using VBA. Now as per syntax of Vlookup in VBA select the lookup value, lookup range or table, Column index number and range lookup is TRUE or FALSE. Now, if we run the code, then we will be able to see the lookup value in a declared cell in Excel.

Formula of VLOOKUP Function

The Formula includes 4 mandatory arguments.

VLOOKUP Syntax

  • Lookup Value: This is the base values you are searching. Based on this we look for a value in the table.
  • Table Value: This is the table which holds all the values. From this table using lookup value, we will fetch the data.
  • Column Index Number: This is the column number from the table we are looking for. In a table, there are many columns, out of many columns we only require the column which we are looking for the data.
  • Range Lookup: Here we need to specify what kind of result we want. If we want the exact match we need to mention as FALSE or 0, if we want the approximate match we can mention as TRUE or 1.

Where to Write Macros?

VBA is accommodated under Developer tab in excel. If you are not able to find the developer tab follow the below steps to unhide this.

Step 1: Click on File.

VBA VLOOKUP Step 1

Step 2: Under File, click on Options.

VBA VLOOKUP Step 2

Step 3: Select Customize Ribbon.

VBA VLOOKUP Step 3

Step 4: On the right-hand side make sure the checkbox of the Developer tab is ticked.

VBA VLOOKUP Step 4

Now you must see the Developer tab in the Ribbon.

VBA VLOOKUP Step 5

How to Use VBA VLOOKUP Function in Excel?

VBA VLOOKUP Function is very simple to use. Let us now see how to use VBA VLOOKUP function in Excel with the help of some examples.

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

Example #1

I have a sales table for different products. It has product name and sales made against that product.

VBA VLOOKUP Example 1-1

In cell E2, I want to know the sales value of TV using VBA VLOOKUP function.

Step 1: Go to the Developer tab and click on Visual Basic

VBA VLOOKUP Example 1-2

Step 2: Once you click on Visual Basic it will open the below window for you

VBA VLOOKUP Example 1-3

Step 3: Click on Insert and select Module

VBA VLOOKUP Example 1-4

Step 4: Once you click on Module it will insert the new module for you. Double click on that newly inserted module to write your VLOOKUP code.

VBA VLOOKUP Example 1-5

Step 5: Copy and paste the below code to your newly inserted module.

Sub Vlookup_Example()
Dim rng As Range, FinalResult As Variant
Set rng = Sheets("Example 1").Range("E2")
FinalResult = Application. WorksheetFunction. VLookup(Range("D2"), Range("A2:B7"), 2, False)
rng = FinalResult
End Sub

VBA VLOOKUP Example 1-6

Let me break down the code to explain it to you.

Line 1: Dim rng as Range, FinalResult as Variant

This is the first line of the code. Using DIM statement I have declared two variables one is rng & another one is FinalResult.

Rng holds Range as the variable and FinalResult holds Variant as the variable.

Line 2: Set rng = Sheets(“Example 1”).Range(“E2”)

Previous declared variable rng is an object variable so we need to set to which range actually we are referring to. I have set the range to E2 cell. This is actually where I need the result to be displayed.

Line 3: FinalResult = Application. WorksheetFunction.VLookup (Range(“D2”), Range (“A2:B7”), 2, False)

This is the important line of the code. FinalResult holds the variable of the variant i.e. any kind of data type. FinalResugetsget the data from the function VLOOKUP.

Line 4: rng = FinalResult

Initial variable rng is equal to the value of FinalResult. Rng means E2 cell, FinalResult means value returned by the VLOOKUP function.

Step 6: Hit the RUN button or Press F5 to execute the code

VBA VLOOKUP Example 1-7

Step 7: We will get the below output.

VBA VLOOKUP Example 1-8

Example #2

Take the same data from the above example. Here I am going to create names and apply the same in the VLOOKUP. The code will the same as the previous example. Only in VLOOKUP, I am changing references.

Sub Vlookup_Example1()
Dim rng As Range, FinalResult As Variant, Table_Range As Range, LookupValue As Range
Set rng = Sheets("Example 1").Range("E2")
Set Table_Range = Sheets("Example 1").Range("A2:B7")
Set LookupValue = Sheets("Example 1").Range("D2")
FinalResult = Application. WorksheetFunction. VLookup(LookupValue, Table_Range, 2, False)
rng = FinalResult
End Sub

VBA VLOOKUP Example 2-1

Lookup value is set to D2 cell in the name of LookupValue. Table Array is set to A2 to B7 in the name of Table_Range.

Create a Macro Button

Once the macro code is written we need to design the macro.

Step 1: Go to Insert and Select the rectangular shape.

VBA VLOOKUP Example 2-2

Step 2: Draw a rectangular shape

VBA VLOOKUP Example 2-3

Step 3: Once the Rectangular shape has drawn right click on the rectangular shape and click on Assign Macro.

VBA VLOOKUP Example 2-4

Step 4: Once you click on Assign Macro it will open up all the macro names. Select the macro name you wish to assign. I am assigning Example 1 macro name to the rectangular shape.

VBA VLOOKUP Example 2-5

Step 5: Now rectangular shape has become a macro button. Once you click on the rectangular shape, you will get the below output.

VBA VLOOKUP Example 2-6

You can change the lookup value cell D2 and get the result. In the below image, I have changed the D2 cell value to Mobile.

VBA VLOOKUP Example 2-7

Things to Remember About VBA VLOOKUP

  • In VBA too VLOOKUP works the same as the worksheet function.
  • Declaring variables and assigning data type is the important thing here.
  • In the resulting cell, we do not see any kind of formula. Any value returned by VBA function does not hold any kind of formula.

Recommended Articles

This is a guide to Excel VBA VLOOKUP function. Here we discuss the VLOOKUP Formula and how to use VBA VLOOKUP in Excel along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA RGB
  2. VBA Create Object
  3. VBA Solver
  4. VBA Login

VLOOKUP is one of the most useful and versatile functions in Excel. As you work further with macros it’s not uncommon to make your create an Excel VBA VLOOKUP macro. With this you get the ability to reference your tables of data, but automated.

Wait, what’s a VLOOKUP function?

The Vertical Lookup is one of Excel’s most popular commands. It’s most common use allows you retrieve data from another table of data based on a key value. For example, in one Excel sheet you may have a list of one customer’s invoice numbers, and in another sheet a list of all your invoice numbers plus other columns, such as amount, customer and invoice date. A VLOOKUP function can use the invoice number as a reference point to extract one or more other related columns of data. This avoids sloppy copy-and-paste and ensures the data remains up to date.

excel vlookup function

An example of a simple VLOOKUP retrieving a ticket price for a given country.

There are other smart uses of the VLOOKUP, such as being able to search for duplicates, group values into buckets and check to see if items exists but this is enough detail for now.

For a more thorough discussion of the VLOOKUP function, check out our article here. Even better, come on one of our Excel Advanced courses!

So what about using Excel VBA VLOOKUPs?

You can retrieve data from sheet to sheet programmatically using VBA alone, usually with nested FOR NEXT loops and variables to track your current cell position. These can be a bit fiddly and the learning curve can be a little steep (if you want to learn how to do this check out our Excel VBA Introduction / Intermediate course).

an example of excel vba vlookup style functionality

The CopyRecords macro is simulating VLOOKUP-style functionality.

Luckily, VBA provides you with the Application.WorksheetFunction method which allows you to implement any Excel function from within your macro code.

So if your original VLOOKUP in cell B2 was something like this:

=VLOOKUP(Input!A2, Data!A1:X200, 5, FALSE)

The VBA version would look like this:

Range("B2") = Application.WorksheetFunction.VLookup(Sheets("Input").Range("A2"), Sheets("Data").Range("A1:X200"), 5, False)

Notice a couple of things:  I had to insert the Sheets and Range objects so VBA could properly interpret it.

I want a sneakier version!

Don’t want to do that Sheets and Ranges business? You can adopt a little-known punctuation trick in VBA that converts things into cell references: the square brackets. Did you know you can turn this:

Range("A1") = "Fred"

into

[A1] = "Fred"

With a little lateral thinking we can do the same to our VLOOKUP:

[B2] = [VLOOKUP(Input!A2, Data!A1:X200, 5, FALSE)]

Make it more robust

The code lines above will do the bare minimum. They’ll get the job done. What if you grab the result of the VLOOKUP and store it in a variable?

result = [VLOOKUP(Input!A2, Data!A1:X200, 5, FALSE)]

And then throw an unexpected value at it?

vba error 1004

Of course! Error 1004! Why didn’t I see that coming?

Let’s add a little error-handling so your code doesn’t come to a screeching halt. There’s a number of ways you can test this, and various things you can do with the error, so here’s only one suggestion:

On Error GoTo MyErrorHandler:

  result = [VLOOKUP(Input!A2, Data!A1:X200, 5, FALSE)]

MyErrorHandler:
  If Err.Number = 1004 Then
    MsgBox "Value not found"
  End If

Or possibly

On Error GoTo MyErrorHandler:

  result = [VLOOKUP(Input!A2, Data!A1:X200, 5, FALSE)]

MyErrorHandler:
  If Err.Number = 1004 Then
    result = ""
  End If

The first example throws the error right up in your face. The second one is a ‘silent’ error that pushes a null string into the result variable. Not usually advisable as you can’t actually spot the problem but on some occasions you just want to move past the code issue. You could replace the empty string with your own custom error message.

Make it dynamic

This is all well and good but what if your data grows and shrinks? You should be on the lookout for dynamic methods. You can consider things such as dynamic range names and similar, but here’s a VBA option you can consider:

    Dim ws As Worksheet
    Dim LastRow As Long
    Dim TargetRange As Range

    On Error GoTo MyErrorHandler:

    Set ws = Sheets("Data")

    LastRow = ws.Cells(Rows.Count, "X").End(xlUp).Row
    Set TargetRange = ws.Range("A1:X" & LastRow)

    result = Application.WorksheetFunction.VLookup(Sheets("Input").Range("A2"), TargetRange, 5, False)

    MsgBox result

MyErrorHandler:
    If Err.Number = 1004 Then
      MsgBox "Value not found"
    End If

Note I went back to standard sheet and range references; they’re tricky to mix and match with square bracket notation.

What’s happening here? We set up three variables, to house the sheet name, last row and final range. Then we calculate what the last used row is with the “xlUp” method. This is equivalent to pressing CTRL + up on the keyboard when working in Excel. This finds the last row on the worksheet, and finally we set this as the range used.

There’s lots of variations on this, depending on whether you need dynamic columns too and how regular your data is, but this is a great method for getting you started.

So there it is, from soup to nuts, ways to implement VLOOKUP functions in Excel VBA.

Looking for help on your VBA projects? We offer the UK’s largest schedule of VBA training events, with all versions and levels trained. The Introduction and Intermediate levels will give you all the tools you need to get started, while the Advanced course will allow you to hook up other Office applications and communicate with databases. We can also visit your offices to deliver training, or consult on your projects. We can also offer Access VBA and Word VBA too.

Read about our Excel VBA training solutions

5 Things You Didn’t Know Excel VBA Could Do

Like this post? Please share to your friends:
  • Vba excel эта закладка
  • Vba excel элементы управления формы
  • Vba excel элемент не найден
  • Vba excel элемент множество
  • Vba excel экспорт в csv