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


 

stolniy

Пользователь

Сообщений: 20
Регистрация: 08.02.2020

Добрый день!

Есть данные из 1С и данные с сайта, которые постоянно меняются по объему. Т.е. колонки стандарт, а количество вариативно.
Что делает макрос, преобразовывает данные из 1С в удобоваримые для сайта, сравнивает штрихкода на сайте и в 1С, и формирует данные для поставки.
Что сделано: Через запись макроса, сформировано тело макроса. С помощью всемогущего Интернет код ужат по возможности, через форумы добавлены отдельные элементы.

Вопрос: В макросе использую формулы ВПР, но есть затык, который меня беспокоит.

1. Формулу сформировал макросом и у нее есть обращение к таблице определенного размера. Как то можно эту переменную в формуле подстраивать под размеры таблицы? Плюс есть нюанс, когда макрос заканчивается то появляются расхождения между ШК. Но по факту оба ШК из разных источников «на вид» идентичны, т.е. цифра в цифру, и это самый большой минус

Код
    'проверяем на совпадение баркодов c WB
    Sheets("Номенклатура WB").Range("I:I").Cut
    Sheets("Номенклатура WB").Range("A:A").Insert Shift:=xlShiftToRight
    Sheets("Номенклатура WB").Range("A:A") = Sheets("Номенклатура WB").Range("A:A").Value
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row
    Sheets("Сводные данные").Range("I2").FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],'Номенклатура WB'!R[-1]C[-8]:R[414]C[2],1,FALSE),0)"
    Sheets("Сводные данные").Range("I2").AutoFill Destination:=Sheets("Сводные данные").Range("I2:I" & LastRow)
    Sheets("Сводные данные").Range("J2").FormulaR1C1 = "=IF(RC[-2]=RC[-1],""Нет"",""Есть"")"
    Sheets("Сводные данные").Range("J2").AutoFill Destination:=Sheets("Сводные данные").Range("J2:J" & LastRow)
    Sheets("Сводные данные").Range("I:J") = Sheets("Сводные данные").Range("I:J").Value
    'Worksheets("Номенклатура WB").Cells.ClearContents
  

2. Перфекто не дремлет, и хотелось бы реализовать эту функцию в VBA. Готовые конструкции находил, но не смог разобраться с механикой функции и перекроить ее под себя. Взято с другого тематического форума.

Код
Sub ee150604_0806()
Dim i, n, s1
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Excel.Worksheets("лист1")  ''справочник
Set ws2 = Excel.Worksheets("лист2")  ''основной

For i = 1 To 5
s1 = ws2.Cells(i, 1)

For n = 1 To 5
If ws1.Cells(n, 1) = s1 Then

ws2.Cells(i, 2) = ws1.Cells(n, 2)

Exit For
End If
Next n
Next i

End Sub

3. Не могу разобраться почему в коде ниже если убрать первую строку результат не появляется. Код взят тоже из Интернет и адаптирован под мои задачи

Код
    Sheets("Упаковочные листы").Select 'почему без этой строки цикл ниже не выдает результата?
    Dim vItem, avArr, li As Long
    ReDim avArr(1 To ActiveWorkbook.Worksheets("Упаковочные листы").Rows.Count, 1 To 1)
    With New Collection
        On Error Resume Next
        For Each vItem In ActiveWorkbook.Worksheets("Упаковочные листы").Range("C2", Cells(ActiveWorkbook.Worksheets("Упаковочные листы").Rows.Count, 3).End(xlUp)).Value
            'Cells(Rows.Count, 1).End(xlUp) – определяет последнюю заполненную ячейку в столбце А
            .Add vItem, CStr(vItem)
            If Err = 0 Then
                li = li + 1: avArr(li, 1) = vItem
            Else: Err.Clear
            End If
        Next
    End With
    If li Then Sheets("ШК_коробов").Range("A2").Resize(li).Value = avArr
    ActiveWorkbook.Worksheets("ШК_коробов").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("ШК_коробов").Sort.SortFields.Add2 Key:=Range("A:A"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("ШК_коробов").Sort
        .SetRange Range("A:A")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Любая критика приветствуется! Я уверен что код можно еще больше сжать и использовать более удобные и «правильные» конструкции.
И если Вам не сложно пишите комментарии к Вашему коду, чтоб была возможность потом самостоятельно повторить написанное.

Спасибо!

I’m trying to lookup a value on a spreadsheet within a table array using the VLOOKUP function in my vba code. I don’t know how to write it correctly.

Here is the normal VLOOKUP formula with all the references:

=VLOOKUP(DATA!AN2,DATA!AA9:AF20,5,FALSE)

aphoria's user avatar

aphoria

19.7k7 gold badges63 silver badges73 bronze badges

asked Apr 6, 2011 at 13:54

Mike's user avatar

Have you tried:

Dim result As String 
Dim sheet As Worksheet 
Set sheet = ActiveWorkbook.Sheets("Data") 
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)

answered Apr 6, 2011 at 14:01

Ben Hoffstein's user avatar

Ben HoffsteinBen Hoffstein

