Page 260 - Excel 2007 Bible
P. 260
17_044039 ch12.qxp 11/21/06 11:05 AM Page 217
The next formula examines the text in cell A1 and returns the position of the first three-character sequence
that has a hyphen in the middle of it. In other words, it looks for any character followed by a hyphen and
any other character. If cell A1 contains the text Part-A90, the formula returns 4.
=SEARCH(“?-?”,A1,1)
Searching and replacing within a string
You can use the REPLACE function in conjunction with the SEARCH function to replace part of a text string
with another string. In effect, you use the SEARCH function to find the starting location used by the
REPLACE function.
For example, assume that cell A1 contains the text Annual Profit Figures. The following formula
searches for the 6-letter word Profit and replaces it with the word Loss:
=REPLACE(A1,SEARCH(“Profit”,A1),6,”Loss”)
This next formula uses the SUBSTITUTE function to accomplish the same effect in a more efficient manner:
=SUBSTITUTE(A1,”Profit”,”Loss”)
Advanced Text Formulas Creating Formulas That Manipulate Text 12
The examples in this section appear more complex than the examples in the preceding section. But as you
can see, these examples can perform some very useful text manipulations. Space limitations prevent a
detailed explanation of how these formulas work, but this section gives you a basic introduction.
You can access all of the examples in this section on the companion CD-ROM. The file is
ON the CD-ROM named text formula examples.xlsx.
ON the CD-ROM
Counting specific characters in a cell
This formula counts the number of Bs (uppercase only) in the string in cell A1:
=LEN(A1)-LEN(SUBSTITUTE(A1,”B”,””))
This formula works by using the SUBSTITUTE function to create a new string (in memory) that has all the
Bs removed. Then the length of this string is subtracted from the length of the original string. The result
reveals the number of Bs in the original string.
The following formula is a bit more versatile; it counts the number of Bs (both uppercase and lowercase) in
the string in cell A1. Using the UPPER function to convert the string makes this formula work with both
uppercase and lowercase characters:
=LEN(A1)-LEN(SUBSTITUTE(UPPER(A1),”B”,””))
Counting the occurrences of a substring in a cell
The formulas in the preceding section count the number of occurrences of a particular character in a string.
The following formula works with more than one character. It returns the number of occurrences of a par-
ticular substring (contained in cell B1) within a string (contained in cell A1). The substring can consist of
any number of characters.
=(LEN(A1)-LEN(SUBSTITUTE(A1,B1,””)))/LEN(B1)
217