© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
A. MurrayAdvanced Excel Formulashttps://doi.org/10.1007/978-1-4842-7125-4_7

7. The Infamous VLOOKUP Function

Alan Murray1  
(1)
IPSWICH, UK
 

VLOOKUP is one of the most used functions in Excel. Almost anyone who has used Excel for a certain number of years would have heard of VLOOKUP and has likely written one or two.

This function is often considered a benchmark in a user’s Excel development – that moment when they step into the intermediate level of Excel formula skills. I will never forget the days when I was first learning VLOOKUP – a wild mixture of confusion, fun, and excitement.

In recent years, with the development of the new array engine in Excel (Chapter 10) and with new functions such as XLOOKUP and FILTER, the position of VLOOKUP as the number 1 lookup function of Excel is beginning to get a little shaky.

Make no mistake though. This function is incredibly useful, very popular (used in millions of spreadsheets worldwide), and therefore important for an Excel formula jedi to master.

VLOOKUP is available in all versions of Excel, so is reliable when sharing spreadsheets to staff across different offices or to users external to your organization.

In this chapter, we will begin with the basics of VLOOKUP and learn how to write the two different types of lookups (exact match and range lookup). We will learn some neat VLOOKUP tricks and understand common reasons to why things go wrong.

As the chapter progresses, we will see more advanced uses of VLOOKUP including using multiple lookup criteria and returning a specific instance of a value.

File

vlookup.xlsx

Introduction to VLOOKUP

Availability: All versions

The name VLOOKUP stands for vertical lookup. It looks for a value, within a table, and returns a value from the same row but from a different column in the table.

The VLOOKUP function always looks for a value in the first column of the table in which it is told to search.

There are many reasons VLOOKUP is used. The most common use is to look up values in another table to combine them into one main table. This table would then be used for the analysis such as a PivotTable.

Other reasons include to compare two lists for differences, automate data entry on a spreadsheet, and fetch values from a lookup table for use in calculations, for example, a lookup table of different tax rates by city.

VLOOKUP asks for four pieces of information:
=VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])
  • Lookup value: The value you are looking for.

  • Table array: The table or range that you are looking and returning from.

  • Col index num: The number of the column containing the value you want to return. This is the column number within the table array, not the worksheet.

  • [Range lookup]: A logical value (TRUE or FALSE) to specify whether you are looking in ranges of values or not. This is an optional argument.

    TRUE is used to request a range lookup (also known as an approximate match). This is the default option. FALSE is used to specify an exact match.

VLOOKUP for an Exact Match

The most common form of VLOOKUP is to perform an exact match. This means that you are looking for a unique value such as a product code, booking reference, or an employee ID.

In this first example, we have a table named [tblTiers] that contains the prices for different membership tiers (Figure 7-1).

We have a table of customers and the membership tier they are enrolled in. We want to use VLOOKUP to return the price for each customer’s membership.
Figure 7-1

Lookup table with tier prices

Note

Although the second argument of VLOOKUP is named table array and this example uses a table, it should be noted that it does not need to be a table. It could be a range such as $B$2:$C$7, a named range, or an array returned by another function.

In Figure 7-2, the following formula is used in column C to return the membership price for each customer:
=VLOOKUP([@Membership],tblTiers,2,FALSE)
There are a few points of interest in this first VLOOKUP formula:
  • VLOOKUP looks vertically down the first column of a given table. In this example, that is the [Tier] column of the [tblTiers] table.

  • FALSE is used to specify an exact match in the final argument.

  • The tiers in [tblTiers] are in ascending order by the [Price] column and not by [Tier]. This demonstrates that when performing an exact match, the table array does not need to be ordered by its first column.

  • The column index number is 2. [Price] is the second column in the [tblTiers] table.

Figure 7-2

VLOOKUP to return the price for each membership

Note

For the range lookup argument, a 0 can be entered to request an exact match instead of False, and a 1 can be entered to specify a range lookup instead of True.

VLOOKUP for a Range Lookup

The second type of lookup that you can perform with VLOOKUP is a range lookup. With this type of lookup, you are looking within ranges of values. For example, these could be date or time ranges or other values such as exam scores, amounts spent, or some other performance value.

This type of lookup, although not as commonplace as an exact match lookup, can be very useful. Let’s see two examples.

In the first example, we have the lookup table shown in Figure 7-3. The first column contains a range of quantity values. We have a table of orders and want to look up the quantity ordered and return the earned discount.

When performing a range lookup (also known as an approximate match), it is essential that the first column of the lookup table is in ascending order.