102k8 gold badges104 silver badges120 bronze badges

1

How about just using:

result = [VLOOKUP(DATA!AN2, DATA!AA9:AF20, 5, FALSE)]

Note the [ and ].

answered Apr 6, 2011 at 16:40

Oneide's user avatar

OneideOneide

1,0208 silver badges12 bronze badges

3

Please find the code below for Vlookup:

Function vlookupVBA(lookupValue, rangeString, colOffset)
vlookupVBA = "#N/A"
On Error Resume Next
Dim table_lookup As range
Set table_lookup = range(rangeString)
vlookupVBA = Application.WorksheetFunction.vlookup(lookupValue, table_lookup, colOffset, False)
End Function

Unni Kris's user avatar

Unni Kris

3,0614 gold badges33 silver badges57 bronze badges

answered Feb 20, 2013 at 3:32

Alejandro Sardi's user avatar

1

As Tim Williams suggested, using Application.VLookup will not throw an error if the lookup value is not found (unlike Application.WorksheetFunction.VLookup).

If you want the lookup to return a default value when it fails to find a match, and to avoid hard-coding the column number — an equivalent of IFERROR(VLOOKUP(what, where, COLUMNS(where), FALSE), default) in formulas, you could use the following function:

Private Function VLookupVBA(what As Variant, lookupRng As Range, defaultValue As Variant) As Variant
    Dim rv As Variant: rv = Application.VLookup(what, lookupRng, lookupRng.Columns.Count, False)
    If IsError(rv) Then
        VLookupVBA = defaultValue
    Else
        VLookupVBA = rv
    End If
End Function

Public Sub UsageExample()
    MsgBox VLookupVBA("ValueToFind", ThisWorkbook.Sheets("ReferenceSheet").Range("A:D"), "Not found!")
End Sub

answered May 15, 2018 at 21:10

Nickolay's user avatar

NickolayNickolay

30.6k12 gold badges106 silver badges181 bronze badges

Dim found As Integer
    found = 0

    Dim vTest As Variant

    vTest = Application.VLookup(TextBox1.Value, _
    Worksheets("Sheet3").Range("A2:A55"), 1, False)

If IsError(vTest) Then
    found = 0
    MsgBox ("Type Mismatch")
    TextBox1.SetFocus
    Cancel = True
    Exit Sub
Else

    TextBox2.Value = Application.VLookup(TextBox1.Value, _
    Worksheets("Sheet3").Range("A2:B55"), 2, False)
    found = 1
    End If

Mallikarjuna Reddy's user avatar

answered Dec 8, 2016 at 9:56

Avin's user avatar

        Public Function VLOOKUP1(ByVal lookup_value As String, ByVal table_array As Range, ByVal col_index_num As Integer) As String
        Dim i As Long

        For i = 1 To table_array.Rows.Count
            If lookup_value = table_array.Cells(table_array.Row + i - 1, 1) Then
                VLOOKUP1 = table_array.Cells(table_array.Row + i - 1, col_index_num)
                Exit For
            End If
        Next i

        End Function

answered Oct 31, 2016 at 12:10

Vahid Dastitash's user avatar

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

In my earlier post, I had written about VLOOKUP in Excel. It was a massive post of around 2500 words, it explains most of the things about the vertical lookup function in excel. Today’s post is an extension to that post and here we will understand how to apply a VLOOKUP in VBA.

If you haven’t read that post then I would strongly recommend you read that post before going any further. [Read Here]

Assuming that you have basic knowledge of the VLOOKUP function we will move further.

Note: To perform these programs yourself, you may need to enable macros in excel. Read this post to know how to do this.

Syntax of VBA VLOOKUP

You can use VLookUp in macros by following any of the below ways:

Application.VLOOKUP(lookup_value, table_array, column_index, range_lookup)

Or

Application.WorksheetFunction.VLOOKUP(lookup_value, table_array, column_index, range_lookup)

Note: If you are searching for something similar to the VLOOKUP function for Access then probably you should use DLOOKUP.

5 Examples of Using VLOOKUP in VBA

Now let’s move to some practical examples of using VLookUp in VBA codes.

Example 1

Using VLookUp find the monthly salary of “Justin Jones” from the below table. Display the salary using a dialog box.

VLOOKUP in VBA Example 1

Below is the code for this:

Sub FINDSAL() 
Dim E_name As String
E_name = "Justin Jones"
Sal = Application.WorksheetFunction.VLookup(E_name, Sheet1.Range("B3:D13"), 3, False)
MsgBox "Salary is : $ " & Sal
End Sub

Example 1 Message Box

Explanation: In this code, we have used a variable ‘E_name’ to store the employee name whose salary is to be fetched. After this, we have simply supplied the employee name and other required arguments to the VLOOKUP and it returns the salary of the corresponding Employee.

Example 2

Now make the above program a little customizable by accepting the Employee name from the user. If the user enters any Employee name that is not present in the table then the program should be able to convey this clearly to the user.

To accomplish this we can use the below code:

