Export (0) Print
Expand All

Using the VLookup Function in Excel 2007

Office 2007

Summary:  Learn how to dynamically search table arrays in Microsoft Office Excel 2007 by using the built-in VLOOKUP function.

Office Visual How To

Applies to:  2007 Microsoft Office System, Microsoft Office Excel 2007, Microsoft Visual Basic for Applications (VBA)

Michael LaRosa, Murphy & Associates

April 2009

Overview

Often cells in a worksheet have dependencies on other cells in the same or in a separate, but related, worksheet. The most robust method of assigning values to these dependent rows is to dynamically locate and resolve these values. Office Excel 2007 contains a number of search functions to address this need. The VLOOKUP function enables you to search for a value in the first column of a table array, and if a match is found, then return a value from another column in this same row.

See It

Using the VLOOKUP Function video splash screen

Watch the Video

Length: 06:54 | Size: 24.6 MB | Type: WMV file

Code It | Read It | Explore It

In this example, you create three calculated columns using the VLOOKUP function in a variety of ways. It uses information about students at a hypothetical state university.

Open and Examine StudentInfo

Download the sample file

In this example you will work with the file StudentInfo.xlsx, which you can download from Code Gallery. Open this file in Office Excel 2007. It contains a workbook with three worksheets:

  • Students contains key information about registered students. This is the worksheet that you will be modifying.

  • GPA lists the students' quarterly and averaged yearly grade point average, on a scale from 0 to 4.0.

  • Grades contains a GPA-to-letter conversion table. (It also contains some UI at the bottom that can be used in a procedure for calculating a grade from a GPA value. This is discussed in the section Using VLOOKUP from VBA.)

This workbook represents a sample of an actual workbook that could potentially contain information about thousands or tens of thousands of students.

Adding a Buddy Email Column

The university pairs all incoming freshman with one another in a "buddy" system. Currently in the Students worksheet, the Class Buddy column lists the ID of the corresponding student. Although this information is available via a manual search in this same table, to enable easier access, another column with the buddy's email will be added. To accomplish this, you will use the VLOOKUP function to search in the same table using an exact match.

To create the buddy email column

  1. On the Students worksheet, enter "CB Email" into cell I1. Increase the width of this column to about 180 pixels.

  2. Enter the following formula into cell I2:

    =VLOOKUP(H2, A2:H23, 7, FALSE)
    

    Notice how the autocomplete and tooltip features in Office Excel 2007 assist in creating this formula. The parameters have the following meaning:

    • H2 is the cell containing the value (391885) to lookup.

    • A2:H23 is the table array to search through. Note the first, left-most column, here A (ID), represents the column to search for our lookup value.

    • 7 is the index of the column whose cell contains the returned value of the function, assuming a match is found for the lookup value.

    • FALSE specifies that an exact search should be performed.

    When you click Enter, I2 should display the calculated value of steventh@stateu.edu. Steven Thorpe is the assigned buddy of Anne Hellung.

  3. Edit the formula in I2 so that the table array uses absolute cell references:

    =VLOOKUP(H2, $A$2:$H$23, 7, FALSE)
    

    This should not change the calculated value in I2, but is required for the next step.

  4. Copy the formula in cell I2 to cells I3 through I23. The easiest way to accomplish this is to autofill this column by dragging the lower-right handle on I2 down to I23. The rest of the calculated buddy email addresses should now display. Click several of these cells to examine the underlying LOOKUP formula.

Adding a Column to Confirm Buddy Compatibility

Buddies are usually required to be in the same graduation class. To help monitor this proscription, a new column is requested to keep track of this relationship. Again you will use VLOOKUP to search in the same table using an exact match, but the results will then be used in a further calculation.

To create the paired class validation column

  1. On the Students worksheet, enter "CBSY?" into cell J1. This acronym represents "Class Buddies the Same Year?"

  2. Enter the following formula into cell J2:

    =EXACT(D2, VLOOKUP(H2, A:H, 4, FALSE))
    

    This formula compares the graduation class of the current student with that of his buddy and returns the Boolean result. Note that this time that the table is described by a range of columns, A:H. This is more appropriate for tables in which rows are dynamically added and deleted.

  3. Copy this formula to the rest of the cells in this column, cells J3 through J23.

    Note that two paired students, Mr. White and Mr. Xie, are in different graduation classes.

Adding a Grade Column

Lastly, a request has been received to extend this worksheet with the current student average grade. To accomplish this, you perform a nested lookup using tables on the other worksheets.

To create the grade column

  1. On the Students worksheet, enter "Grade" into cell K1.

  2. Select the column and format the cells as a Number type with 2 Decimal places of precision.

  3. Enter the following formula into cell K2:

    =VLOOKUP(A2,GPA!A:F,6,FALSE)
    

    This formula performs a lookup using the current student's ID on the table in the GPA worksheet. It returns the matching values in column 6, which is the average GPA for the year.

  4. Next convert this GPA into a grade by wrapping this function call inside of another call to VLOOKUP:

    =VLOOKUP(VLOOKUP(A2,GPA!A:F,6,FALSE), GradesCnv, 2, TRUE)
    

    A lookup is performed using the result of the previous lookup, searching on the table in the GPA worksheet, and returning the sixth column. Notice the following:

    • The named range GradesCnv is used instead of Grades!A2:B12. This is just a shorthand convenience.

    • The search type is approximate (FALSE) and therefore the first column (GPA) in the Grades worksheet must be ordered ascending.

  5. Copy this formula to the rest of the cells in this column, cells K3 through K23.

The Resulting Students Worksheet

After you have added these three new columns, the resulting Students worksheet should appear as in Figure 1 (except that in the figure, columns D-G have been hidden to conserve space).

Figure 1. Students worksheet after column additions.

Students worksheet after column additions

The built-in VLOOKUP function in Office Excel 2007 is used to dynamically search for matching values in a table arrays. Given a value, it performs a vertical search in the first column of the specified table, and if it finds a match, it returns a value from the specified column in the same row.

This function can be used to find information in a single worksheet or, more commonly, to use a known value in one worksheet to search for associated data in a row of another, related worksheet.

Office Excel 2007 contains a number of related search functions, including:

Function

Description

LOOKUP

Searches for an exact matching value and, if successful, returns an associated value. The LOOKUP function has two syntax forms: the vector form and the array form.

HLOOKUP

This horizontal lookup function is the counterpart to VLOOKUP. It searches for a value in the first row of a table array, and if a match is found, then it returns a value from the specified row in this same column.

MATCH

Returns the relative position of an item in an array that matches a specified value in a specified order. Use MATCH instead of one of the LOOKUP functions when you need the position of an item in a range instead of the item itself.

In addition, it is common to use other built-in functions—such as INDEX, OFFSET, FIND, SEARCH, and CHOOSE—to refine searches.

Syntax

VLOOKUP has the following syntax:

VLOOKUP(lookup_value,table_array,col_index_num,[range_lookup])

Where:

lookup_value is the value to search for in the first column of the table array. This parameter can hold a value or a reference.

Note:

  • A text match is not case sensitive, but does consider whitespace, non-printing and special characters. You can use the TRIM or CLEAN functions to remove these characters and EXACT to compare case.

  • Exact text searches can use the question mark (?) and asterisk (*) wildcard characters to match a single character or any sequence of characters, respectively.

  • Exact matches on floating point values may not succeed because of rounding approximations. Instead, perform an approximate match or use the TRUNC function.

Error Conditions

The following conditions will result in error values being returned:

  • If lookup_value is smaller than the smallest value in the first column of table_array, VLOOKUP returns #N/A.

  • If col_index_num is less than 1, then #VALUE! is returned; if greater than the number of columns in table_array, then #REF! is returned.

  • If a match is not found, #N/A is returned.

Using VLOOKUP from VBA

The VLOOKUP function is exposed in the Office Excel 2007 object model as the WorksheetFunction.VLookup method. For example, the following code could be added to the Grades worksheet to perform a basic GPA-to-grade conversion. This code utilizes the existing UI elements already found in this worksheet: the button named GradeCalc, and named cells GpaInput and GradeOutput.

Note: VBA code will only function in macro-enabled spreadsheets and templates. If you want to add and test this code, save the companion file StudentInfo.xlsx as a macro-enabled spreadsheet named StudentInfo.xlsm.

' Event handler to calculate a grade from a GPA 
Sub GradeCalc_Click()
    Dim oGradeCell As Range
    Set oGradeCell = Range("GradeOutput")
    oGradeCell.Value = ""
    Dim res As Variant
    Dim errNum As Integer
    'Traps and reports all application errors
    On Error Resume Next
    res = Application.WorksheetFunction.VLookup(Range("GpaInput"), _
           Range("A2", "B12"), 2, True)
    errNum = Err.Number
    If errNum <> 0 Then
        res = "Error: " & errNum
    End If
    oGradeCell.Value = res
End Sub

This code must be implemented as an event procedure for the GradeCalc button.

To create an event procedure for an existing form control

  1. Right-click on the control (here the GradeCalc button) and choose the Assign Macro command from the context menu. The Assign Macro dialog box should display.

  2. In the Macro Name text box, enter a name for the VBA event procedure (here GradeCalc_Click) and click New.

    The dialog box closes and the Visual Basic Editor opens, displaying the VBA source code for the newly created event procedure.

In addition to the standard runtime errors, such as out of memory, described in Core Visual Basic Language Errors, the VLOOKUP method also issues the application-defined error (error number 1004) for the error conditions described in the previous section.

Show:
© 2014 Microsoft