Excel формулы впр - Учим Эксель

Excel Macro Mastery

VBA VLookup – A Complete Guide

VBA Lookup

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.

A Simple VBA VLookup example

Note: The variable shData in the examples refers to the worksheet by the code name. You can replace this with the code name of the worksheet you are using.

Take a look at the following data:

Use this code to generate this data on any worksheet:

The code below will return the price for the Orange 1.45

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

Let’s look at some more examples and results

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

Интересно почитать:  Ошибка в формуле в excel

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

In this case, the lookup value must be a Long or you will get an error message.

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

You can then use it as normal in the VLookup function when the search column contains dates

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.

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

The following code shows some examples of how this parameter works:

Dealing with Errors

VBA VLookup Errors

© BigStockPhoto.com

We can use VLookup in two ways in VBA. With Application or with WorksheetFunction

The difference between them is how we handle errors. Let’s look at each of these in turn.

Интересно почитать:  Формула индекс поискпоз в excel

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.

Using Application

Using Application.VLookup we can simply check the return value to see if there was an error

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.

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

Get the Free eBook

How To Ace the 21 Most Common Questions in VBA

Please feel free to subscribe to my newsletter and get exclusive VBA content that you cannot find here on the blog, as well as free access to my eBook, How to Ace the 21 Most Common Questions in VBA which is full of examples you can use in your own code.

60 comments

hi sir paul can i or is there vlookup to the left range

thank you for your attention and answers
rian

Dear Paul Kelly.

My name is Frank, I live in Italy.
I would like to send you this question to have your answer from you, if possible.

Using the “Vlookup” function and a VBA code in a module, in the current spreadsheet I am trying to return in a range of cells the corresponding value imported from a second spreadsheet, including any related comment with its original formatting.

The Vlookup formula is as follows: =VlookupComment (H2; A2:C10;3;FALSE)

And the VBA code in the module is the follows:

Function VlookupComment(LookVal As Variant, FTable As Range, FColumn As Long, FType As Long) As Variant
‘Frank [12.03.20]
Application.Volatile
Dim xRet As Variant ‘potrebbe risultare un errore
Dim xCell As Range
xRet = Application.Match(LookVal, FTable.Columns(1), FType)
If IsError(xRet) Then
VlookupComment = “value not available”
Else
Set xCell = FTable.Columns(FColumn).Cells(1)(xRet)
VlookupComment = xCell.Value
With Application.Caller
If Not .Comment Is Nothing Then
.Comment.Delete
End If
If Not xCell.Comment Is Nothing Then
.AddComment xCell.Comment.Text
End If
End With
End If
End Function

Everything is working, however the comment text is not imported with the same original formatting but in a small box and with different characters.
Can You help me to solve this problem?

Thank you very much …
I await your kind reply.

Sheet1.Cells(input_row, name_clm) = Application.VLookup(Sheet1.Cells(input_row, name_clm), Sheet2.Range(“C2: C7”), 1, 1)

this code run good

I want to use “cells” format instead of “C2:C7”
.Range(Cells(1, name_clm), Cells(last_row, name_clm))

but it doesn’t work! why?

Put full stop before Cells. e.g. .Range(.Cells

‘ActiveCell.FormulaR1C1 = “=VLOOKUP(RC[-1],Data!C[1]:C[2],2,0)”
‘ActiveCell.FormulaR1C1 = “=VLOOKUP(RC[-2],Data!C:C[2],3,0)”

For this formula instead of activecell… i want it to be C2 for the first line and D2 for the second line…how do i amend this code

Ссылка на основную публикацию
Adblock
detector