Chapter 9第9章
Using Powerful Functions: Logical, Lookup, and Database Functions使用强大的功能:逻辑、查找和数据库功能

Examples of Logical Functions逻辑函数示例

Examples of Information Functions信息功能示例

Examples of Lookup and Reference Functions查找和引用函数的示例

Examples of Database Functions数据库功能示例

Examples of Linked Data Types链接数据类型的示例

This chapter covers four groups of workhorse functions. 本章涵盖四组主要功能。If you process spreadsheets of medium complexity, you turn to logical and lookup functions regularly.如果您处理中等复杂度的Electron表格,则需要定期使用逻辑和查找功能。

Table 9.1 provides an alphabetical list of all the logical functions in Excel 2019. 提供Excel 2019中所有逻辑函数的字母顺序列表。Detailed examples of these functions are provided later in this chapter.本章后面将提供这些功能的详细示例。

Table 9.1 Alphabetical List of Logical Functions按字母顺序排列的逻辑函数列表

Function函数

Description描述

AND(logical1, logical2,...)

Returns TRUE if all its arguments are TRUE; returns FALSE if one or more arguments are FALSE.如果其所有参数均为TRUE,则返回TRUE;如果一个或多个参数为FALSE,则返回FALSE

FALSE()

Returns the logical value FALSE. 返回逻辑值FALSEThis function is useless, considering that typing FALSE without the parentheses returns the same value.考虑到在不带括号的情况下键入FALSE返回相同的值,此函数是无用的。

IF(logical_test, value_if_true, value_if_false)

Returns one value if a condition specified evaluates to TRUE and another value if it evaluates to FALSE.如果指定条件的计算结果为TRUE,则返回一个值;如果指定条件的计算结果为FALSE,则返回另一个值。

IFERROR(value, value_if_error)

Returns value_if_error if the expression is an error; otherwise, returns the value itself.如果表达式为错误,则返回value_if_error;否则,返回值本身。

IFNA(value, value_if_na)

Returns value_if_na if the expression resolves to #N/A; otherwise, returns the result of the expression.如果表达式解析为#N/A,则返回value_if_na;否则,返回表达式的结果。

IFS(logical_test1, value_if_true1, [logical_test2, value_if_true2…])

Checks whether one or more conditions are met and returns a value corresponding to the first TRUE condition.检查是否满足一个或多个条件,并返回与第一个真条件对应的值。

NOT(logical)

Reverses the value of its argument. 反转其参数的值。You use NOT when you want to make sure a value is not equal to another particular value.当要确保某个值不等于另一个特定值时,可以使用NOT

OR(logical1, logical2,…)

Returns TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.如果任何参数为TRUE,则返回TRUE;如果所有参数都为FALSE,则返回FALSE

SWITCH(Expression, Value1, Result1, [Default_or_value2], [Result2]…)

Evaluates an expression against a list of values and returns the result corresponding to the first matching value. 根据值列表计算表达式,并返回与第一个匹配值相对应的结果。If there is no match, an optional default value is returned.如果不匹配,则返回可选的默认值。

TRUE()

Returns the logical value TRUE. 返回逻辑值TRUEEquivalent to typing TRUE.相当于输入TRUE

XOR()

Returns the logical Exclusive Or of the arguments. 返回参数的逻辑异或。However, to be compatible with an XOR chip frequently used in electrical engineering, this function actually measures if an odd number of arguments are TRUE. 然而,为了与电子工程中常用的异或芯片兼容,该函数实际上测量奇数个参数是否为TRUEPeople who don’t make their living designing electrical circuits will wonder why =XOR(True,True,True) is True.不以设计电路为生的人会想为什么=XOR(True,True,True)True

Table 9.2 provides an alphabetical list of the information functions in Excel 2019. 表9.2提供了Excel 2019中信息函数的字母顺序列表。Detailed examples of these functions are provided in the remainder of the chapter.本章剩余部分提供了这些功能的详细示例。

Table 9.2 Alphabetical List of Information Functions按字母顺序排列的信息功能列表

Function函数

Description描述

CELL(info_type, reference)

Returns information about the formatting, location, or contents of the upper-left cell in a reference.返回有关引用中左上角单元格的格式、位置或内容的信息。

ERROR.TYPE(error_val)

Returns a number corresponding to one of the error values in Microsoft Excel or returns an #N/A error if no error exists. 返回与Microsoft Excel中的一个错误值对应的数字,如果不存在错误,则返回#N/A错误。You can use ERROR.TYPE in an IF function to test for an error value and return a text string, such as a message, instead of the error value.您可以在IF函数中使用ERROR.TYPE以测试错误值,并返回文本字符串(如消息),而不是错误值。

INFO(type_text)

Returns information about the current operating environment.返回有关当前操作环境的信息。

ISBLANK(value)

Returns TRUE if value refers to an empty cell. 如果value引用空单元格,则返回TRUENote that if a cell contains “blanks” or spaces, this function will not return TRUE.请注意,如果单元格包含“空格”或空格,此函数将不会返回TRUE

ISERR(value)

Returns TRUE if value refers to any error value except #N/A.如果value引用除#N/A之外的任何错误值,则返回TRUE

ISERROR(value)

