## VLOOKUP is a Microsoft Excel function that will look up a value in a row based on the value searched on in the first column of that row. This function can be used directly in Excel or in a macro or Visual Basic program using VBA (Visual Basic for Applications).

For instance in the following table, using the VLOOKUP function, one could do a search on Jones and retrieve the value 52. It doesn't matter how many columns are in the table or which column the desired value is in, but the search criteria must be in the first column searched using the function. The V stands for vertical as opposed to an HLOOKUP where the search criteria are in a row.

A B

1 Adams 75

2 Jones 52

3 Smith 50

The syntax of the VLOOKUP function is as follows:

VLOOKUP(SearchValue, Array, ColumnNumber, [Range_Lookup])

‘SearchValue’ is the value you are looking for in the first column of the spreadsheet or range. I the example above, the ‘SearchValue’ would be ‘Jones.’

‘Array’ refers to the range of cells that contains the data to be searched. In the above example, the ‘Array’ would be ‘A1:B3’.)

‘ColumnNumber’ refers to the column that contains the data that will be returned by the search. In the example, the ‘ColumnNumber’ would be 2.

‘Range_Lookup is an optional true/false argument that determines whether the search needs to return an exact or approximate value. If this is set to ‘False,’ VLOOKUP will only return an exact match. In this case the values in the first column need to be sorted. If it is set to ‘True’ or omitted, the column must be sorted and the function will return the largest value less than ‘SearchValue.’ In the example, if the ‘SearchValue’ were ‘Johnson’ instead of ‘Jones,’’ the function find a match with ‘Adams’ and return 75.

The complete function for the above example would be =VLOOKUP("Jones", A1:B3, 2)

Including the function in VBA code

To use the VLOOKUP function in VBA it should be wrapped in a sub-routine with declared variables following normal programming practices. Ideally, one would pass all values to the routine as variables so that the routine and the VLOOKUP function itself would be generic and could be re-used.

First, declare the variables to be used in the VLOOKUP function

dim vSearchValue as Variant

dim rArray as Range

dim iColumnNumber as Integer

dim bRangeLookup as Boolean

Next declare the variable used to hold the return on the VLOOKUP function. The contents of this variable will also be used to return from the routine.

dim vReturn as Variant

Putting it all together

Put all the components in a routine and test it against a spreadsheet.

Sub GetValue

dim vSearchValue as Variant

dim rArray as Range

dim iColumnNumber as Integer

dim bRangeLookup as Boolean

dim vReturn as Variant

vReturn = Application.WorksheetFunction.VLookup(vSearchValue, rArray, iColumnNumber, bRangeLookup)

End Sub