Sub FINDSAL() 
On Error GoTo MyErrorHandler:
Dim E_name As String
E_name = InputBox("Enter the Employee Name :")
If Len(E_name) > 0 Then
Sal = Application.WorksheetFunction.VLookup(E_name, Sheet1.Range("B3:D13"), 3, False)
MsgBox "Salary is : $ " & Sal
Else
MsgBox ("You entered an invalid value")
End If
Exit Sub
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Employee Not Present in the table."
End If
End Sub

Explanation: In this code, we are accepting the user input using an InputBox function. If the Employee name entered by the user is found, then VLookUp returns its corresponding salary. However, if the employee name is not present in the table then VLOOKUP throws a “1004 Error”.

And, we have created an error handler to catch such cases for conveying the user that entered employee name doesn’t exist.

Example 3

In this example we will try to write a code that adds the Department field from the Employee Table 1 to our old Employee Table.

VLookup Employee Tables Example 3

As you can see that in both these tables there is only one common column i.e. Employee_ID. So, in this case, we will have to apply the VLookUp based on the Employee ID.

Below is the code to do this:

Sub ADDCLM()
On Error Resume Next
Dim Dept_Row As Long
Dim Dept_Clm As Long
Table1 = Sheet1.Range("A3:A13") ' Employee_ID Column from Employee table
Table2 = Sheet1.Range("H3:I13") ' Range of Employee Table 1
Dept_Row = Sheet1.Range("E3").Row ' Change E3 with the cell from where you need to start populating the Department
Dept_Clm = Sheet1.Range("E3").Column
For Each cl In Table1
Sheet1.Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 2, False)
Dept_Row = Dept_Row + 1
Next cl
MsgBox "Done"
End Sub

VBA VLOOKUP Example 4

Explanation: This code takes each ‘lookup_value’ from the Employee ID field (one at a time), looks up its corresponding Department, and then populates the corresponding department value at the appropriate place.

Please note that in this code we have just pasted the result of the VLOOKUP formula, and not the VLookUp formula itself (Refer Example 5).

Example 4

In this example we will try to write a code that displays all the details of an employee from the Employee table (as shown below) when its Employee ID is entered.

VLookup For Example 4

Below is the code that can accomplish this:

Sub FETCH_EMP_DETAILS()
On Error GoTo MyErrorHandler:
Dim E_id As Long
E_id = InputBox("Enter the Employee ID :")
Det = "Employee ID : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 1, False)
Det = Det & vbNewLine & "Employee Name : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 2, False)
Det = Det & vbNewLine & "Employee SSN : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 3, False)
Det = Det & vbNewLine & "Monthly Salary : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 4, False)
Det = Det & vbNewLine & "Department : " & Application.WorksheetFunction.VLookup(E_id, Sheet1.Range("A3:E13"), 5, False)
MsgBox "Employee Details : " & vbNewLine & Det
Exit Sub
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Employee Not Present in the table."
ElseIf Err.Number = 13 Then
MsgBox "You have entered an invalid value."
End If
End Sub

Message Box Output Example 4

Explanation: In this example, we have asked the user to enter the Employee Id and then we have used multiple VLookUp Statements and concatenated their outputs to show all the details in a single message box.

Example 5

Redo example 3 but this time paste the whole VLookUp formula instead of pasting only the result.

VLookup Employee Tables Example 3

Below is the code for doing this:

Sub ADDCLM()
On Error Resume Next
Dim Dept_Row As Long
Dim Dept_Clm As Long
ctr = 0
Table1 = Sheet1.Range("A3:A13") ' Employee_ID Column from Employee table
Table2 = Sheet1.Range("H3:I13") ' Range of Employee Table 1
Dept_Row = Sheet1.Range("E3").Row ' Change E3 with the cell from where you need to start populating the Department
Dept_Clm = Sheet1.Range("E3").Column
For Each cl In Table1
Sheet1.Cells(Dept_Row, Dept_Clm).FormulaR1C1 = "=VLOOKUP(RC[-4], R3C8:R13C9, 2, False)"
Dept_Row = Dept_Row + 1
ctr = ctr + 1
Next cl
MsgBox "Done"
End Sub

VLOOKUP in VBA paste formula

Explanation: This code is very similar to the one that we have discussed in Example 3, the only difference between these formulas is that here we are copying the VLookUp formula directly in the cells.

In this code, we have applied the VLOOKUP in R1C1 form. So, the formula =VLOOKUP(RC[-4], R3C8:R13C9, 2, False) means =VLOOKUP(<4 cells to the left of current cell>, <Range of Employee Table 1>, <column to be fetched>, <exact match>).

One thing that is worth noting here is: the square brackets ( [ ] ) in your R1C1 formula indicate that you are specifying a relative range. If you want to specify an absolute range, you need to specify the R1C1 cells without brackets; e.g. R3C8:R13C9.

So, this was all about VBA VLOOKUP .

Понравилась статья? Поделить с друзьями:
  • Vba excel внешние данные
  • Vba excel вложенный with
  • Vba excel вставить формулу в диапазон
  • Vba excel вложенные циклы for
  • Vba excel вставить текущую дату