VLOOKUP will match the value to the closest value less than the one searched for. So, for example, if we were looking for a quantity of 49 in the lookup table of Figure 7-3, the discount of 3% is returned, as 15 is the closest match less than 49.
Figure 7-3

Range of quantities and discounts to look up

The following formula has been used in Figure 7-4 to return the discount earned:
=VLOOKUP(B2,'Range Lookup Data'!$A$2:$B$7,2,TRUE)
Things to note in this formula include
  • The lookup range is not formatted as a table, so has been referenced in the formula as 'Range Lookup Data'!$A$2:$B$7.

This shows that the lookup table does not need to be in an Excel table; however, the use of tables is an improvement over the range that includes a worksheet name and absolute cell references.
  • TRUE has been entered for the range lookup argument to specify an approximate match.

This argument is named range lookup , as it is asking you if you are looking in ranges or not. In this example, the answer is true; yes, we are looking in ranges of values. Remember, we could also type 1, or omit a response, as TRUE is the default lookup type.
Figure 7-4

VLOOKUP returning the appropriate discount of each quantity ordered

In the second example, the lookup table in Figure 7-5 contains date ranges in its first column. In the second column of the table is a tax rate that changes at specific dates. This table is named [tblRates].
Figure 7-5

Lookup table with date ranges and tax rates

In Figure 7-6, the following VLOOKUP formula is used to return the necessary rate:
=VLOOKUP(H2,tblRates,2)
In this formula, the range lookup argument is omitted. The default result of the range lookup argument is True, so this is fine.
Figure 7-6

Returning the tax rate dependent upon the date of transaction

Column Index Number Tricks

In the examples demonstrated so far, the lookup tables have been small, and the column index number has always been 2. When looking up data in larger tables, counting to find the correct column index number can be frustrating.

There are a few tricks that we can deploy to save having to count to find the required column index number. These tricks also work in making our VLOOKUP formulas more durable, as when typing the number directly into the formula, it can easily be broken by someone inserting or deleting a column.

Another mistake can be that a user did not count hidden columns when finding the column index number.

Trick 1: The COLUMN Function

Availability: All versions

The COLUMN function returns the column number of a given reference. This reference can be a cell, table column, or a named range. It returns the column number of the sheet, for example, column D is column number 4.

The COLUMN function only asks for the reference from which to return the column number. This is an optional argument. If omitted, the column number of cell where the formula resides is returned.
=COLUMN([reference])

This function is ideal for the task of preventing having to find the column number in the lookup table ourselves. We can just reference the column of the lookup table that we want, and COLUMN returns its index number.

In Figure 7-7, we have a table named [tblReps] containing data about our sales representatives. We will use a VLOOKUP function to return the data from the [Status] column to another table.
Figure 7-7

Sales representative data

The following formula is used in Figure 7-8 to return the status data. A similar formula was also used in cell F2 to return the rep name.
=VLOOKUP(E2,tblReps,COLUMN(tblReps[Status]),0)

The COLUMN function is provided with the [Status] column of the table. This makes it very simple to provide a column number to VLOOKUP, as referencing columns in a table is fast and easy. This technique was covered in Chapter 4.

Remember, the column number returned is the column number of the worksheet, not the table.

As this lookup table (Figure 7-7) starts in column A, the worksheet column and the table column are the same number, so it is not a problem. However, let’s explore an alternative scenario.
Figure 7-8

COLUMN function used to prevent entering the column number

In Figure 7-9, the [tblReps] table now begins in column C. So, the [Status] column is the fifth column of [tblReps], but the seventh column of the worksheet.
Figure 7-9

Lookup table beginning from column C

For the COLUMN function to work, we will need to subtract two from its result to account for columns A and B not being used by the table.

In the following formula, minus 2 is entered after the COLUMN function (Figure 7-10):
=VLOOKUP(E2,tblReps,COLUMN(tblReps[Status])-2,0)
Figure 7-10

VLOOKUP function with COLUMN to fetch the column number

If someone were to insert another column, or remove a column, before the start of the table, our formula would fail. The subtraction of 2 would no longer be relevant.

For a more robust version of this formula, we want to dynamically return the column number of the column directly before the table, 2 in the previous example. To do this, the COLUMN function will be used to return the sheet’s column number of the first column of the table. One will be subtracted from this to return the column number that precedes the start of the table.

The following formula is entered in cell G2 (Figure 7-11). The calculation to return the start column is enclosed in brackets to calculate first.
=VLOOKUP(E2,tblReps,COLUMN(tblReps[Status])-(COLUMN(tblReps[ID])-1),0)
Figure 7-11

More robust version of VLOOKUP with the COLUMN function

Trick 2: The COLUMNS Function

Availability: All versions

The COLUMNS function returns the number of columns in a given reference or array. This could be a reference to a range of cells, a table, a named range, or an array formula.

The COLUMNS function only requires the array for which to return the total number of columns:
=COLUMNS(array)

This function is very useful when the column number you require is at the end or a specific number of columns from the end of a reference or array.

In Figure 7-12, we have a table named [tblMonthly] that contains monthly performance values for staff. We require a VLOOKUP to return the last month’s performance. This will always be the final column in the table (currently May-21).

The COLUMNS function will be perfect for this task, as every month the table will expand with another column when a new month is added. The COLUMNS function will always return the number of columns in the table, that is, the final column number.

So, this will always be correct even when the table expands. Much better than counting columns or having to update the column number manually each month.
Figure 7-12

Table with staff monthly performance

In Figure 7-13, the following VLOOKUP formula is used to return the monthly total for each staff member. The COLUMNS function is used for the column index number argument to return the final column number from [tblMonthly].
=VLOOKUP(A2,tblMonthly,COLUMNS(tblMonthly),FALSE)
Figure 7-13

COLUMNS function used to return the final column’s data

If the required column number was a specified number of columns from the end, this number could be subtracted from the COLUMNS result. For example, the following formula would return the previous month’s value:
COLUMNS(tblMonthly)-1
Note

There are also ROW and ROWS functions in Excel to perform the equivalent tasks but for rows instead of columns. We will see ROWS later in this book.

Trick 3: Using an Index Row

Another technique that you may come across is the creation of an index row. This is a row where the column index numbers of the table are entered and then referenced in the VLOOKUP.

Figure 7-14 shows an index row set up above a lookup table. Notice that the lookup table range begins in column B, but the column is indexed as column 1, ready for VLOOKUP. This lookup range is on a sheet named [Index Row Data].

This row is often hidden once the formulas are created, to avoid accidental damage and to remove clutter.
Figure 7-14

Lookup table with an index row

In Figure 7-15, the following formula is used to return the data from the [Status] column. It references cell F1 of the [Index Row Number] sheet to return the required column index number.
=VLOOKUP(E2,'Index Row Data'!$B$3:$G$11,'Index Row Data'!$F$1,0)
Figure 7-15

VLOOKUP referring to a cell value to return the column index number

Referring to a cell value in this manner is another trick to avoid counting the columns of your larger lookup tables.

It is not as durable as using the COLUMN function can be, but it is very simple to set up and utilize.

Note

Another technique is to use the MATCH function to find and return the required column number. We will see this technique in Chapter 11, when we explore more lookup functions in Excel.

Reasons Why VLOOKUP Is Not Working

There are a few reasons why your VLOOKUP is not working. Let’s explore some of the common reasons along with their solutions.

Lookup Column Must Be the First Column

VLOOKUP looks for a value down the first column of a given range or array. If the column you need to look in is not the first (or leftmost) column of the table array, VLOOKUP will not find a match.

In Figure 7-16, the following VLOOKUP is returning the #N/A error as it cannot find a match for the ID value entered in cell B3. The lookup column is the second column of the range provided for the table array argument, $B$6:$E$9, and not the first column.
=VLOOKUP(B3,$B$6:$E$9,4,FALSE)
Figure 7-16

The lookup column needs to be the first column

This can be fixed by reordering the columns of the lookup table so that the ID column is first or by using a different formula to VLOOKUP, such as XLOOKUP or the INDEX-MATCH function combination.

Another fix in this example is that you do not need to select all the columns of a table or range, only the ones that you need.

The following VLOOKUP formula uses the range $C$6:$E$9 for the lookup table (Figure 7-17). So, VLOOKUP now looks down column C and finds a match. Then it returns from column 3, as the salary is the third column of range $C$6:$E$9.
=VLOOKUP(B3,$C$6:$E$9,3,FALSE)
Figure 7-17

VLOOKUP now works with an adjusted table array

Data Type of the Values Must Match

This issue causes problems even for regular users of VLOOKUP. The data type of the lookup value and the value it finds must match, not just its value.

This issue commonly occurs when the table array is an export from an external source, and the numeric values are stored as text. However, the lookup value is a number.

In Figure 7-18, the lookup value in cell G3 is numeric, but the values in range $G$6:$G$9 are text values. You see their different alignment in the cells. VLOOKUP returns the #N/A error as it cannot match the lookup value.
Figure 7-18