Returns TRUE if value refers to any error value (that is, #N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME?, or #NULL!).如果值引用任何错误值(即#N/A#VALUE!#REF!#DIV/0!#NUM!#NAME?#NULL!),则返回TRUE

ISEVEN(number)

Returns TRUE if number is even and FALSE if number is odd.如果number为偶数,则返回TRUE;如果number为奇数,则为FALSE

ISFORMULA(reference)

Checks whether a reference is to a cell containing a formula and returns TRUE or FALSE.检查引用是否指向包含公式的单元格,并返回TRUEFALSE

ISLOGICAL(value)

Returns TRUE if value refers to a logical value.如果value引用逻辑值,则返回TRUE

ISNA(value)

Returns TRUE if value refers to the #N/A (value not available) error value.如果value引用#N/A(值不可用)错误值,则返回TRUE

ISNONTEXT(value)

Returns TRUE if value refers to any item that is not text. 如果value引用非文本的任何项,则返回TRUE(Note that this function returns TRUE if value refers to a blank cell.)(请注意,如果value引用空白单元格,则此函数返回TRUE。)

ISNUMBER(value)

Returns TRUE if value refers to a number.如果value引用数字,则返回TRUE

ISODD(number)

Returns TRUE if the number is odd and FALSE if the number is even.如果number为奇数,则返回TRUE;如果number为偶数,则为FALSE

ISREF(value)

Returns TRUE if value refers to a reference.如果value引用引用,则返回TRUE

ISTEXT(value)

Returns TRUE if value refers to text.如果value引用文本,则返回TRUE

N(value)

Returns a value converted to a number.返回转换为数字的value

NA()

Returns the error value #N/A, which means “no value is available.” 返回错误值#N/A,表示“没有可用值”You use NA to mark empty cells or cells that are missing information to avoid the problem of unintentionally including empty cells in your calculations. 使用NA标记空单元格或缺少信息的单元格,以避免在计算中意外包含空单元格的问题。When a formula refers to a cell containing #N/A, the formula returns the #N/A error value.当公式引用包含#N/A的单元格时,公式返回#N/A错误值。

SHEET([value])

Returns the sheet number of the referenced sheet.返回被引用图纸的图纸编号。

SHEETS([reference]

Returns the number of sheets in a reference.返回引用中的图纸数。

TYPE(value)

Returns the type of value. 返回value的类型。You use TYPE when the behavior of another function depends on the type of value in a particular cell.当另一个函数的行为取决于特定单元格中的值类型时,可以使用TYPE

Table 9.3 provides an alphabetical list of the lookup functions in Excel 2019. 表9.3提供了Excel 2019中查找函数的字母顺序列表。Detailed examples of these functions are provided later in this chapter.本章后面将提供这些函数的详细示例。

Table 9.3 Alphabetical List of Lookup Functions按字母顺序排列的查找函数列表

Function函数

Description描述

ADDRESS(row_num, column_num, abs_num, a1, sheet_text)

Creates a cell address as text, given specified row and column numbers.根据指定的行号和列号,将单元格地址创建为文本。

AREAS(reference)

Returns the number of areas in a reference. 返回引用中的区域数。An area is a range of contiguous cells or a single cell.区域是一系列连续单元或单个单元。

CHOOSE(index_num, value1, value2,...)

Uses index_num to return a value from the list of value arguments. 使用index_numvalue参数列表中返回值。You use CHOOSE to select one of up to 254 values, based on the index number. 使用CHOOSE可根据索引号从最多254个值中选择一个。For example, if value1 through value7 are the days of the week, CHOOSE returns one of the days when a number between 1 and 7 is used as index_num.例如,如果value1value7是一周中的几天,CHOOSE返回17之间的数字用作index_num的一天。

COLUMN(reference)

Returns the column number of the given reference.返回给定引用的列号。

COLUMNS(array)

Returns the number of columns in an array or a reference.返回数组或引用中的列数。

FILTER(Array,Include,[If_Empty])

Filter a range or array. 筛选范围或数组。Office 365 exclusive.Office 365独家版。

FORMULATEXT(reference)

Returns a formula as a string.以字符串形式返回公式。

GETPIVOTDATA(data_field, pivot_table,[field1],[item1],...)

Returns data stored in a pivot table report. 返回数据透视表报表中存储的数据。You can use GETPIVOTDATA to retrieve summary data from a pivot table report if the summary data is visible in the report.如果汇总数据在透视表报表中可见,则可以使用GETPIVOTDATA从透视表报表检索汇总数据。

HLOOKUP(lookup_value, table_array, row_index_num, range_lookup)

Searches for a value in the top row of a table or an array of values, and then returns a value in the same column from a row you specify in the table or array. 在表或值数组的顶行中搜索值,然后从表或数组中指定的行中返回同一列中的值。You use HLOOKUP when your comparison values are located in a row across the top of a table of data, and you want to look down a specified number of rows. 当比较值位于数据表顶部的一行中,并且希望向下查看指定数量的行时,可以使用HLOOKUPYou use VLOOKUP when your comparison values are located in a column to the left of the data you want to find.当比较值位于要查找的数据左侧的列中时,可以使用VLOOKUP

HYPERLINK(link_location, friendly_name)

Creates a shortcut or jump that opens a document stored on a network server, an intranet, or the Internet. 创建用于打开存储在网络服务器、intranet或Internet上的文档的快捷方式或跳转。When you click the cell that contains the HYPERLINK function, Excel opens the file stored at link_location.单击包含HYPERLINK函数的单元格时,Excel将打开存储在link_location的文件。

INDEX(array, row_num, column_num)

Returns the value of a specified cell or array of cells within the array.返回array中指定单元格或单元格数组的值。

INDEX(reference, row_num, column_num, area_num)

Returns a reference to a specified cell or cells within the reference.返回对reference中指定单元格的引用。

INDIRECT(ref_text, a1)

Returns the reference specified by a text string. References are evaluated immediately to display their contents. 返回由文本字符串指定的引用。将立即评估引用以显示其内容。You use INDIRECT when you want to change the reference to a cell within a formula without changing the formula itself.如果要在不更改公式本身的情况下更改对公式中单元格的引用,可以使用INDIRECT

LOOKUP(lookup_value, lookup_vector, result_vector)

Returns a value from either a one-row or one-column range. 从一行或一列范围返回值。This vector form of LOOKUP looks in a one-row or one-column range, known as a vector, for a value and returns a value from the same position in a second one-row or one-column range. 这种向量形式的LOOKUP在一行或一列范围内(称为向量)查找值,并从第二行或一行范围内的相同位置返回值。This function is included for compatibility with other worksheets. 包含此功能是为了与其他工作表兼容。You should use VLOOKUP instead.你应该改用VLOOKUP

LOOKUP(lookup_value, array)

Returns a value from an array. 从数组中返回一个值。The array form of LOOKUP looks in the first row or column of an array for the specified value and returns a value from the same position in the last row or column of the array. 数组形式的LOOKUP在数组的第一行或第一列中查找指定的值,并从数组的最后一行或第列的相同位置返回值。This function is included for compatibility with other spreadsheet programs. 包含此功能是为了与其他电子表格程序兼容。You should use VLOOKUP instead. 你应该改用VLOOKUPHowever, unlike VLOOKUP, the LOOKUP function can process an array of lookup_values.然而,与VLOOKUP不同,LOOKUP函数可以处理lookup_values的数组。

MATCH(lookup_value, lookup_array, match_type)

Returns the relative position of an item in an array that matches a specified value in a specified order. 返回数组中项目的相对位置,该数组按指定顺序与指定值匹配。You 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.当需要某个项目在某个范围内的位置而不是项目本身时,可以使用MATCH而不是其中一个LOOKUP函数。

OFFSET(reference, rows, cols, height, width)

Returns a reference to a range that is a specified number of rows and columns away from a cell or range of cells. 返回对某个区域的引用,该区域距离某个单元格或某个单元格区域有指定数量的行和列。The reference that is returned can be a single cell or a range of cells. 返回的引用可以是单个单元格,也可以是一系列单元格。You can specify the number of rows and the number of columns to be returned.可以指定要返回的行数和列数。

ROW(reference)

Returns the row number of a reference.返回引用的行号。

ROWS(array)

Returns the number of rows in a reference or an array.返回引用或数组中的行数。

RTD(progid, server, topic, [to pic2], ...)

Retrieves real-time data from a program that supports COM automation.从支持COM自动化的程序中检索实时数据。

SINGLE(Value)

Returns a single value when given a value, range or array. 当给定值、范围或数组时,返回单个值。Used instead of implicit intersection. 用于代替隐式相交。Office 365 exclusive.Office 365独家版。

SORT(Array,Sort_index,Sort_order,By_col)

Sorts a range or array. Office 365 exclusive.对范围或数组进行排序。Office 365独家版。

SORTBY(Array, by_array1, sort_order1, ...)

Sorts a range or array based on the values in a corresponding range or array. 根据相应范围或数组中的值对范围或数组进行排序。Office 365 exclusive.Office 365独家版。

TRANSPOSE(array)

Returns a vertical range of cells as a horizontal range, or vice versa. 将单元格的垂直范围作为水平范围返回,反之亦然。TRANSPOSE must be entered as an array formula in a range that has the same number of rows and columns, respectively, because the array has columns and rows. TRANSPOSE必须作为一个数组公式输入,其范围分别具有相同的行数和列数,因为array具有列数和行数。You use TRANSPOSE to shift the vertical and horizontal orientation of an array on a worksheet. 使用TRANSPOSE可以移动工作表上数组的垂直和水平方向。For example, some functions, such as LINEST, return horizontal arrays. 例如,某些函数(如LINEST)返回水平数组。LINEST returns a horizontal array of the slope and y-intercept for a line. 返回直线的斜率和y截距的水平数组。Use TRANSPOSE to convert the LINEST result to a vertical array.使用TRANSPOSELINEST结果转换为垂直数组。

UNIQUE(array, [by_col], [occurs_once])

Returns the unique values from a range or array. 返回范围或数组中的唯一值。Office 365 exclusive.Office 365独家版。

VLOOKUP(lookup_value, table_array, col_index_num, range_lookup)

Searches for a value in the leftmost column of a table and then returns a value in the same row from a column you specify in the table. 在表最左边的列中搜索值,然后从表中指定的列返回同一行中的值。You use VLOOKUP instead of HLOOKUP when your comparison values are located in a column to the left of the data you want to find.当比较值位于要查找的数据左侧的列中时,可以使用VLOOKUP而不是HLOOKUP

Table 9.4 provides an alphabetical list of all the database functions in Excel 2019. 表9.4提供了Excel 2019中所有数据库功能的字母顺序列表。Detailed examples of these functions are provided later in this chapter.本章后面将提供这些功能的详细示例。

Table 9.4 Alphabetical List of Database Functions按字母顺序排列的数据库函数列表

Function函数

Description描述

DAVERAGE(database, field, criteria)

Averages the values in a column in a list or database that match the conditions specified.平均列表或数据库中与指定条件匹配的列中的值。

DCOUNT(database, field, criteria)

Counts the cells that contain numbers in a column in a list or database that match the conditions specified.对列表或数据库中的列中包含符合指定条件的数字的单元格进行计数。

DCOUNTA(database, field, criteria)

Counts all the nonblank cells in a column in a list or database that match the conditions specified.统计列表或数据库中符合指定条件的列中的所有非空单元格。

DGET(database, field, criteria)

Extracts a single value from a column in a list or database that matches the conditions specified. 从列表或数据库中匹配指定条件的列中提取单个值。If multiple matches are found, returns #NUM! error.如果找到多个匹配项,则返回#NUM!错误

DMAX(database, field, criteria)

Returns the largest number in a column in a list or database that matches the conditions specified.返回列表或数据库中与指定条件匹配的列中的最大数字。

DMIN(database, field, criteria)

Returns the smallest number in a column in a list or database that matches the conditions specified.返回列表或数据库中与指定条件匹配的列中的最小数字。

DPRODUCT(database, field, criteria)

Multiplies the values in a column in a list or database that match the conditions specified.将列表或数据库中与指定条件匹配的列中的值相乘。

DSTDEV(database, field, criteria)

Estimates the standard deviation of a population based on a sample, using the numbers in a column in a list or database that match the conditions specified.使用列表或数据库中与指定条件匹配的列中的数字,基于样本估计总体的标准偏差。

DSTDEVP(database, field, criteria)

Calculates the standard deviation of a population based on the entire population, using the numbers in a column in a list or database that match the conditions specified.使用列表或数据库中与指定条件匹配的列中的数字,基于整个总体计算总体的标准偏差。

DSUM(database, field, criteria)

Adds the numbers in a column in a list or database that match the conditions specified.在列表或数据库的列中添加符合指定条件的数字。

DVAR(database, field, criteria)

Estimates the variance of a population based on a sample, using the numbers in a column in a list or database that match the conditions specified.使用列表或数据库中与指定条件匹配的列中的数字,基于样本估计总体的方差。

DVARP(database, field, criteria)

Calculates the variance of a population based on the entire population, using the numbers in a column in a list or database that match the conditions specified.使用列表或数据库中与指定条件匹配的列中的数字,基于整个总体计算总体的方差。

Examples of Logical Functions逻辑函数示例

With only eight functions, the logical function group is one of the smallest in Excel. 逻辑函数组只有八个函数,是Excel中最小的函数组之一。The IF function is easy to understand, and it enables you to solve a variety of problems.IF函数很容易理解,它使您能够解决各种问题。

Using the IF Function to Make a Decision使用IF函数做出决策

Many calculations in our lives are not straightforward. 我们生活中的许多计算并不简单。Suppose that a manager offers a bonus program if her team meets its goals. 假设一位经理提供了一个奖金计划,如果她的团队达到了目标。Or perhaps a commission plan offers a bonus if a certain profit goal is met. 或者,如果达到某个利润目标,佣金计划可能会提供奖金。You can solve these types of calculations by using the IF function.可以使用IF函数来解决这些类型的计算。

Syntax:语法:
IF(logical_test,value_if_true,value_if_false)

There are three arguments in the IF function. IF函数中有三个参数。The first argument is any logical test that results in a TRUE or FALSE. 第一个参数是任何逻辑测试,结果是TRUEFALSEFor example, you might have logical tests such as these:例如,您可能有如下逻辑测试:

A2>100
B5="West"
C99<=D99

All logical tests involve one of the comparison operators shown in Table 9.5.所有逻辑测试都涉及表9.5中所示的一个比较运算符。

Table 9.5 Comparison Operators比较运算符

Comparison Operator比较运算符

Meaning意思

Example实例

=

Equal to相当于

C1=D1

>

Greater than大于

A1>B1

<

Less than小于

A1<B1

>=

Greater than or equal to大于或等于

A1>=0

<=

Less than or equal to小于或等于

A1<=99

<>

Not equal to不等于

A2<>B2

The remaining two arguments are the formula or value to use if the logical test is TRUE and the formula or value to use if the logical test is FALSE.其余两个参数是逻辑测试为TRUE时使用的公式或值,以及逻辑测试为FALSE时使用的公式或值。

When you read an IF function, you should think of the first comma as the word then and the second comma as the word otherwise. 阅读IF函数时,应将第一个逗号视为单词then,将第二个逗号视作为单词otherwiseFor example, =IF(A2>10,25,0) would be read as “If A2>10, then 25; otherwise, 0.”例如,=IF(A2>10,25,0)将被解读为“如果A2>10,则为25;否则为0”

Figure 9.1 calculates a sales commission. 图9.1计算了销售佣金。The commission rate is 1.5 percent of revenue. 佣金率为收入的1.5%。However, if the gross profit percentage is 50% or higher, the commission rate is 2.5 percent of revenue.然而,如果毛利率为50%或更高,佣金率为收入的2.5%。

This image has Revenue in column F, Gross Profit Percent in column H and calculates a commission in column I. The formula bar shows that I2 contains the formula =IF(H2>=50%,0.025*F2,0.015*F2).
Figure 9.1 In rows 2, 4, and 5, the commission is 1.5%. 在第2行、第4行和第5行中,佣金为1.5%。In rows 3 and 6 through 9, the commission is 2.5%.在第3行和第6行至第9行中,佣金为2.5%。

Note

Mathematicians would correctly note that in both the second and third arguments of the formula =IF(H2>=50%,0.025*F2,0.015*F2), you are multiplying by F2. 数学家们会正确地注意到,在公式=IF(H2>=50%,0.025*F2,0.015*F2)的第二个和第三个参数中,您是在乘以F2。Therefore, you could simplify the formula by using =IF(H2>=50%,0.025,0.015)*F2.因此,您可以使用=IF(H2>=50%,0.025,0.015)*F2简化公式。

In this case, the logical test is H2>=50%. 在这种情况下,逻辑测试为H2>=50%The formula for whether that test is true is 0.025*F2. 该测试是否正确的公式为0.025*F2Otherwise, the formula is 0.015*F2. 否则,公式为0.015*F2You could build the formula as =IF(H2>=50%,0.025*F2,0.015*F2).您可以将公式构建为:=IF(H2>=50%,0.025*F2,0.015*F2)

Using the AND Function to Check for Two or More Conditions使用AND函数检查两种或更多情况

The previous example had one simple condition: If the value in column H was greater than or equal to 50%, the commission rate changed.上一个例子有一个简单的条件:如果H列中的值大于或等于50%,佣金率就会改变。

However, in many cases, you might need to test for two or more conditions. 然而,在许多情况下,您可能需要测试两个或更多条件。For example, suppose that a retail store manager offers a $25 bonus for every leather jacket sold on Fridays this month. 例如,假设一位零售店经理为本月周五售出的每件皮夹克提供25美元的奖金。In this case, the logical test requires you to determine whether both conditions are true. 在这种情况下,逻辑测试要求您确定这两个条件是否都为真。You can do this with the AND function.您可以使用AND函数来实现这一点。

Syntax:语法:
AND(logical1,logical2,...)

The arguments logical1,logical2,... are from one to 255 expressions that evaluate to either TRUE or FALSE. 参数logical1,logical2,...是从一到255个表达式,计算结果为TRUEFALSEThe function returns TRUE only if all arguments are TRUE.仅当所有参数均为TRUE时,该函数才返回TRUE

In Figure 9.2, the function in cell F2 checks whether cell E2 is a jacket and whether the date in cell D2 falls on a Friday:在图9.2中,单元格F2中的函数检查单元格E2是否为夹套,以及单元格D2中的日期是否为周五:

=AND(E2="Jacket",WEEKDAY(D2,2)=5)
An AND function checks to see if column E contains the word Jacket and if the date in column D falls on a Friday. The formula bar shows the formula to calculate if a bonus is paid as =AND(E2=”Jacket”,WEEKDAY(D2,2)=5. The results show either TRUE or FALSE.
Figure 9.2 The AND function is TRUE only when every condition is met.只有在满足所有条件时,AND函数才为TRUE

Using OR to Check Whether One or More Conditions Are Met使用OR检查是否满足一个或多个条件

In the earlier examples, all the conditions had to be met for the IF function to be true. 在前面的例子中,IF函数必须满足所有条件才能为真。In other cases, you might need to identify when exactly one condition is true, or when one or more conditions are true.在其他情况下,您可能需要确定一个条件何时为真,或者一个或多个条件何时为真。

For example, a sales manager may want to reward big orders and orders from new customers. 例如,销售经理可能想要奖励大订单和新客户的订单。The manager may offer a commission bonus if the order is more than $50,000 or if the customer is a new customer this year. 如果订单金额超过50000美元,或者客户是今年的新客户,经理可以提供佣金奖金。The bonus is awarded if either condition is true. 如果其中一个条件为真,则奖励。But only one bonus is paid; you do not give two bonuses if a customer is both new and the order is large. 但只支付了一笔奖金;如果客户都是新客户,而且订单很大,你不会给两个奖金。In this case, you would use the OR function with logical tests to check whether the customer is new or if the order is large.在这种情况下,您将使用OR函数和逻辑测试来检查客户是新客户还是订单大。

To test whether a particular sale meets either condition, use the OR function. 要测试特定销售是否满足任一条件,请使用OR函数。The OR function returns TRUE if any condition is TRUE and returns FALSE if none of the conditions are TRUE.如果任一条件为TRUEOR函数返回TRUE;如果没有条件均为TRUE,则返回FALSE

Syntax:语法:
OR(logical1,logical2,...)

The OR function checks whether any of the arguments are TRUE. OR函数检查任何参数是否为TRUEIt returns a FALSE only if all the arguments are FALSE. 只有当所有参数都为FALSE时,才会返回FALSEIf any argument is TRUE, the function returns TRUE.如果任何参数为TRUE,则函数返回TRUE

The arguments logical1,logical2,... are 1 to 255 conditions that can evaluate to TRUE or FALSE.参数logical1,logical2,...是1到255个条件,可以计算为TRUEFALSE

Nesting IF Functions Versus IFS SWITCH or CHOOSE嵌套IF函数与使用IFS SWITCHCHOOSE的对比

The IF function offers only two possible values: Either the logical test is TRUE, and the first formula or value is used, or the logical test is FALSE and the second formula or value is used.IF函数只提供两个可能的值:逻辑测试为TRUE,使用第一个公式或值,或者逻辑测试为FALSE,使用第二个公式或数值。

Many situations have a series of choices. For example, in a human resources department, annual merit raises might be given based on the employee’s numeric rating in an annual review in which employees are ranked on a five-point scale. 很多情况下都有一系列的选择。例如,在人力资源部门,年度绩效加薪可能基于员工在年度考核中的数字评分,员工在年度考核中按五分制进行排名。The rules for setting the raise are as follows:设定加薪的规则如下:

Traditionally, you would test for five conditions by nesting four IF functions:传统上,您会通过嵌套四个IF函数来测试五个条件:

=IF(D2=5,8%,IF(D2=4,7%,IF(D2=3,5%,IF(D2=2,3%,0%))))

You only needed four IF functions to test for five conditions. 您只需要四个IF函数就可以测试五个条件。After testing for the first four conditions, the fifth answer would be provided in the Value_If_False for the last IF function.在测试前四个条件后,第五个答案将在最后一个IF函数的Value_If_False中提供。

In February 2017, Office 365 customers were offered two alternatives:2017年2月,Office 365客户获得了两种选择:

=IFS(D2=5,8%,D2=4,7%,D2=3,5%,D2=2,3%,TRUE,0%)

=SWITCH(D2,5,8%,4,7%,3,5%,2,3%,0%)
Syntax:语法:
IFS(logical_test1, value_if_true1, [logical_test2, value_if_true2…])
Syntax:语法:
SWITCH(Expression, Value1, Result1,[Default_or_value2],[Result2]…)

In the IFS function, you can handle multiple conditions without nesting new functions. 在IFS函数中,您可以在不嵌套新函数的情况下处理多个条件。The IFS means that you have multiple IF conditions. IFS表示您有多个IF条件。The IFS formula above reads, “If D2 is 5, then return 8%. 上面的IFS公式是:“如果D2为5,则返回8%。Otherwise, if D2=4, then return 7%. 否则,如果D2=4,则返回7%。Otherwise, if D2=3, then return 5%. 否则,如果D2=3,则返回5%。Otherwise, if D2=2, then return 3%.” 否则,如果D2=2,则返回3%。”The last two arguments in IFS are a little bizarre. IFS中的最后两个论点有点奇怪。You essentially want to have a value to return if none of the previous conditions are true. 如果前面的条件都不为真,您基本上希望返回一个值。You need to put a logical test that is always True. 你需要做一个始终是TRUE的逻辑测试。Explicitly typing TRUE solves the problem.显式键入TRUE可以解决这个问题。

The SWITCH function is better, in this case, because you only specify cell D2 once. 在这种情况下,切换功能更好,因为您只指定单元格D2一次。You tell the SWITCH function that you want to return a value based on the value of D2. 您告诉开关函数,您希望返回一个基于D2值的值。If it is 5, then 8%. 如果是5,则为8%。If it is 4, then 7%. 如果为4,则为7%。If it is 3, then 5%. 如果为3,则为5%。If it is 2, then 3%. 如果为2,则为3%。For any other value, use 0%. 对于任何其他值,使用0%。Note that SWITCH does not require you to enter the TRUE argument as the second-to-last argument.请注意,SWITCH不要求您输入TRUE参数作为倒数第二个参数。

In this particular case, because the five possible scores are 1 through 5, the CHOOSE function will be shortest:在这种特殊情况下,由于五个可能的分数是1到5,所以选择函数将是最短的:

=CHOOSE(D2,0,3%,5%,7%,8%)

The CHOOSE function points to a single value and then expects the value to return if the answer is 1, 2, 3, 4, 5, and so on.CHOOSE函数指向单个值,然后如果答案为1、2、3、4、5等,则期望该值返回。

Note that Excel classifies CHOOSE as a Lookup and Reference function instead of a Logical function.请注意,Excel将“选择”分类为查找和引用函数,而不是逻辑函数。

Images Read more about CHOOSE in “Examples of Lookup and Reference Functions” on page 244.在第244页的“查找和引用函数示例”中了解更多关于选择的信息。

Figure 9.3 compares the four formulas. 图9.3比较了四个公式。In this case, CHOOSE is the shortest.在这种情况下,CHOOSE是最短的。

This image compares the four formulas discussed above: the nested IF is the longest formula at 51 characters. The new IFS formula is 45 characters. The SWITCH function is 34 characters. The CHOOSE function is 25 characters.
Figure 9.3 Four different ways to calculate the raise percentage.计算加薪百分比的四种不同方法。

Caution小心

These IF formulas are hard to read. 这些IF公式很难阅读。There is a temptation to use them for situations with very long lists of conditions. 在条件列表很长的情况下,很容易使用它们。Whereas Excel 2003 prevented you from nesting more than seven levels of IF functions, Excel 2007 and later allow you to nest up to 64 IF statements. Excel 2003不允许嵌套超过七个级别的IF函数,而Excel 2007和更高版本允许嵌套多达64个IF语句。Before you start nesting that many IF statements, you should consider using VLOOKUP, which is explained later in this chapter.在开始嵌套那么多IF语句之前,您应该考虑使用VLOOKUP,这将在本章后面进行解释。

CHOOSE will not always be the shortest formula. CHOOSE并不总是最短的公式。SWITCH will win if you have to look for values that are not sequential or don’t have to start with 1:如果您必须查找不连续或不必以1开头的值,则SWITCH将获胜:

=SWITCH(A2,30,"CURRY",35,"DURANT",23,"GREEN",11,"THOMPSON","OTHER")

IFS will be better if you need to look for ranges of values:如果需要查找值的范围,IFS会更好:

=IFS(A2>80,"Top Tier",A2>50,"Group 2",A2>20,"Group 3",TRUE,"Bottom Tier")

Nested IF will be better if there is any chance the workbook will be opened in Excel 2016, Excel 2013, Excel 2010, or an earlier version. 如果工作簿有可能在Excel 2016、Excel 2013、Excel 2010或更早版本中打开,则嵌套IF会更好。The new IFS and SWITCH functions will return #NAME? error if opened in a prior version of Excel.新的IFS和SWITCH函数将返回#NAME?在早期版本的Excel中打开时出错。

Using the NOT Function to Simplify the Use of AND and OR

In the language of Boolean logic, there are typically NAND, NOR, and XOR functions, which stand for Not And, Not Or, and Exclusive Or. To simplify matters, Excel offers the NOT function.

Syntax:语法:
NOT(logical)

Quite simply, NOT reverses a logical value. TRUE becomes FALSE, and FALSE becomes TRUE when processed through a NOT function.

For example, suppose you need to find all flights landing outside Oklahoma. You can build a massive OR statement to find every airport code in the United States. Alternatively, you can build an OR function to find Tulsa and Oklahoma City and then use a NOT function to reverse the result: =NOT(OR(A2="Tulsa",A2="Oklahoma City")).

Using the IFERROR or IFNA Function to Simplify Error Checking

The IFERROR function, which was introduced in Excel 2007, was added at the request of many customers. To better understand the IFERROR function, you need to understand how error checking was performed during the 22 years before Excel 2007 was released.

Consider a typical spreadsheet that calculates a ratio of sales to hours. A formula of =B2/C2 returns the #DIV/0 error in the records when column C contains a zero. The typical workaround is to test for the error condition: =IF(C2=0,0,B2/C2).

In legacy versions of Excel, it was typical to use this type of IF formula on thousands of rows of data. The formula is more complex and takes longer to calculate than the new IFERROR function. However, this particular formula is tame compared to some of the formulas needed to check for errors.

A common error occurs when you use the VLOOKUP function to retrieve a value from a lookup table. In Figure 9.4, the VLOOKUP function in cell D2 asks Excel to look for the rep number S07 from cell B2 and find the corresponding name in the lookup table of F2:G9. This works great, returning JESSE from the table. However, a problem arises when the sales rep is not found in the table. In row 7, rep S09 is new and has not yet been added to the table, so Excel returns the #N/A result.

This image shows a VLOOKUP formula to return a sales rep name based on a sales rep number. One of the results is returning an #N/A error because the sales rep number is not found.
Figure 9.4 An #N/A error means that the value is not in the lookup table.#N/A错误表示该值不在查找表中。

If you want to avoid #N/A errors, the generally accepted workaround in legacy versions of Excel was to write this horrible formula:

=IF(ISNA(VLOOKUP(B7,$F$2:$G$9,2,FALSE)),"New Rep", VLOOKUP(B7,$F$2:$G$9,2,FALSE))

In English, this formula says first to find the rep name in the lookup table. If the rep is not found and returns the #N/A error, then use some other text, which in this case is the words New Rep. If the rep is found, then perform the lookup again and use that result.

Because VLOOKUP was one of the most time-intensive functions, it was horrible to have Excel perform every VLOOKUP twice in this formula. In a data set with 50,000 records, it could take minutes for the VLOOKUP to complete. Microsoft wisely added the new IFERROR function in Excel 2010 to handle all these error-checking situations.

Starting in Excel 2013, Microsoft has added the IFNA function. It works just like the IFERROR function, but the second argument is used only when the first argument results in an #N/A error. You might be able to imagine a situation in which you want to replace the #N/A errors but allow other errors to appear.

Syntax:语法:
IFERROR(value,value_if_error)

The advantage of the IFERROR function is that the calculation is evaluated only once. If the calculation results in any type of an error value, such as #N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME?, or #NULL!, Excel returns the alternative value. If the calculation results in any other valid value, whether it is numeric, logical, or text, Excel returns the calculated value.

Syntax:语法:
IFNA(value,value_if_na)

If the expression evaluates to a value of #N/A, then IFNA returns value_if_na instead of the expression. Added in Excel 2013, this function replaces only #N/A errors and allows other errors to appear as the result.

The formula from the preceding section can be rewritten as =IFERROR(VLOOKUP(B7, $F$2:$G$9,2,FALSE),"New Rep") or as =IFNA(VLOOKUP(B7, $F$2:$G$9,2,FALSE),"New Rep"). Although IFNA is a bit shorter than IFERROR, the new IFNA function fails for anyone using Excel 2010 or earlier. This makes IFERROR a safer function to use for the next several years. Either IFERROR or IFNA calculates much more quickly than putting two VLOOKUPs in an IF function.

Examples of Information Functions信息功能示例

Found under the More Function icon, the 20 information functions return eclectic information about any cell. 在“更多功能”图标下,20个信息功能返回关于任何单元格的折衷信息。Eleven of the 20 functions are called the IS functions because they test for various conditions.20个函数中的11个被称为IS函数,因为它们测试各种条件。

Using the ISFORMULA Function with Conditional Formatting to Mark Formula Cells使用带有条件格式的ISFORMULA函数标记公式单元格

The Excel team introduced the ISFORMULA function in Excel 2013 to identify whether a cell contains a formula. Excel团队在Excel 2013中引入了ISFORMULA函数,以确定单元格是否包含公式。A hack had been floating around for years to mark formula cells using an old XL4 Macro Language function. 多年来,一个黑客一直在使用旧的XL4宏语言函数标记公式单元格。Being able to use ISFORMULA is a great improvement.能够使用ISFORMULA是一大进步。

Syntax:语法:
ISFORMULA(reference)

Checks whether reference contains a formula. Returns TRUE or FALSE.

Figure 9.5 shows a worksheet in which all the cells have a conditional formatting formula that uses =ISFORMULA. Any cells that contain a formula are shown in white text on black fill.

In this image, the =ISFORMULA(A1) formula is used as the Conditional Formatting formula. The result is that any cells that contain a formula are highlighted in another color.
Figure 9.5 Use the ISFORMULA function with conditional formatting to mark all the formula cells.使用带条件格式的ISFORMULA函数标记所有公式单元格。

Using IS Functions to Test for Types of Values使用IS函数测试值的类型

The remaining IS functions enable you to test whether a cell contains numbers, text, or various other data types.剩下的IS函数允许您测试单元格是否包含数字、文本或各种其他数据类型。

Figure 9.6 shows a common solution. Column C contains a mix of text and numeric ZIP Codes. The formula in column D, =IF(ISNONTEXT(C5),RIGHT("0000"&C5,5),C5), replaces numeric ZIP Codes with text ZIP Codes. If the value in column C is nontext, the program pads the left side of the ZIP Code with zeros and then takes the five rightmost digits.

A series of Zip Codes appear in column C. The zip code for Portland Maine is shown as 4123 instead of 04123. A Zip Fixed column uses the formula =IF(ISNONTEXT(C2),RIGHT(“0000”&C5,5),C5).
Figure 9.6 The formula in column D detects nontext ZIP Codes and converts to text with five digits.D列中的公式检测非文本邮政编码,并将其转换为五位数的文本。

Using the N Function to Add a Comment to a Formula使用N函数向公式添加注释

You can call Excel’s N function a creative use for an obsolete function. Lotus 1-2-3 used to offer an N() function that converted True to 1 and False to 0. The N of any text is zero. Some have figured they could use this function to add a comment to a formula:

=VLOOKUP(A2,MyTable,2,False)+N("The False ensures an exact match. Don't omit False")

Using the NA Function to Force Charts to Not Plot Missing Data使用NA函数强制图表不绘制缺失数据

Suppose that you are in charge of a school’s annual fund drive. 假设你负责一所学校的年度基金活动。Each day, you mark the fundraising total on a worksheet by following these steps:每天,您通过以下步骤在工作表上标记筹款总额:

  1. In column A, you enter the results of each day’s collection through nine days of the fund drive (see Figure 9.7).在A列中,您输入基金驱动的九天内每天收集的结果(见图9.7)。

    This image contrasts two charts with a trendline. The charts will eventually show sales for 14 days, but only 9 days of data are entered. In the chart on the left, data for days 10 through 14 is blank. The line chart drops to zero. The automatic trendline slopes downwards because of all the zero values in days 10 through 14. In contrast, the chart on the right replaces the empty cells with NA() functions. The #N/A are not plotted on the chart, and the trendline correctly slopes up, predicting higher accumulated sales for days 10 through 14.
    Figure 9.7 Using NA in the chart on the right allows the trendline to ignore future missing data points and project a reasonable ending result.在右边的图表中使用NA可以让趋势线忽略未来缺失的数据点,并预测合理的最终结果。
  2. You enter a formula in column C to keep track of the total collected throughout the fund drive.在C列中输入一个公式,以跟踪整个基金活动中收集的总金额。

  3. To avoid making it look like the fund drive collected nothing in days 10 through 14, you enter a formula in column C to check whether column A is blank. 为了避免让它看起来像是基金驱动器在第10天到第14天没有收集到任何东西,您可以在C列中输入一个公式,以检查a列是否为空。If it is, then the IF function inserts a null cell in column C. For example, the formula in cell C15 is =IF(ISBLANK(A15),"",A15+C14).如果是,则IF函数在C列中插入一个空单元格。例如,单元格C15中的公式为=IF(ISBLANK(A15),"",A15+C14)

  4. You build a line chart based on B1:C15. 您将基于B1:C15构建一个折线图。You then add a trendline to the chart to predict future fundraising totals.然后在图表中添加趋势线,以预测未来的筹资总额。

  5. As shown in columns A:C of Figure 9.7, this technique fails. Even though the totals for days 10 through 14 are blank, Excel charts those days as zero. The linear trendline predicts that your fundraising will go down, with a projected total of just over $2,000.

  6. You try the same chart again, but this time you use the NA function instead of "" in the IF statement in step 3. The formula is shown in cell H16, and the results are in cell J15. Excel understands that NA values should not be plotted. The trendline is calculated based on only the data points available and projects a total just under $18,000.

In many cases, you are trying to avoid #N/A! errors. However, in the case of charting a calculated column, you might want to have #N/A! produce the correct look to the chart.

Using the CELL Function to Return the Worksheet Name使用CELL函数返回工作表名称

The CELL function can tell you information about a specific cell. Although the function can return many ancient bits of information (Excel 2003 color index, for example), it has one argument that allows you to put the worksheet name in a cell.

=CELL("filename",A1) returns the complete path, filename, and worksheet name. The technique is to locate the right square bracket at the end of the filename. Everything after that character is the worksheet tab name.

Figure 9.8 shows an example.

This image builds a rather complex formula to return the worksheet tab name to a cell. The inner part of the formula =CELL(“filename”,$A$1) returns the file path, then the workbook name in square brackets, then the sheet name. By locating the right square bracket using FIND, you can isolate the worksheet name with MID.
Figure 9.8 The CELL function returns the full path, filename, and tab name to a cell.CELL函数返回单元格的完整路径、文件名和选项卡名。

Examples of Lookup and Reference Functions查找和引用函数的示例

The Lookup & Reference icon contains 18 functions. 查找和参考图标包含18个函数。The all-star of this group is the venerable VLOOKUP function, which is one of the most powerful and most used functions in Excel. 该组的全明星是令人尊敬的VLOOKUP函数,它是Excel中功能最强大、使用最多的函数之一。As database people point out, a lot of work done in Excel should probably be done in Access. 正如数据库人员指出的那样,在Excel中完成的许多工作可能都应该在Access中完成。The VLOOKUP function enables you to perform the equivalent of a join operation in a database.VLOOKUP函数使您能够在数据库中执行相当于连接操作的操作。

This lookup and reference group also includes several functions that seem useless when considered alone. 这个查找和参考组还包括几个单独考虑时似乎无用的功能。However, when combined, they allow for some very powerful manipulations of data. 然而,当它们结合在一起时,它们允许对数据进行一些非常强大的操作。The examples in the following sections reveal details on how to use the lookup functions and how to combine them to create powerful results.以下各节中的示例详细介绍了如何使用查找函数,以及如何组合它们以创建强大的结果。

Using the CHOOSE Function for Simple Lookups使用CHOOSE函数进行简单查找

Most lookup functions require you to set up a lookup table in a range on the worksheet. 大多数查找功能要求您在工作表的某个范围内设置查找表。However, the CHOOSE function enables you to specify up to 254 choices right in the syntax of the function. 但是,CHOOSE函数允许您在函数语法中最多指定254个选项。The formula that requires the lookup should be able to calculate an integer from 1 to 254 to use the CHOOSE function.需要查找的公式应该能够计算1到254之间的整数,以使用CHOOSE函数。

Syntax:语法:
CHOOSE(index_num,value1,value2,...)

The CHOOSE function chooses a value from a list of values, based on an index number. The CHOOSE function takes the following arguments:

The example in Figure 9.9 shows survey data from some respondents. Columns B:F indicate their responses on five measures of your service. Column G calculates an average that ranges from 1 to 5. Suppose that you want to add words to column H to characterize the overall rating from the respondent. The following formula is used in cell H4:

=CHOOSE(G4,"Strongly Disagree","Disagree","Neutral","Agree","Strongly Agree")
The CHOOSE function mentioned above is shown in this figure. Note that the formula for the average score is returning non-integers, such as 4.8 and 2.4. The results of the formula show that 4.8 returns the value associated with 4. This indicates Excel truncates any decimals from the index number.
Figure 9.9 CHOOSE is great for simple choices in which the index number is between 1 and 254.CHOOSE适用于索引号介于1和254之间的简单选择。

Using VLOOKUP with TRUE to Find a Value Based on a Range使用带TRUEVLOOKUP查找基于范围的值

VLOOKUP stands for vertical lookup. This function behaves differently, depending on the fourth parameter. This section describes using VLOOKUP in which you need to choose a value based on a table that contains ranges.

Suppose that you have a list of students and their scores on a test. 假设你有一份学生名单和他们的考试成绩。The school grading scale is based on these ranges:学校评分标准基于以下范围:

Follow these steps to set up a VLOOKUP for this scenario:

  1. Because in this version of VLOOKUP you do not have to list every possible grade, build a table showing the scores where the grading scale changes from one grade to the next.

  2. Although the published grading scale starts with the higher values, your lookup table must be sorted in ascending sequence. This requires a bit of translation as you set up the table. Although the grading scale says that below 65 is an F, you need to set up the table to show that an F corresponds to any grade at 0 or higher. Therefore, in cell E2 enter 0, and in cell F2, enter F (see Figure 9.10).

    A lookup table in E2:F6 lists values 0, 65, 70, 85, and 92 and the letter grade associated with each. A formula of =VLOOKUP(B2,$@$2:$F$6,2,TRUE) returns the proper letter grade. Note that the lookup table is sorted low to high because you are using TRUE as the fourth argument.
    Figure 9.10 The VLOOKUP formula in column C finds the correct grade from the table in columns E and F.C列的VLOOKUP公式从E列和F列的表格中找到正确的等级。
  3. Continue building the grading scale in successive rows of columns E and F. 继续在E列和F列的连续行中构建放坡比例。Anything above a 65 is given a D. 任何高于65分的成绩都被评为D。Anything above 70 is given a C. 任何高于70的都会被打C。Note that this is somewhat counterintuitive because it is the opposite order that you would use if you were building a grading scale using nested IF functions.请注意,这有点违反直觉,因为如果使用嵌套的IF函数构建放坡比例,则会使用相反的顺序。

  4. Ensure that the numeric values are the leftmost column in your lookup table. 确保数值是查找表中最左边的列。In Figure 9.10, the lookup table range is E2:F6. When you use VLOOKUP, Excel searches the first column of the lookup table for the appropriate score.

  5. When using this version of VLOOKUP with ranges, sort the list in ascending order. If you are not sure of the proper order, use the Sort command from the Home tab to sort the table.

  6. Because the first argument in the VLOOKUP function is the student’s score, in cell C2, enter =VLOOKUP(B2,.

  7. Because the next argument is the range of the lookup table, be sure to press the F4 key after entering E2:F6 to change to an absolute reference of $E$2:$F$6.

  8. Ensure that the third argument specifies which column of the lookup table should be returned. Because the letter grade is in the second column of E2:F6, use 2 for the third argument.

  9. Ensure that the final argument is either TRUE or simply omitted. This tells Excel that you are using the sorted range variety of lookup.

  10. After you enter the formula in cell C2, again select cell C2 and double-click the fill handle to copy the formula down to all students.

Using VLOOKUP with FALSE to Find an Exact Value

In some situations, you do not want VLOOKUP to return a value based on a close match. Instead, you want Excel to find the exact match in the lookup table.

Figure 9.11 shows a table of sales. The original table had columns A through C: Rep, Date, and Sale Amount. Although a data analyst might have all the rep numbers memorized, the manager who is going to see the report prefers to have the rep names on the report.

A lookup table in F2:G7 gives the sales rep name for various sales rep numbers. This table is not sorted. The formula =VLOOKUP(A2,$F$2:$G$7,2,FALSE) returns the sales rep name given a sales rep number.
Figure 9.11 In this case, VLOOKUP needs to find the exact rep number from the table in columns E and F.在这种情况下,VLOOKUP需要从E列和F列的表中找到确切的代表编号。

To fill in the rep names from a lookup table, you follow these steps:要从查找表中填写代表姓名,请执行以下步骤:

  1. In columns F and G, enter a table of rep numbers and rep names. 在F列和G列中,输入代表编号和代表姓名表。Note that it is not important for this table to be sorted by the rep number field. 请注意,此表按rep number字段排序并不重要。It is fine that the table is sorted alphabetically by name.表格按名称的字母顺序排列是可以的。

  2. Use FALSE as the fourth parameter in VLOOKUP. You need to do this because close matches are not acceptable here. If something was sold by a new rep with number R9, you do not want to give credit to the name associated with R8 just because it is a close match. Either Excel finds an exact match and returns the result, or Excel does not give you a result.Excel会找到精确匹配并返回结果,或者Excel不会给出结果。

  3. For cell D2, you want Excel to use the rep number in A2, so in cell D2, enter =VLOOKUP(A2,.

  4. The lookup table is in F2:G7, so enter F2:G7 and then press the F4 key to make the reference absolute. This enables you to copy the formula in step 7. After pressing F4, type a comma.

  5. In the lookup table, the rep name is in column 2 of the table, so type 2 to specify that you want to return the second column of the lookup table.

  6. Finish the function with FALSE). Press Ctrl+Enter to accept the formula and keep the cursor in cell D2.

  7. Double-click the fill handle to copy the formula down to all the rows.

  8. VLOOKUP is a very time-intensive calculation. Having thousands of VLOOKUP formulas significantly affects your recalculation times. In this particular case, you have successfully added rep names. It would be appropriate to convert these live formulas to their current values. Therefore, press Ctrl+C to copy. Then, from the Home tab, select Paste, Paste Values to convert the formulas to values.

    Note

    If your lookup table is arranged sideways, with going across a row, you should use HLOOKUP. If your data is vertical, but the key field is not the leftmost column, you can use a combination of INDEX and MATCH, also explained later in this chapter.

  9. Look through the results. 查看结果。If a sale was credited to a new rep who is not in the table, the name appears as #N/A. Manually fix these records, if needed.

To recap, the two versions of the VLOOKUP formula behave very differently. VLOOKUP with FALSE as the fourth parameter looks for an exact match, whereas VLOOKUP with TRUE as the fourth parameter looks for the closest (lower) match. In the TRUE version, the lookup table must be sorted. In the FALSE version, the table can be in any sequence. In every case, the key field must be in the left column of the lookup table.

Syntax:语法:
VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)

VLOOKUP searches for a value in the leftmost column of a table and then returns a value in the same row from a column you specify in the table. The VLOOKUP function takes the following arguments:

Using VLOOKUP to Match Two Lists

If Excel is used throughout your company, you undoubtedly have many lists in Excel. People use Excel to track everything. How many times are you faced with a situation in which you have two versions of a list and you need to match them up?

In Figure 9.12, the worksheet has two simple lists. Column A shows last week’s version of who was coming to an event. Column C shows this week’s version of who is coming to an event. Follow these steps if you want to find out quickly if anyone is new:

  1. Add the heading There? to cell D2.

  2. Because the formula in cell D3 should look at the value in cell C3 to see whether that person is in the original list in column A, start the formula with =VLOOKUP(C3,$A$3:$A$15,.

  3. Because your only choice for the column number is to return the first column from the original list, finish the function with 1,FALSE). Then press Ctrl+Enter to accept the formula and stay in cell D3.

  4. Double-click the fill handle to copy the formula down to all rows.

    This figure shows two versions of a list of names. A3:A15 contains last week’s list. C3:C18 contains this week’s list. A column labeled “There?” in D uses the formula =VLOOKUP(C3,$A$3:A$A15,1,False). If the name appears in column D, then the person in column C was in the old list. However, if the formula returns #N/A, then you know that this person is new to the list.
    Figure 9.12 An #N/A error as the result of VLOOKUP tells you that the person is new to the list.VLOOKUP的结果是一个#N/A错误,它告诉你这个人是列表中的新成员。

For any cells in which column D contains a name, it means that the person was on the RSVP list from last week. 对于D列包含姓名的任何单元格,这意味着此人从上周起就在RSVP列表中。If the result of the VLOOKUP is #N/A, you know that this person is new since the previous week.

Tip

If you study the data in Figure 9.12, you see that three more names are in the column C list than in the column A list, yet four people were reported as being new this week. This means that one of the people from last week has dropped off the list. To quickly find who dropped off the list, use the formula =VLOOKUP(A3,$C$3:$C$18,1,FALSE) in B3:B15 to find that Donald Tyler has dropped off the list.

Note that you can also use MATCH to solve this problem.请注意,您也可以使用MATCH来解决此问题。

Using the MATCH Function to Locate the Position of a Matching Value使用MATCH函数定位匹配值的位置

At first glance, MATCH seems like a function that would rarely be useful. MATCH returns the relative position of an item in a range that matches a specified value in a specified order. You 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.

Suppose that your manager asks, “Can you tell me on which row I would find this value?” The manager wants to know the value or some piece of data on that record. However, rarely would the manager want to know that XYZ is found on the 111th relative row within the range A99:A11432.

MATCH comes in handy in several instances. In the first instance, consider a situation in which you are using VLOOKUP to find whether an item is in a list. In this case, you do not care what value is returned. You are interested in seeing either whether a valid value is returned, meaning that the entry is in the old list, or whether an #N/A is returned, meaning that the entry is new. In this case, using MATCH is a slightly faster way to achieve the same result.

Another handy way to use MATCH is with the INDEX function. MATCH has two features that make it more versatile than VLOOKUP. MATCH allows for wildcard matches. MATCH also allows for a search based on an exact match, based on the number just below the value, or based on a value greater than or equal to the lookup value. This third option is not available in the VLOOKUP or HLOOKUP functions.

Syntax:语法:
MATCH(lookup_value,lookup_array,match_type)

The MATCH function returns the relative position of an item in a column or row of values. It is useful for determining if a certain value exists in a list.

The MATCH function takes the following arguments:MATCH函数采用以下参数:

MATCH returns the position of the matched value within lookup_array, not the value itself. For example, MATCH("b",{"a","b","c"},0) returns 2, the relative position of b within the array {"a","b","c"}.

MATCH does not distinguish between uppercase and lowercase letters when matching text values. If MATCH is unsuccessful in finding a match, it returns an #N/A error.

If match_type is 0 and lookup_value is text, lookup_value can contain the wildcard characters asterisk (*) and question mark (?). An asterisk matches any sequence of characters; a question mark matches any single character.

Using MATCH to Compare Two Lists

You might face situations in which you have two versions of a list, and you need to match them up.

In Figure 9.13, the worksheet has two simple lists. Column A shows last week’s list. Column C shows this week’s version of the list. You want to find out quickly which items are new. Here’s how you do it:

  1. Add the heading There? to cell D2.

  2. Because the formula in cell D3 looks at the value in cell C3 to see if that value is in the original list in column A, start the formula with =MATCH(C3,$A$3:$A$11,.

  3. Because you want an exact match, use 0 as the third parameter. Finish the function with a ). Press Ctrl+Enter to accept the formula and stay in cell C3.

  4. Double-click the fill handle to copy the formula down to all rows.

    Similar to Figure 9.12, this worksheet shows two lists. Rather than use VLOOKUP for the “There?” column, a formula of =MATCH(C3,$A$3:$A$11,0) is used. In these results, a positive integer means the item is found in the original list. A #N/A means the item is newly added.
    Figure 9.13 MATCH operates slightly more quickly than VLOOKUP and achieves the same result in this special case in which you are trying to figure out whether a value is in another list.MATCH的运行速度比VLOOKUP略快,在这个特殊情况下,您试图确定某个值是否在另一个列表中,MATCH也会获得相同的结果。

For any cells in which column D contains a number, it means that the entry was on the original list from last week. 对于D列包含数字的任何单元格,这意味着该条目位于上周的原始列表中。If the result of MATCH is #N/A, you know that this item is new since the previous week.

Using INDEX and MATCH for a Left Lookup

INDEX is another function that does not immediately seem to have many great uses. In its basic form, INDEX returns the value from a particular row and column of a rectangular range. It returns a value from a particular position of a vertical or horizontal vector.它从垂直或水平向量的特定位置返回值。

Typically, you specify a rectangular range and then indicate the row number and column number of the value that you want to return. 通常,指定一个矩形范围,然后指示要返回的值的行号和列号。In Figure 9.14, the formula in C3 returns the third row and second column of B5:D9. Certainly, this is a needlessly complicated way to point to cell C7.

Three uses of INDEX are shown in this figure. Given a row of 3 in C1 and a column of 2 in C2, =INDEX(B5:D9,C1,C2) will return the answer found in the 3rd row and 2nd column of B5:D9. The second example chooses a random name from a list of names in M1:M7: =INDEX(M1:M7,RANDBETWEEN(1,7)). The third example is a horizontal list of month names and values for each month in A14:L14. =INDEX(A14:L14,MONTH(TODAY())) will return the value for the current month.
Figure 9.14 INDEX can be used in a variety of situations without the MATCH function.INDEX可以在没有MATCH函数的情况下用于各种情况。

INDEX becomes interesting when you have a formula calculating the position argument. 当你有一个计算位置参数的公式时,INDEX就变得有趣了。Still in Figure 9.14, a list of people is in M1:M7. You can randomly select from the list by using INDEX and RANDBETWEEN(1,7), as shown in C4.

If you specify zero as the row or column argument, INDEX returns the entire row or column. The INDEX in H8 is returning all three values from row 4 of the table, so you have to wrap the index function in a SUM or COUNT or AVERAGE function.

The data in row 14 illustrates an undocumented feature of INDEX. When the reference contains data in a single row, you can specify the column number as the second argument. To get the data for September, you can use the correct =INDEX(A14:L14,0,9) or the shortened =INDEX(A14:L14,9). In Figure 9.14, the formula in C11 returns the value from the current month by using =MONTH(TODAY()) to return a 9 as the second argument of the INDEX function. (This was written in September, hence the 9.0.)

You’ve reached Excel guru status when you start combining INDEX and MATCH. On its own, neither INDEX nor MATCH seems particularly useful. Used together, though, they become a powerful combination that is more flexible than VLOOKUP and often faster to calculate than VLOOKUP.

In Figure 9.15, a customer number is in cell B1. The customer lookup table appears in columns F, G, and H. The main problem is that the customer table does not have the customer number on the left side.主要问题是customer表的左侧没有customer编号。

This image shows a lookup table where the key field is to the right of the text fields. The customer number is in H, while Name is in F and Address is in G. Formulas described below will use MATCH inside of INDEX to return the name and address for a customer.
Figure 9.15 This combination of INDEX and MATCH enables you to look up data that is to the left of a key field.INDEXMATCH的组合使您能够查找键字段左侧的数据。

In many cases, you would copy column H to column E and use column E as the key of the table. However, the table in F:H is likely to be repopulated every day from a web query or an OLAP query. Therefore, it might become monotonous to move the data after every refresh. The solution is to use a combination of INDEX and MATCH. Here’s what you do:

  1. Use the formula =MATCH(B1,H2:H89,0) to search through column H to find the row with the customer number that matches the one in cell B1. In this case, C499 is in row 9, which is the eighth row of the table.

  2. Be sure to use exactly the same shape range as the first argument in the INDEX function: =INDEX(F2:F89,WhichRow,WhichColumn) searches through the customer names in column F.

  3. For the second parameter of the INDEX function, specify the relative row number. This information was provided by the MATCH function in step 1.

  4. Ensure that the third parameter of the INDEX function is the relative column number. Because the range F2:F89 has only one column, this is either 1 or can simply be omitted.

  5. Putting the formula together, the formula in cell B2 is =INDEX(F2:F89,MATCH(B1,H2:H89,0),1).

Syntax:语法:
INDEX(array,row_num,[column_num])
INDEX(reference,row_num,[column_num],[area_num])

The INDEX function returns the value at the intersection of a particular row and column within a range. This function takes the following arguments:

If both the row_num and the column_num arguments are used, INDEX returns the value in the cell at the intersection of row_num and column_num.

If you set row_num or column_num to 0, INDEX returns the array of values for the entire column or row, respectively. To use values returned as an array, you use the INDEX function as an array formula in a horizontal range of cells for a row and in a vertical range of cells for a column. To enter an array formula, you press Ctrl+Shift+Enter. Thanks to modern arrays introduced in September 2018, customers using Office 365 will not need to press Ctrl+Shift+Enter.

row_num and column_num must point to a cell within array; otherwise, INDEX returns a #REF! error.

Using MATCH and INDEX to Fill a Wide Table

The lookup functions VLOOKUP, HLOOKUP, and MATCH can be very processor intensive when the lookup table contains hundreds of thousands of rows. The problem is worse when you have to return multiple columns from the same row of the lookup table. If it takes Excel 3 seconds to find the matching row for column 2 of the table, it will take another 3 seconds to find the matching row for column 3 of the table. If you hope to return 12 monthly columns, it could take 36 seconds.

Instead, you could find the matching row once using a MATCH function in a helper column. After the MATCH identifies the correct row, 12 INDEX functions can return the values for each month. INDEX is incredibly fast. The 13 formulas will run in 12% of the time it takes to run 12 VLOOKUP formulas.

Figure 9.16 illustrates the technique. A MATCH function in column C figures out which row contains the match. INDEX functions in D5:O12 return the monthly numbers.

In this figure, you have to look up inventory in 12 warehouses for each item number. Rather than use 12 columns of VLOOKUP, the worksheet uses a single column of MATCH in column C to tell Excel where the item number is found in the lookup table. Given the row number information in the Match column, you can use INDEX to return the information from the correct warehouse quickly. Item numbers are in B5:B12. The lookup table is in A17:M14056. The Match column uses =MATCH(B5,$A$17:$A$14056,0) to find the row number. The inventory values for Warehouse1 in column D use =INDEX(B$17:B$14056,$C5). Note the single dollar sign before 17, 14056, and C in that formula. Those mixed references allow the formula to be copied across to all 12 warehouses.
Figure 9.16 This performs eight relatively slow MATCH functions and then 96 relatively fast INDEX functions.它执行八个相对较慢的MATCH函数,然后执行96个相对较快的INDEX函数。

Performing Many Lookups with LOOKUP使用LOOKUP执行许多查找

Even Excel Help tells you to avoid the old LOOKUP function. However, LOOKUP can do one useful trick that VLOOKUP and HLOOKUP cannot do—it can process many lookups in one single array formula. LOOKUP can also deal with a lookup range that is vertical and a return range that is horizontal, or vice versa.

One additional superpower of the old LOOKUP function is the capability to look up several values at once. You have to use Ctrl+Shift+Enter to accept the formula, and because LOOKUP will be returning an array of answers, you should enclose the LOOKUP in a wrapper function such as SUM to add all the results from the function.

In Figure 9.17, a series of invoices appear in rows 4 through 17. A GP% (gross profit percentage) is associated with each invoice. The sales rep will earn a bonus depending on the GP% of each invoice, as shown in E6:F10. Instead of calculating a bonus for each row, you can calculate a bonus for all the rows at once. The formula in B1 of Figure 9.17 specifies an array of B4:B17 as the lookup value. This causes Excel to perform the LOOKUP 14 times, once for each value in the range B4:B17. The formula wraps the LOOKUP results in a SUM function to add up all the bonus results. To calculate correctly, you must hold down Ctrl+Shift while pressing Enter after typing this formula. When you press Ctrl+Shift+Enter, Excel adds the curly braces around the formula. You do not type the curly braces manually. Typing the curly braces will not work.

An array formula of =SUM(LOOKUP(B4:B17,E6:F10)) performs a LOOKUP for each of the values in B4:B17 and then sums the result.
Figure 9.17 Unlike VLOOKUP and HLOOKUP, the aging LOOKUP function can process many lookups in a single array formula.VLOOKUPHLOOKUP不同,老迈的LOOKUP函数可以在单个数组公式中处理许多查找。

As of late 2018, any Office 365 customers will have access to modern arrays. This is a major change to how Excel calculates. You will no longer have to use Ctrl+Shift+Enter in the example above. Also, with the introduction of modern arrays, every Excel function can accept an array, so you can use =SUM(VLOOKUP(B4:B17,E6:F10,2,False)), and it will calculate correctly. Modern arrays are not in Excel 2019, so those customers will still have to use LOOKUP and Ctrl+Shift+Enter.现代数组不在Excel 2019中,因此这些客户仍然必须使用LOOKUPCtrl+Shift+Enter

Using FORMULATEXT to Document a Worksheet

Quiz: Which Excel function is used the most in this book? It is FORMULATEXT. The FORMULATEXT function was added in Excel 2013. If you ask for the =FORMULATEXT(A1), Excel shows the formula that is in cell A1 as text. All the formulas shown in this book (such as cell C1 in Figure 9.17) are generated with the FORMULATEXT function.

You can use FORMULATEXT to document the formulas used in your worksheet. Normally, you can either print your worksheet with formulas showing or with the results from the formulas. By using FORMULATEXT, you can show both the formula and the result.

If you use FORMULATEXT on a cell with an array formula, the resulting text will be wrapped in curly braces that would be shown in the formula bar.

In Figure 9.18, the text of the formula shown in C3 comes from a FORMULATEXT function.

This image shows the result of a formula in B3. Next to this cell, the formula used to calculate B3 is shown in cell C3. This is achieved with the =FORMULATEXT(B3) function in cell C3.
Figure 9.18 A FORMULATEXT function in C3 shows the formula used in B3.C3中的FORMULATEXT函数显示了B3中使用的公式。
Syntax:语法:
FORMULATEXT(reference)

This function returns a formula as text.此函数以文本形式返回公式。

Troubleshooting故障排除

FORMULATEXT fails when your reference does not contain a formula.当引用不包含公式时,FORMULATEXT失败。

There are people who had written their own versions of FormulaText as a VBA function before Excel 2013 added FormulaText. The version that was made popular on the Internet would return the formula as text if the cell contained a formula. Otherwise, it would return the value in the cell.

However, Excel’s built-in version of FORMULATEXT returns a #N/A error if the cell does not contain a formula.

One workaround is to wrap FORMULATEXT in IFNA. Instead of =FORMULATEXT(C2), use =IFNA(FORMULATEXT(C2),C2).

In this figure, two cells show an answer of 4. Next to each cell, a FORMULATEXT function attempts to show the formula in the adjacent cell. This works for the first cell, where the formula is =2+2. However, in the second cell, the FORMULATEXT returns a #N/A error because the cell simply contains the number 4 instead of a formula. A workaround of =IFNA(FORMULATEXT(B2),B2) will work for either formulas or values.

Two cells show an answer of 4. Next to each cell, a FORMULATEXT function attempts to show the formula in the adjacent cell. This works for the first cell, where the formula is =2+2. However, in the second cell, the FORMULATEXT returns a #N/A error because the cell simply contains the number 4 instead of a formula. A workaround of =IFNA(FORMULATEXT(B2),B2) will work for either formulas or values.

Using Numbers with OFFSET to Describe a Range

The language of Excel is numbers. There are functions that count the number of entries in a range. There are functions that can tell you the numeric position of a looked-up value. You might know that a particular value is found in row 20, but what if you want to perform calculations on other cells in row 20?

The OFFSET function handles this very situation. You can use OFFSET to describe a range using mostly numbers. OFFSET is flexible: It can describe a single cell, or it can describe a rectangular range.

Although INDEX can return a single cell, row, or column from a rectangular range, it has limitations. If you specify C5:Z99 as the range for an INDEX function, you can select only cells below and/or to the right of C5. The OFFSET function can move up and down or left and right from the starting cell, which is C5.

Syntax:语法:
OFFSET(reference,rows,cols,height,width)

The OFFSET function returns a reference to a range that is a given number of rows and columns from a given reference. This function takes the following arguments:

OFFSET enables you to specify a reference. It does not move a cell. 它不会移动细胞。It does not change the selection. 它不会更改选择。It is just a numeric way to describe a reference. 这只是一种描述引用的数字方式。OFFSET can be used in any function that is expecting a reference argument.OFFSET可用于任何需要引用参数的函数。

Excel Help provides a trivial example of =SUM(OFFSET(C2,1,2,3,1)), which sums E3:E5. However, this example is silly because no one would ever write such a formula! If you were to write such a formula, you would just write =SUM(E3:E5) instead. The power of OFFSET comes when at least one of the four numeric arguments is calculated by the COUNT function or a lookup function.

In Figure 9.20, you can use COUNT(A5:A99) to count how many entries are in column A. If you assume that there are no blanks in the range of data, you can use the COUNT result as the height argument in OFFSET to describe the range of numbers. Here’s what you do:

  1. There is nothing magical about the reference, so write it as =OFFSET(A5,.

  2. Do not move the starting position any rows or columns from cell A5. The starting position is A5, so you always use 0 and 0 for rows and columns. Therefore, the formula is now =OFFSET(A5,0,0,.

  3. If you want to include only the number of entries in the list, use COUNT(A5:A999) as the height of the range. The formula is now =OFFSET(A5,0,0,COUNT(A5:A999),.

  4. The width is one column, so make the function =OFFSET(A5,0,0,COUNT(A5:A999),1).

  5. Use your OFFSET function anywhere you would normally specify a reference. You can use =SUM(OFFSET(A5,0,0,COUNT(A5:A999),1)) or specify that formula as the series in a chart. This creates a dynamic chart that grows or shrinks as the number of entries changes.

    This figure shows several columns of numbers. Each column has numbers starting in row 5 that extend for a different number of rows. You can count how many items are in each list with COUNT(A5:A999). To Sum the items in the list, use =SUM(OFFSET(A5,0,0,COUNT(A5:A999),1)).
    Figure 9.20 Every argument except height is hard-coded in these functions. 在这些函数中,除height外的所有参数都是硬编码的。The height argument comes from a COUNT function to allow the range to expand as more entries are added.height参数来自一个COUNT函数,允许范围随着更多条目的添加而扩展。

    Troubleshooting故障排除

    OFFSET is a volatile function and will slow recalculation of your worksheet. 偏移量是一个不稳定的函数,会减慢工作表的重新计算。Avoid OFFSET using a little-known version of INDEX.避免使用鲜为人知的索引版本进行偏移。

    Normally, =INDEX(A1:A10,5) will return the value stored in the fifth row of A1:A12. Excel guru Dan Mayoh discovered an alternate use for INDEX. If the INDEX function is placed adjacent to a colon, the INDEX function returns the cell address instead of the value stored in the cell. =SUM(A1:INDEX(A1:A12,5)) will sum A1:A5.

    Of course, you would not hard-code the 5 in the INDEX function. You might use MONTH(TODAY()) to dynamically choose the number corresponding to the current month.

    =SUM(A1:INDEX(A1:A12,MONTH(TODAY()))) is not volatile and does the same thing as =SUM(OFFSET(A1,0,0,MONTH(TODAY()),1)).

Using INDIRECT to Build and Evaluate Cell References on the Fly

The INDIRECT function is deceivingly powerful. Consider this trivial example: In cell A1, enter the text B2. In cell B2, enter a number. In cell C3, enter the formula =INDIRECT(A1). Excel returns the number that you entered in cell B2 in cell C3. The INDIRECT function looks in cell A1 and expects to find something that is a valid cell or range reference. It then looks in that address to return the answer for the function.

The reference text can be any text that you can string together using various text functions. This enables you to create complex references that dynamically point to other sheets or to other open workbooks.

The reference text can also be a range name. You could have a validation list box in which someone selects a value from a list. If you have predefined a named range that corresponds to each possible entry on the list, INDIRECT can point to the various named ranges on the fly.

When you use traditional formulas, even absolute formulas, there is a chance that someone might insert rows or columns that will move the reference. If you need a formula to always point to cell J10, no matter how someone rearranges the worksheet, you can use =INDIRECT("J10") to handle this.

Syntax:语法:
INDIRECT(ref_text,a1)

The INDIRECT function returns the reference specified by a text string. This function takes the following arguments:

Figure 9.21 is a monthly worksheet in a workbook that has 12 similar sheets. In each worksheet, the data headings are in row 6, and the total for the worksheet appears in cell D2. To build a summary sheet that points to D2 on the individual worksheets, you can concatenate the month name from column A with “!D2” to build a reference.

This workbook contains worksheets labeled Jan, Feb, Mar, and so on through Dec. A Summary worksheet lists the month abbreviations in A4:A15. To return cell D2 from each worksheet, use =INDIRECT(A4&”!D2”).
Figure 9.21 Cell D4 dynamically builds a text formula to reference the previous sheet,单元格D4动态生成一个文本公式,以引用上一页,

Using the HYPERLINK Function to Add Hyperlinks Quickly使用HYPERLINK函数快速添加超链接

Excel enables you to add a hyperlink by using the Excel interface. Excel允许您使用Excel界面添加超链接。On the Insert tab, select the Hyperlink icon. 在“插入”选项卡上,选择超链接图标。Next, you specify text to appear in the cell and the underlying address. 接下来,指定要显示在单元格中的文本和基础地址。Building links in this way is easy, but it is tedious to build them one at a time. 以这种方式构建链接很容易,但一次构建一个链接却很乏味。If you have hundreds of links to add, you can add them quickly by using the HYPERLINK function.如果要添加数百个链接,可以使用HYPERLINK函数快速添加。

Syntax:语法:
HYPERLINK(link_location,friendly_name)

The HYPERLINK function creates a shortcut that opens a document stored on your hard drive, a network server, or the Internet. This function takes the following arguments:

Figure 9.22 shows a list of web pages in column A. Column B contains the titles of those web pages. To quickly build a table of hyperlinks, you use =HYPERLINK(A2,B2) in cell C2 and copy the formula down the column. Unfortunately, you must keep columns A and B intact for the hyperlink to keep working. You can hide those columns, but there is no Paste Special option to convert the formula to values that will keep the hyperlink.

This image shows a list of URLs in column A and a list of titles in B. The formula =HYPERLINK(A2,B2) in column C creates a hyperlink with the title from B and the URL from A.
Figure 9.22 The formulas in column C enable you to create hundreds of hyperlinks in seconds.C列中的公式使您能够在几秒钟内创建数百个超链接。

Note

Note that Excel does not check whether the link location is valid at the time you created the link. 请注意,Excel在创建链接时不会检查链接位置是否有效。If the link is not valid when someone clicks it, the person encounters an error.如果有人单击链接时该链接无效,则该人会遇到错误。

Tip

It is difficult to select a cell that contains a HYPERLINK function. If you click the cell, Excel attempts to follow the hyperlink. Instead, click the cell and hold the mouse button until the pointer changes from a hand to a plus. Alternatively, click a nearby cell and use the arrow keys to move to the cell with the hyperlink.

To keep only the hyperlinks, copy column C and paste to a blank Word document. Open a new workbook. Copy from Word and paste back to the new Excel document.

Alternatively, use ="#HYPERLINK("""&A2&""""&", "&""""&B2&""""&")" in C2. Copy down and paste special values. Use Find and Replace to change # to =.

Using the TRANSPOSE Function to Formulaically Turn Data

With many people using Excel in a company, there are bound to be different usage styles from person to person. Some people build their worksheets horizontally, and other people build their worksheets vertically. For example, in Figure 9.23, the monthly totals stretch horizontally across row 80. However, for some reason, you need these figures to be arranged going vertically down from cell B84.然而,由于某些原因,您需要将这些图形从单元格B84垂直向下排列。

A horizontal row of month totals appears in C80:N80. You want those totals to appear going down a column, in B84:B95. Select B84:B95. Type the formula, =TRANSPOSE(C80:N80), and press Ctrl+Shift+Enter.
Figure 9.23 One TRANSPOSE function occupies 12 cells, from B84:B95.一个TRANSPOSE函数占据12个单位格,来自B84:B95。

The typical method is to copy C80:N80 and then use Home, Paste, Transpose. This copies a snapshot of the totals in row 80 to a column of data.

This is fine if you need only a snapshot of the totals. However, what if you want to see the totals continually updated in column B? Excel provides the TRANSPOSE function for such situations.

Because the function returns several answers, you need to use special care when entering the formula. Here’s how:

  1. Note that C80:N80 contains 12 cells.

  2. Select an identical number of cells starting in B84. Select B84:B95.

  3. Even though you have 12 cells selected, type the formula, =TRANSPOSE(C80:N80), as if you had only one cell selected.

  4. To tell Excel 2019 that this is a special type of formula called an array formula, hold down Ctrl+Shift while you press Enter. Pressing Ctrl+Shift+Enter is not required in Office 365 thanks to modern array formulas introduced in September 2018.

Excel shows the formula surrounded by curly braces in the formula bar. This is one single formula entered in 12 cells. Therefore, you cannot delete or change one cell in the range. If you want to change the formula, you need to delete all 12 cells in B84:B95 in a single command.

Syntax:语法:
TRANSPOSE(array)

The TRANSPOSE function transposes a vertical range into a horizontal array or vice versa.

The argument array is an array or a range of cells on a worksheet that you want to transpose. The transposition of an array is accomplished by using the first row of the array as the first column of the new array, the second row of the array as the second column of the new array, and so on.

Note

You can also use TRANSPOSE to turn a vertical range into a horizontal range.

Using GETPIVOTDATA to Retrieve One Cell from a Pivot Table

You might turn to this book to find out how to use most of the Excel functions. However, for the GETPIVOTDATA function, you are likely to turn to this book to find out why the function is being automatically generated for you.

Suppose that you have a pivot table on a worksheet. You should click outside the pivot table. Next, you type an equal sign and then use the mouse to click one of the cells in the data area of the pivot table. Although you might expect this to generate a formula such as =E9, instead, Excel puts in the formula =GETPIVOTDATA("Sales",$B$5,"Customer","Astonishing Glass Company","Region","West"), as shown in Figure 9.24.

A pivot table has customers in column A, regions in C6:F6 and sales in the values area. From outside the pivot table, type an equals sign and click on any cell in the values area. Rather than building a simple formula such as =E9, Excel returns a complex =GETPIVOTDATA() formula.
Figure 9.24 Excel inserts this strange function in the worksheet.Excel在工作表中插入这个奇怪的函数。

This function is annoying. As you copy the formula down to more rows, the function keeps retrieving sales to Astonishing Glass in the West region. By default, Excel is generating this function instead of a simple formula such as =E9. This happens whether you use the mouse or the arrow keys to specify the cell in the formula.

To avoid this behavior, you can enter the entire formula by manually typing it on the keyboard. Typing =E9 in a cell forces Excel to create a relative reference to cell E9. You are then free to copy the formula to other cells.

There is also a way to turn off this behavior permanently:

  1. Select a cell inside an active pivot table.

  2. The Pivot Table Tools tabs are displayed. Select the Analyze tab. From the PivotTable group, select the Options drop-down menu and then select the Generate GetPivotData icon. The behavior turns off.

  3. Enter formulas by using the mouse, arrow keys, or keyboard without generating the GETPIVOTDATA function.

Microsoft made GETPIVOTDATA the default behavior because the function is pretty cool. Now that you have learned how to turn off the behavior, you might want to understand exactly how it works in case you ever need to use the function.

Syntax:语法:
GETPIVOTDATA(data_field,pivot_table,field1,item1,field2,item2,...)

The GETPIVOTDATA function returns data stored in a pivot table report. You can use GETPIVOTDATA to retrieve summary data from a pivot table report, provided that the summary data is visible in the report. This function takes the following arguments:

Calculated fields or items and custom calculations are included in GETPIVOTDATA calculations.

Examples of Database Functions

If you were a data analyst in the 1980s and the early 1990s, you would have been enamored with the database functions. I used @DSUM every hour of my work life for many years. It was one of the most powerful weapons in any spreadsheet arsenal. Combined with a data table, the DSUM, DMIN, DMAX, and DAVERAGE functions got a serious workout when people performed data analysis in a spreadsheet.

Then, in 1993, Microsoft Excel added the pivot table to the Data menu in Excel. Pivot tables changed everything. Those powerful database functions seemed tired and worn out. Since that day in 1993, I had never used DSUM again until I created the example described in the following section. As far as I knew, the database functions had been living in a cave in South Carolina.

Maybe it is like the nostalgia of finding a box of photos of an old girlfriend, but I realized that the database functions are still pretty powerful. Customers whined enough to have Microsoft add AVERAGEIF to the COUNTIF and SUMIF arsenal. This was unnecessary: Customers could have done this easily by setting up a small criteria range and using DAVERAGE.

Eleven of the 12 database functions are similar. DSUM, DAVERAGE, DCOUNT, DCOUNTA, DMAX, DMIN, DPRODUCT, DSTDEV, DSTDEVP, DVAR, and DVARP all perform the equivalent operation of their non-D equivalents, but they allow for complex criteria to include records that meet certain criteria. See examples of each of these in Figure 9.25.

This figure shows a database in A23:I5024. The headings from row 23 are repeated in row 17, creating a criteria range in A17:A18. The figure shows formulas for eleven database functions: DSUM, DAVERAGE, DCOUNT, DCOUNTA, DMAX, DMIN, DPRODUCT, DSTDEV, DSTDEVP, DVAR, DVARP. In this case, the criteria range contains one customer name in A18, and the remaining values are blank. The formula =DSUM($A$23:$I$5024,H$23,$A$17:$I$18) sums all of the revenue for the customer entered in the criteria range. H$23 contains the heading for Revenue.
Figure 9.25 A simple criteria range specifies to limit DSUM to only records for Best Paint Inc. as a customer.一个简单的标准范围规定,DSUM仅限于Best Paint Inc.作为客户的记录。

To save you the hassle of looking up the confusing few, DCOUNT counts numeric cells, and DCOUNTA counts nonblank cells. DSTDEV and DVAR calculate the standard deviation and variance of a sample of a population, respectively. DSTDEVP and DVARP calculate the standard deviation and variance of the entire population, respectively. The 12th database function, DGET, has the same arguments, but it acts a bit differently, as explained later in this chapter.

Using DSUM to Conditionally Sum Records from a Database

There are three arguments to every database function. It is very easy to get your first DSUM working. The criteria argument is the one that offers vast flexibility. The following section explains the syntax for DSUM. The syntax for the other 11 database functions is identical to this.

Syntax:语法:
DSUM(database,field,criteria)

The DSUM function adds records from one field in a data set, provided that the records meet some criteria that you specify. The DSUM function takes the following arguments:

Creating a Simple Criteria Range for Database Functions

Although a criteria range needs only one field heading from the database, it is just as easy to copy the entire set of headings to a blank section of the worksheet. In Figure 9.25, for example, the headings in A17:I17, along with at least one additional row, create a criteria range.

In Figure 9.25, you see results of the 11 database functions for a simple criteria in which the customer is Best Paint Inc. Each formula specifies a database of $A$23:$I$5024. The field is H23, which is the heading for Revenue. The criteria range is A17:I18. In this example, the criteria range could have easily been A17:A18, but the A17:I18 form enables you to enter future criteria without specifying the criteria range again.

Using a Blank Criteria Range to Return All Records

This is a trivial example, but if the second row of the criteria range is completely blank, the database function returns the total of all rows in the data set. As shown in Figure 9.26, this is $256.6 million. This is equivalent to using the SUM function.

The criteria range has headings in row 17 and is completely blank in row 18. The DSUM returns all of the revenue in the entire database.
Figure 9.26 If the second row of the criteria is blank, the result reflects all rows.如果条件的第二行为空,则结果将反映所有行。
Using AND to Join Criteria

Many people who have used SUMIF in Excel 2003 and earlier are likely to want to know how to conditionally sum based on two conditions. This is simple to do with DSUM. If two criteria are placed on the same row of the criteria range, they are joined by an AND. In Figure 9.27, for example, the $123,275 is the sum of records in which the customer is Best Paint Inc. and the product is V937.

The criteria range specifies one customer in A18 and one product in B18. The DSUM returns the sum of all sales of one particular product to one specific customer.
Figure 9.27 When two criteria are on the same line, they are joined by an AND function; rows must meet both criteria to be included in the DSUM.当两个条件在同一条线上时,它们由AND函数连接;行必须满足这两个条件才能包含在DSUM中。
Using OR to Join Criteria使用OR来连接标准

When two criteria are placed on separate rows of the criteria range, they are joined by an OR function. In Figure 9.28, the $2.1 million represents records for either Improved Radio Traders or Best Paint Inc.

The criteria range is three rows tall in this example. Headings are in row 17. Two customers are listed, one in A18 and one in A19. The DSUM formula specifies a criteria range of A17:I19, and the result is sales to either of the customers.
Figure 9.28 When two criteria are on different rows, they are joined by an OR function; rows can meet either criterion to be included in the DSUM.

You can use OR to join criteria from different fields. The criteria range in Figure 9.29 shows a Region value of West joined by an OR with a District value of Texas. This pulls a superset of all the West records plus just the Texas records, which happen to fall in the Central region.

Another example of an OR criteria is shown. C18 asks for Region=West. D19 asks for District=Texas. Any records from either the West region or the Texas district will be returned in the DSUM answer.
Figure 9.29 The criteria to be joined with OR can be in separate columns.要与之连接的条件,或可以在单独的列中。
Using Dates or Numbers as Criteria

The example in Figure 9.30 finds records with a date after 2017 and with revenue under $50,000. The criteria in F18 for the date could have used any of these formats:

>12/31/2017
>=1/1/2018
>31-Dec-2017
The second row of the criteria range contains >12/31/2017 and <50000.
Figure 9.30 Using dates or numbers in criteria.在标准中使用日期或数字。
Using the Miracle Version of a Criteria Range使用标准范围的奇迹版本

Using the criteria ranges in the preceding examples, you could easily build any complex criteria with multiple AND or OR operators.使用前面示例中的条件范围,可以轻松地使用多个ANDOR运算符构建任何复杂的条件。

However, this could get complex. 然而,这可能会变得复杂。Imagine if you wanted to pull all the records for five specific customers and five specific products. 想象一下,如果你想获取五个特定客户和五个特定产品的所有记录。You would have to build a criteria range that is 26 rows tall. 你必须建立一个26排高的标准范围。Basically, the first row is the headings for customer and product. 基本上,第一行是客户和产品的标题。The second row indicates that you want to see records for Customer1 and Product1. 第二行表示您希望查看Customer1和Product1的记录。The third row indicates that you want to see records for Customer1 and Product2. The fourth row indicates that you want to see records for Customer1 and Product3. The seventh row indicates Customer2 and Product1. The 26th row indicates Customer5 and Product5.

If you need to pull the records for seven customers and seven products from five districts, your criteria range would grow to 246 rows tall and would probably never finish calculating.如果你需要从五个地区提取七个客户和七种产品的记录,你的标准范围将增长到246行,可能永远无法完成计算。

There is a miraculous version of the criteria range that completely avoids this problem. Here’s how it works:标准范围有一个神奇的版本,完全避免了这个问题。下面是它的工作原理:

For a simple example, suppose you want to find records that match one of 15 customers. You copy the customers to K24:K38. In the second row of the criteria field, write the formula =NOT(ISNA( MATCH(A24,$K$24:$K$38,0))). This formula does a MATCH on the first customer in the database to see if it is in the list in K. The ISNA and NOT functions make sure that the criteria cell returns a TRUE when the customer is one of the 15 customers.

Very quickly and without complaint, Excel compares the 5,000 rows of your database with this complex formula, and the DSUM produces the correct value, as shown in Figure 9.31.

In this image, the first row of the criteria range is completely blank. The second row contains one formula: =NOT(ISNA(MATCH(A24,$K$24:$K$38,0))). In this formula, A24 is the first customer in the database. K24:K38 is not seen but contains a list of customers.
Figure 9.31 The formula version of the criteria range is rare but incredibly powerful.标准范围的公式版本很少见,但却非常强大。

Using the DGET Function

The DGET function returns a single cell from a database. The problem is that this function is picky. If your criteria range matches zero records, DGET returns a #VALUE error. If your criteria range returns more than one row, DGET returns a #NUM! error.

To have DGET work, you need to write a criteria record that causes one and only one row to be evaluated as TRUE.

Syntax:语法:
DGET(database,field,criteria)

The DGET function returns a single cell matching criteria from a data set.DGET函数从数据集中返回单个单元格匹配条件。

Examples of Linked Data Types链接数据类型的示例

Microsoft debuted linked data types in 2018. 2018年,微软首次推出链接数据类型。The first two data types are stock market data and geographic data.前两种数据类型是股市数据和地理数据。

Enter a list of states, cities, or countries in some cells. 在某些单元格中输入州、城市或国家的列表。Select those cells and choose Geography from the Data Types gallery on the Data tab. 选择这些单元格,然后从数据选项卡上的数据类型库中选择地理位置。As shown in Figure 9.32, a Map icon appears next to each value to tell you that the cells contain a geography data type.如图9.32所示,每个值旁边都会出现一个地图图标,告诉您单元格包含地理数据类型。

This image shows five states in H2:H6. The new Data Types gallery on the Data tab offers Stocks and Geography. By choosing H2:H6 and clicking Geography, you are marking the cells as a geography data type.
Figure 9.32 Mark cells as the Geography data type.将单元格标记为地理数据类型。

If you click the map icon for a cell, a data card appears with information from Wikipedia about the state listed in the cell.如果单击某个单元格的地图图标,则会出现一张数据卡,其中包含来自维基百科的有关该单元格中所列状态的信息。

However, the more interesting feature is the new formulas that can point to the linked cell. In this example, Ohio is in H2. Go to any cell and type =H2 followed by a period. A list of fields appears. You can choose any of these fields to retrieve information about the geography. For example, =H2.Capital or =H2.Population. As shown in Figure 9.33, if the field name contains a space, wrap the name in square brackets: =H2.[Building Permits].

Cell H2 contains Ohio. Cell I2 shows the start of a formula =H2 followed by a period. Several fields are available, including Area, Capital, Largest city, and Median Gross Rent. The scroll bar indicates many more choices are available below this list.
Figure 9.33 Build a formula to return a property of the state.构建一个公式以返回状态的属性。

After entering the formula for the first state, you can copy the formula to pull similar data for each state. 在输入第一个状态的公式后,可以复制公式以获取每个状态的类似数据。Figure 9.34 shows the largest city in each state.图9.34显示了各州最大的城市。

I2 shows a formula of =H2.[Largest City] and the answer is Columbus. The formula has been copied down to other states, and each row is returning the largest city from a different state.
Figure 9.34 Once you’ve entered a formula, copy it down to other states.输入公式后,将其复制到其他州。

If you type a different state name in a cell, the formulas will update. 如果在单元格中键入其他状态名称,公式将更新。In Figure 9.35, Hawaii replaced Illinois. 在图9.35中,夏威夷取代了伊利诺伊州。In a second or so, Chicago is replaced with Honolulu.在一秒钟左右的时间里,芝加哥被檀香山取代。

Two states have been changed. Illinois was changed to Hawaii, and the Largest City formula in I4 is now reporting Honolulu. However, when Georgia was replaced with the misspelling of Maine as Mane, the result in I6 is a new error type of #FIELD!.
Figure 9.35 Change a state name and the calculated fields update.更改状态名称,计算字段将更新。

What if you mistype a name? 如果你打错名字怎么办?You will see a brand-new error value called #FIELD!.您将看到一个名为#FIELD!的全新错误值!。

Given that this is a new feature, there are some odd limitations:鉴于这是一项新功能,有一些奇怪的限制: