In Excel VBA, use Application.VLookup(lookup_value, table_array, column_index, False) to find an exact match in the first column of a range and return a value from another column. Assign the result to a Variant and check IsError before using it, so a missing match does not stop the macro.
What VLOOKUP Does in VBA
VLOOKUP searches vertically: it compares a lookup value with the leftmost column of a table range, then returns a value from the same row. The name comes from “vertical lookup.” In VBA, VLOOKUP is an Excel worksheet function that your macro can call; it is not a separate search algorithm built into the VBA language.
The function’s arguments have the same purpose in VBA as in a worksheet formula:
- Lookup value: the item to find, such as a product code or employee ID.
- Table array: the range to search. Its first column must contain the lookup values.
- Column index: the number of the return column counted from the left edge of the selected range. The first column is 1.
- Range lookup: use
Falsefor an exact match orTruefor an approximate match. In most VBA lookups, exact matching is the safer choice.
For example, if the table range is A2:C100, column index 3 returns a value from column C. It does not mean worksheet column C in every case: if the range starts in column D, index 3 means column F. This relative numbering is a frequent source of incorrect results.
Choose the VBA Lookup Method
The common call is Application.VLookup. It returns a Variant, which can hold the result or an Excel error value such as #N/A. That makes it convenient to test a missing match with IsError and decide what the macro should do.
You can also call Application.WorksheetFunction.VLookup. This version behaves more like calling a worksheet function directly: if no match exists, VBA raises a runtime error instead of returning an error value for you to inspect. Use it when you deliberately want to handle that runtime error with an error handler. For ordinary lookup code, Application.VLookup plus an IsError check is usually more straightforward.
Neither method changes the underlying lookup rules. VLOOKUP searches only the first column of the specified range, returns only a column to its right, and returns the first matching row when a key appears more than once. It also does not distinguish uppercase from lowercase letters when matching text.
Exact Match and Approximate Match
Use False as the fourth argument when you need the key to match exactly. This is appropriate for identifiers, names, product codes, and most lookups against a reference table. If the key is absent, VLOOKUP reports an error rather than silently selecting a nearby value.
True, or an omitted fourth argument, requests an approximate match. For that mode, the first column must be sorted in ascending order. VLOOKUP returns an exact match if it finds one; otherwise it returns the value associated with the largest key less than the lookup value. This can be useful for threshold tables, such as rate bands, but unsorted data can produce misleading results. Always specify the fourth argument rather than relying on the default.
Exact match does not mean every visually similar value is equal. A number stored as text may not match the same digits stored as a number, and extra spaces can prevent a text match. VLOOKUP is also case-insensitive, so keys that differ only by capitalization are not a reliable way to identify separate records.
Set Up a Simple Lookup
Before writing the macro, identify the key column, the value to retrieve, and the destination cell. Use a range that contains the relevant records but not a title row unless the title row is intentionally part of the lookup area. Check that the key is in the range’s first column and that the return column is to its right.
- In the Visual Basic Editor, choose Insert > Module to add a standard module.
- Refer to the intended worksheet explicitly instead of relying on whichever sheet happens to be active.
- Set the table range and lookup value, then call
Application.VLookupwithFalsefor an exact match. - Check the result with
IsErrorbefore writing it to a cell or using it in further calculations. - Save the workbook as a macro-enabled
.xlsmfile if it contains the VBA code.
On Windows, open the Visual Basic Editor with Alt+F11; on a Mac, use Option+F11 (some keyboards require Fn as well), or use the Visual Basic command on the Developer tab. Excel for the web can open a macro-enabled workbook, but it cannot create or run VBA macros.
Worked Example: Return a Product Department
Assume a worksheet named Products has product IDs in A2:A100, product names in column B, and departments in column C. Cell E2 contains the ID to look up, and F2 is where the macro should write the department. With that layout, a worksheet formula would be =VLOOKUP(E2,A2:C100,3,FALSE). If E2 contains ID 1042 and the matching row has “Hardware” in column C, the formula returns Hardware.
The VBA version below uses the same range and exact-match setting. It writes a clear message in F2 if the ID is missing.
Sub FindProductDepartment()
Dim ws As Worksheet
Dim tableRange As Range
Dim lookupValue As Variant
Dim result As Variant
' Use the worksheet that contains the product table.
Set ws = ThisWorkbook.Worksheets("Products")
Set tableRange = ws.Range("A2:C100")
lookupValue = ws.Range("E2").Value2
' Search the first column and return the third column.
result = Application.VLookup(lookupValue, tableRange, 3, False)
If IsError(result) Then
ws.Range("F2").Value = "ID not found"
Else
ws.Range("F2").Value = result
End If
End Sub
ThisWorkbook means the workbook containing the VBA code. If the macro is stored in another workbook, such as a personal macro workbook, that reference may not point to the file holding the Products sheet. In that situation, explicitly reference the correct workbook rather than assuming it is active.
Handle Missing Values and Other Errors
A missing exact match normally gives Application.VLookup an Excel error value, commonly #N/A. Testing with IsError(result) lets you choose an appropriate response: write a message, leave the output blank, log the missing key, or ask the user to check the source data. Treating “not found” as a normal outcome is better than allowing it to become an unexpected macro failure.
Other mistakes can cause different problems. A column index larger than the number of columns in the table range produces #REF!. A zero or negative column index is invalid. A misspelled worksheet name or a range reference to the wrong sheet can stop the macro before VLOOKUP runs. If you use WorksheetFunction.VLookup, remember that an absent key raises a VBA runtime error; an error handler is needed if you choose that approach.
When a lookup unexpectedly fails, inspect the actual cell values and types, not just their display. Check for leading or trailing spaces, numbers stored as text, inconsistent punctuation, and hidden characters copied from another system. A clean-looking ID can still differ from the table key. You can also confirm that the lookup value and table range refer to the intended worksheet and rows.
Common Limitations and Alternatives
VLOOKUP is useful when the key is on the left and the answer is to its right, but its layout requirement can be inconvenient. It cannot return a value from a column to the left of the key. It also uses a numeric column index, so inserting or rearranging columns can make a hard-coded index return the wrong field without necessarily causing an obvious error.
For newer Excel versions, XLOOKUP can search in one range and return a result from another, including a column to the left. It also provides an argument for a value to return when nothing is found. XLOOKUP is available in Microsoft 365 and Excel 2021 or later, but not in some older perpetual versions. If a workbook must support older Excel installations, check compatibility before using it.
INDEX and MATCH can also separate the search column from the return column and work in older Excel versions. In VBA, you can call these worksheet functions as well, but their added flexibility may not be necessary for a small, simple table. For large repeated searches, a VBA dictionary or a strategy that reads ranges into arrays may be faster than making many individual worksheet-function calls; those approaches require more code and careful handling of duplicate keys.
VLOOKUP remains a reasonable choice when the workbook already uses it, the key is in the first column, and the table structure is stable. Choose an alternative when the lookup needs to go left, column changes are likely, or the workbook’s Excel-version requirements favor another function.
Performance, Workbook Safety, and Compatibility
For one or a few lookups in a modest table, VLOOKUP is generally simple to maintain. If a macro performs thousands of lookups, repeatedly searching a large worksheet range can take longer. Consider limiting the range to actual data rather than entire columns, and avoid repeating the same lookup unnecessarily. For substantial workloads, benchmark a more suitable design with the actual workbook and data size.
Save a separate copy of the workbook before running a macro that writes results or changes data. VBA actions generally cannot be reversed with Ctrl+Z (or Command+Z on Mac), so a backup is the practical way to recover from unintended changes. Run macros only from sources you trust, and do not enable all macros globally just to run one file. Macro security settings and prompts can vary by organization.
VBA is supported in the desktop versions of Excel for Windows and Mac, though the interface and some capabilities differ. Excel for the web does not run VBA. If colleagues need to use the workbook in a browser, consider whether the task can be done with worksheet formulas or Office Scripts instead; Office Scripts are a separate automation feature, not VBA.
Frequently Asked Questions
How do I use VLOOKUP in Excel VBA?
Call Application.VLookup with the lookup value, a range whose first column holds the key, the return-column number, and False for an exact match. Store the returned value in a Variant and check it with IsError.
Why does VBA VLOOKUP return #N/A?
With exact matching, #N/A means the key was not found as an exact value in the range’s first column. Check for text-versus-number differences, extra spaces, an incorrect range, or a key that is genuinely absent.
What does the column number mean in VBA VLOOKUP?
It counts from the left edge of the table range, not from worksheet column A. In a range A2:C100, 3 means the third range column, C. In a range D2:F100, 3 means F.
Is Application.VLookup better than WorksheetFunction.VLookup?
For many macros, Application.VLookup is easier to handle because a missing match can be tested as an error value. WorksheetFunction.VLookup raises a runtime error for a missing match, so use an error handler if you choose it.
Can VBA VLOOKUP return a value from a column to the left?
No. The return column must be to the right of the lookup column within the selected range. Use XLOOKUP in supported Excel versions, or consider INDEX and MATCH when older-version compatibility matters.
Related
- Split Cell Contents Into Multiple Columns in Excel
- Excel Conditional Formatting: Find Partial Text Matches
- Split a Cell in Excel: Separate Text or Unmerge Cells
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA: Find the Latest Date in a Column AutomaticallyTo find the latest date in an Excel column with VBA, scan the cells that contain dates, keep…
- Excel VBA: Copy and Paste Selected Cells with a MacroTo copy selected cells with VBA, call the range’s Copy method and specify a destination cell, as in…
- VBA Delete Blank Rows in Excel: Safe MethodsYes. In Excel for Microsoft 365 on Windows, a VBA macro can scan a chosen range from bottom…
- Excel VBA UserForm: How It Works and When to Use OneAn Excel VBA UserForm is a custom window for collecting information or giving users a guided way to…
- Excel VBA Find a Blank Cell: Methods and ExamplesTo find the first truly empty cell in a range with Excel VBA, loop through the cells and…
- How to Delete Blank Rows in Excel with a VBA MacroTo delete blank rows in Excel with a macro, select the data range, run a VBA procedure that…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.