VLOOKUP not working due to problem with the data type

The fix is to convert either the lookup value to text or the values in the lookup column to numbers. Which side you convert depends on what the value should be – text or number.

Figure 7-19 shows the values in G6:G9 converted to numbers and the VLOOKUP now working.

The Text to Columns command in Excel provides a quick way to convert text to numbers. You need only to select the values, click DataText to Columns and then click Finish to close the window for a quick conversion.

We did discuss functions such as VALUE in Chapter 5 that will perform this task also.
Figure 7-19

ID values are converted to numbers and the VLOOKUP works

This issue can be confusing and difficult to detect. Figure 7-20 shows the numeric values in range G6:G9 selected. They are left aligned and have a text format applied, so do not appear as numbers.

However, the VLOOKUP function is working, as the data type of cell G3 and the values in range G6:G9 do match.
Figure 7-20

Numbers appearing as text can be confusing

When diagnosing issues such as this and it is unclear what data type a value is, the information functions such as ISNUMBER and ISTEXT are very helpful. They check if a value is a number or is text and will return TRUE if it is a match.

In Figure 7-21, the ISNUMBER function has been used to check the values in the original problem. The formula in cell I3 has confirmed that the value in cell G3 is a number, but the formulas in range K6:K9 show that the values in G6:G9 are not numbers.
Figure 7-21

ISNUMBER function confirming the data type of values

Exact Match Has Not Been Specified

This is a common mistake for users that are new to using VLOOKUP. So, keep an eye out for this on spreadsheets set up by others that include VLOOKUP.

The final argument of VLOOKUP is range lookup. This argument is confusing when you are getting started with this function, it is optional, and TRUE is the default. These three factors seem to lead to the argument being missed or ignored.

If you require an exact match but do not specify one, you run the risk of having the wrong results and errors returned.

In Figure 7-22, the final argument is omitted when an exact match is required. You can see the incorrect result for ID 3992 in cell C6. There is also an error in cell C3 for ID 1841.

The values in the lookup table are not in ascending order by the first column, which is a requirement when performing range lookups. This is causing the chaos.
Figure 7-22

VLOOKUP returning incorrect results and errors

The fix for this problem is simple. An exact match needs to be specified for this VLOOKUP by entering FALSE or 0 in the final argument (Figure 7-23).
Figure 7-23

Exact match is specified and the VLOOKUP works

Ranges Must Be in Ascending Order

As we already know, the ranges need to be in ascending order when performing range lookups (approximate match lookups). If a lookup table has been ordered differently for any reason, this will present a problem for VLOOKUP.

In Figure 7-24, the VLOOKUP formulas in range J3:J8 are having trouble returning the correct results. This is because the scores in range L3:L6 are not in ascending order.
Figure 7-24

Ranges not in order breaking VLOOKUP

To fix this issue, the first column of the lookup table needs to be sorted into ascending order.

Figure 7-25 shows a functional VLOOKUP now that the scores are in the correct order.
=VLOOKUP(I3,$L$3:$M$6,2,TRUE)
Figure 7-25

VLOOKUP working now that the ranges are in ascending order

Handling Fake Errors with VLOOKUP

Now, not all errors that VLOOKUP returns are real errors. VLOOKUP is very eager to return #N/A if it cannot complete its job. And sometimes there are logical and valid reasons why it cannot complete its job.

In these circumstances, an alternative action is desired over the error returned by VLOOKUP.

In this example, we have a simple claim form for mileage expenses in Excel. When a user specifies the site that they traveled to, we want a VLOOKUP to return the distance in miles of that site.

Figure 7-26 shows a lookup range with the locations that someone may travel to and the distance in miles.
Figure 7-26

Lookup range with locations and their distance

Figure 7-27 shows the mileage claim form. There are some empty rows where there are no expenses to claim.

The following VLOOKUP returns the #N/A error. This looks ugly and is also breaking the formulas in range E3:E7 and the SUM functions in cells D9 and E9.
=VLOOKUP(C3,$H$3:$I$7,2,FALSE)
We would like to replace the #N/A errors with the value of 0. This is a more appropriate response, looks neater, and, most importantly, ensures the formulas will return the correct results.
Figure 7-27

VLOOKUP returning errors for the empty destination cells

There are two main functions for this task – IFERROR and IFNA. These functions use the same syntax and were covered in detail in Chapter 2, so we will dive straight in and use these now.

In Figure 7-28, the following formula uses IFERROR to handle the errors returned by VLOOKUP. If the VLOOKUP returns an error, a 0 is shown as the alternate action.
=IFERROR(VLOOKUP(C3,$H$3:$I$7,2,FALSE),0)
Note

The IFERROR function will return an alternate action if any error is returned by VLOOKUP; IFNA focuses on the #N/A error only.

Figure 7-28

IFERROR function added to replace errors with 0

Although entering the value 0 is used in this example, we could have displayed any value or run an alternate formula.

The HLOOKUP Function

Availability: All versions

VLOOKUP has a lesser-known sibling – HLOOKUP. As you may have guessed, this stands for horizontal lookup.

The HLOOKUP function has the same syntax as VLOOKUP, though the third argument asks for a row index number instead of a column index number:
=HLOOKUP(lookup_value, table_array, row_index_number, [range_lookup])

Due to its less common usage compared to VLOOKUP, we will see only one example of HLOOKUP. However, every example demonstrated with VLOOKUP in this chapter can be performed with HLOOKUP, if required.

Figure 7-29 shows a lookup table/range with weekly performance values relating to some individuals. The headers are in the first column of the range (column B) with each field’s data stored in rows.

In Figure 7-29, the following HLOOKUP function is entered in cell C2 and is returning the value for week 4 from the fifth row of the lookup range C4:F8 for Cyndy:
=HLOOKUP(B2,$C$4:$F$8,5,FALSE)
Figure 7-29

HLOOKUP returning the value from the fifth row of the lookup range

Get VLOOKUP to Look to the Left

One of the limitations of VLOOKUP is that it can only return a value from a column to the right of the one containing the lookup value (the first column).

Now this is not often a problem, as the first column of a table is typically a unique identifier. However, there is a trick to get VLOOKUP to look to its left.

Take the example shown in Figure 7-30. We need a VLOOKUP to return the grade for the score earned by each person.

The following VLOOKUP formula is returning errors in column D. This is due to VLOOKUP looking for the score in the [Grade] column, as that is the first column of the lookup range.
=VLOOKUP(C3,$F$3:$G$6,2,TRUE)
Now, we could reorder the data in columns F and G, and VLOOKUP would work fine. But let’s look at a trick to get VLOOKUP looking to its left, and we do not need to reorder any columns.
Figure 7-30

VLOOKUP returning errors as the score is not the leftmost column

This trick requires the use of the CHOOSE function in Excel. The CHOOSE function will change the order of the columns for VLOOKUP to work from.

The CHOOSE function returns a value, or performs an action, from a list of given values and actions. The value or action it chooses from the list is based on an index number.

It requires only the index number and the list of possible values and actions:
=CHOOSE(index_num, value1, [value2],...)
In Figure 7-31, the following formula is used to change the order of the columns within VLOOKUP. It, therefore, returns the correct grade without physically changing the column order of the lookup range.
=VLOOKUP(C3,
CHOOSE({1,2},$G$3:$G$6,$F$3:$F$6),
2,TRUE)

The CHOOSE function is used in the table array argument of VLOOKUP. It is given the array of constants {1,2} for its index number. It is then told to return range $G$3:$G$6 first and $F$3:$F$6 second, therefore reversing the column order.

This is an array formula, so press Ctrl + Shift + Enter to run it if you are not using Excel for Microsoft 365, Excel for the Web, or Excel 2021.

Note

The CHOOSE function is covered in more detail in Chapter 11, when we explore more lookup functions.

Figure 7-31

CHOOSE function included to change the column order

Note

This technique is fun and good to be aware of. However, for a more flexible lookup formula, the INDEX and MATCH combination or XLOOKUP functions in Excel are encouraged.

Partial Match Lookup

A partial match is when only part of the lookup value text needs to match. Sometimes, you may be looking to perform a partial match instead of an exact text match.

For example, Figure 7-32 shows a table named [tblTargets]. It contains the performance targets for different offices that are in different cities. The [City] column contains the country name in addition to the city.

We need to match a city to one in the [City] column of [tblTargets]. However, we cannot get an exact match because the country name is also in those cell values. We need to perform a partial match.
Figure 7-32

Table of offices and their respective targets

The VLOOKUP function allows the use of wildcard characters directly in the function. This makes it easy to create partial matches with VLOOKUP.

There are three wildcard characters that can be used in your VLOOKUP formulas:
  • * (Asterisk): Represents any number of characters. For example, New* would match with Newport, Newcastle, New York, and New Zealand.

  • ? (Question mark): Represents a single character. For example, L????n would match with both London and Lisbon.

  • ~ (Tilde): Used to treat a wildcard character as a text character. For example, *don would match any text that ends in the characters don, but ~*don will look for an exact match of *don, treating the asterisk as its character and not a wildcard.

In Figure 7-33, the following formula uses the asterisk wildcard to perform a partial match on the city in the [tblTargets]:
=VLOOKUP(C3&"*",tblTargets,2,0)

The asterisk is joined after the city name in cell C3. Perfect for this scenario. We do not know how many characters will follow the city name, but we know there will be some.

Notice that the asterisk is enclosed in double quotations and joined using the ampersand.
Figure 7-33

VLOOKUP with a wildcard character for a partial match

If we want to create a partial match where the city is mentioned anywhere within the cell value, then an asterisk would also be added before the value in cell C3:
=VLOOKUP("*"&C3&"*",tblTargets,2,0)

Case-Sensitive VLOOKUP

Excel formulas rarely consider the case of characters when matching values. There are exceptions to this, for example, the FIND function is case-sensitive.

Figure 7-34 shows a VLOOKUP formula returning incorrect results for the lookup values written in lowercase – a and b.

Let’s look at how we can fix this by creating a case-sensitive VLOOKUP.
Figure 7-34

VLOOKUP returning incorrect results due to case discrepancy

To create a case-sensitive VLOOKUP, the CHOOSE and EXACT functions will be used together. This is an advanced example that creates a two-dimensional array for VLOOKUP to use.

We saw an example of EXACT being used to match case in Chapter 2 of this book. Back then, we were working with the IF function. Let’s quickly remind ourselves on the EXACT function.

The EXACT function compares two text strings to see if they are exactly the same, including their case. It returns True if they are the same; otherwise, False is returned.

It requires two arguments – the two text strings to compare.
=EXACT(text1, text2)

We saw the CHOOSE function two examples ago, when we made VLOOKUP look to its left.

In Figure 7-35, the following formula has been used for a case-sensitive VLOOKUP formula. The correct results are now being returned for levels a and b.
=VLOOKUP(TRUE,
CHOOSE({1,2},EXACT(C3,$G$3:$G$8),$H$3:$H$8),
2,FALSE)
This is an array formula. If you are using a version of Excel with the array engine, the formula will work as normal. Otherwise, you will need to press Ctrl + Shift + Enter to run the formula.
Figure 7-35

Case-sensitive VLOOKUP formula

So, how does this work?

Firstly, the EXACT function compares the strings from the lookup value in C3 and the values in the lookup range of G3:G8. The following array of logical values is returned:
{TRUE;FALSE;FALSE;FALSE;FALSE;FALSE}
The array of constants {1,2} has been provided as the index number for CHOOSE. So, the CHOOSE function then combines the results of the EXACT function and the values in range H3:H8 into a two-dimensional array.
{TRUE,0.15;FALSE,0.12;FALSE,0.1;FALSE,0.075;FALSE,0.05;FALSE,0.025}

The VLOOKUP function has been given the lookup value of TRUE, so it now looks for TRUE down the first column of the two-dimensional array it has been given and returns the value from the second column.

Multiple Column VLOOKUP

It may be that you have two or more columns that need to be used in a lookup. VLOOKUP was not made with this scenario in mind, and it is much easier to perform with a function such as XLOOKUP or with a Merge Query in Power Query.

However, of course, it can be done. In Figure 7-36, we have a table (columns G:I) named [tblLastMonth] that contains a [Regional Code] column and a [Client ID] column along with last month’s [Total] value.

In column E, we need a VLOOKUP to return the [Total] value for the matching combination of regional code and client ID.
Figure 7-36

Sample data with two columns to match with our lookup

We will do this by first creating a new column in [tblLastMonth] with the combined [Regional Code] and [Client ID]. This column will be the one used for the lookup, so it needs to be the first column of the table.

To insert a new column in a table (not the worksheet)
  1. 1.

    Right-click any cell in the [Regional Code] column of the table.

     
  2. 2.

    Point to Insert and click Table Columns to the Left (Figure 7-37).

     
  3. 3.

    Type the header “Reference” for the new column.

    Note You can also insert a table column by clicking HomeInsertInsert Table Columns to the Left.

     
Figure 7-37

Insert a table column to the left of the first column

The following formula has been entered in the new [Reference] column to concatenate the [Regional Code] and [Client ID] column values (Figure 7-38):
=[@[Regional Code]]&[@[Client ID]]
Figure 7-38

Reference column from combined regional code and client ID

In Figure 7-39, the following VLOOKUP formula is then used to return the previous month’s value:
=VLOOKUP(B3&C3,tblLastMonth,4,0)
The two lookup value columns have been combined to search in the first column of [tblLastMonth] and return the value from column 4.
Figure 7-39

Multicolumn VLOOKUP formula

This technique can easily be extended to work for more than two columns, if required.

Taking this a step further, you can create a multicolumn VLOOKUP using a single formula. So, we can achieve this without inserting a new table column and creating the merged [Regional Code] and [Client ID] column.

In Figure 7-40, the following formula is entered in cell E3. It uses the CHOOSE function to create an array (a virtual table you could say) consisting of two columns. The first column is a merged [Regional Code] and [Client ID] column and the second column is the [Total] column. The VLOOKUP then searches for the multicolumn lookup value in this array and returns the matching value from the second column.
=VLOOKUP(B3&C3,
CHOOSE({1,2},
tblLastMonth[Regional Code]&tblLastMonth[Client ID],
tblLastMonth[Total]),
2,0)
Figure 7-40

Multiple column VLOOKUP with a single formula

We saw the CHOOSE function recently when getting VLOOKUP to look to its left. This brilliant function is covered in more detail in Chapter 11.

Return the Nth Match

The VLOOKUP function always returns a value for the first occurrence of the lookup value that it matches, searching from top to bottom.

Now, if you want to return multiple results, this is not something that VLOOKUP can do. You want to use the FILTER function, covered in Chapter 13.

We can however use VLOOKUP to return a specific instance of the lookup value, such as the second, third, fourth, or nth instance.

In Figure 7-41, we have a lookup range that contains multiple instances of participant names and their scores in a contest. Each participant has three attempts, so they occur three times.

We will use a VLOOKUP to return all three scores to range C5:C7 for the name stated in cell C2.
Figure 7-41

Multiple occurrences of participant scores

Like the previous example, our first task is to create a lookup column in the first column position of the lookup table that we can use to uniquely identify each instance.

In Figure 7-42, the following formula is used to combine the value in the [Name] column and the instance number it occurs:
=G3&COUNTIFS($G$3:G3,G3)

The COUNTIFS function (covered in Chapter 8) is used to count the occurrences of each name.

The interesting part of this formula is the criteria range given to COUNTIFS. It has an absolute cell reference at the start of the range and a relative cell at the end of the range. This ensures that the criteria range expands as the formula is filled down the cells of column E.

So, in range $G$3:G3, David occurs only once. But when the formula gets to the second occurrence of David, the criteria range is $G$3:G7 and includes the second occurrence.
Figure 7-42

Lookup column with name and instance number combined

In Figure 7-43, the following VLOOKUP formula is used to return the first, second, and third scores for the name entered in cell C2:
=VLOOKUP($C$2&B5,$E$3:$H$11,4,FALSE)
The lookup value is a combined value of the name in cell C2 and the instance number from range B5:B7. When the name in cell C2 is changed, the scores for that participant are returned.
Figure 7-43

VLOOKUP returning the first, second, and third instances of a value

It is possible to achieve the same result using a VLOOKUP formula without the helper column identifying each unique instance. It is a more advanced formula.

In Figure 7-44, the following array formula is entered in cell C5. As it is an array formula, if you are using a non-dynamic array version of Excel, you need to press Ctrl + Shift + Enter to run the formula.
=VLOOKUP(
SMALL(IF($F$3:$F$11=$C$2,ROW($F$3:$F$11)),B5),
CHOOSE({1,2},ROW($F$3:$F$11),$G$3:$G$11),
2,0)

So, how does this formula work?

In the lookup value argument of VLOOKUP, the IF function tests the names in range $F$3:$F$11 against the name in cell $C$2. It then uses the ROW function to return an array consisting of the row number of the matching name or FALSE if the name does not match. The following array is returned by IF when “Kelly” is entered in cell $C$2:
{FALSE;4;FALSE;FALSE;FALSE;8;FALSE;FALSE;11}
The ROW function returns the row number of the worksheet, not the row number with range $F$3:$F$11. “Kelly” is matched to rows 4, 8, and 11.
Figure 7-44

Returning the Nth match with a single VLOOKUP formula

The SMALL function then returns the Nth smallest number in this array. This number is specified by the values in range B5:B7. For the formula in cell C5, the SMALL function returns 4 as that is the first smallest number.

The CHOOSE function is used in the table array argument of VLOOKUP (Again! What a useful function!). It creates an array consisting of two columns.

In column 1, the ROW function returns a list of the sheet row numbers for range $F$3:$F$11. The result is {3;4;5;6;7;8;9;10;11}. Column 2 is simply the values from range $G$3:$G$11.

The VLOOKUP function searches for the row number returned by the SMALL and IF combo, in the column of row number provided by ROW, and returns the score value from column 2 of the array created by CHOOSE. Awesome!

VLOOKUP with Other Excel Features

As always, we will conclude the chapter with some examples of how VLOOKUP can be used with other Excel features. Let’s see two examples, one with Conditional Formatting and another with a chart.

Conditional Formatting and VLOOKUP

For a Conditional Formatting example, we want to format the values that exceeded a target score. The target score resides in a different table to the one with the formatted values, so we will use VLOOKUP to retrieve it for testing.

Figure 7-45 shows a list of staff, their locale, and their performance value. A second table lists the different targets by locale.

We want to format only the values in range D3:D9 that are greater than or equal to the respective target for that staff member’s locale.
Figure 7-45

Performance values and a separate target by locale table

  1. 1.

    Select range D3:D9.

     
  2. 2.

    Click HomeConditional FormattingNew RuleUse a formula to determine which cells to format.

     
  3. 3.

    Enter the following formula into the Format values where this formula is true: box (Figure 7-46):

     
=D3>=VLOOKUP(C3,$F$3:$G$9,2,FALSE)
Note

It is often easier to type a formula into a cell first and then copy and paste it into the Conditional Formatting rule. The formula box is quite small and offers little help, and you need to be careful to be in the correct cell mode when moving through the formula.

  1. 4.

    Click Format and specify the formatting you want to use.

     
  2. 5.

    Click OK to apply and close each window.

     
Figure 7-46

VLOOKUP in a Conditional Formatting rule

Figure 7-47 shows the formatting rule successfully applied to range D3:D9.
Figure 7-47

Formatting rule to format only values that are >= the target value

Dynamic Chart Range

In this chart example, we will create a dynamic chart range that changes on the selection of a value from a drop-down list.

In Figure 7-48, there is a table named [tblWeekly] with six weeks’ performance data by different staff members. Below the table are headers in preparation for our range that will feed the chart, and in cell J3 is a drop-down list of the different staff members’ names.

When someone selects a name from the drop-down list, we want the values for that selected staff member to show in the range below the table. The chart will be based on that range, so will change when the drop-down list value changes.
Figure 7-48

Table of data with a chart range below and a list in cell J3

Note

Typically, the table of data, chart range, and chart with drop-down list would all be on different worksheets – a data sheet, calculation sheet, and a report/presentation sheet. It is displayed all-in-one here only to show the mechanics of the technique easier.

First, we want the selected name to appear in cell B12. This is achieved with a simple link to the value in cell J3. This cell value will be used as the chart title.
=J3
In range C12:H12, the following VLOOKUP formula is used to return the weekly values for the selected name (Figure 7-49):
=VLOOKUP($J$3,tblWeekly,COLUMN(C11)-1,FALSE)

The COLUMN function is used to return the column index number so that we do not need to enter it ourselves in six different VLOOKUP formulas, when we fill the formula.

It references the cell directly above the formula (C11 in the formula shown), and one is subtracted from the COLUMN function result because [tblWeekly] begins in column B. So, [Wk1] is the second column of the table, but the third column of the sheet.
Figure 7-49

VLOOKUP formula for a dynamic chart range

With the chart range created, the chart can now be created. For this example, let’s create a simple line chart:
  1. 1.

    Select range B11:H12.

     
  2. 2.

    Click InsertInsert Line or Area ChartLine.

     
  3. 3.

    Make the necessary improvements to the chart to make it look awesome.

     
Figure 7-50 shows a basic line chart with no modifications positioned underneath the drop-down list.
Figure 7-50

Dynamic chart based on the value from the drop-down list above it

Note

Creating the chart is explained very briefly here as working with charts is not the purpose of this book. It is the formulas and the creation of the dynamic chart range that is our focus.

Summary

In this chapter, we learned the VLOOKUP function in Excel along with some tricks to creating a more robust and effective VLOOKUP formula and an understanding of common mistakes that users make. We then progressed to some advanced examples that included multi-criteria and case-sensitive lookups.

In the next chapter, we will look at formulas that perform aggregations such as sum, count, and average dependent on conditions that are met. There is a group of functions in Excel built for these purposes. This group includes SUMIFS, COUNTIFS, and AVERAGEIFS.

There are similar functions, also covered in the next chapter, just outside the scope of this group that includes MEDIAN, TRIMMEAN, and MODE.MULT.

Using functions such as these to aggregate values based on conditions is very popular in Excel. We have lots to cover, so let’s get started.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.27.244