Excel provides no direct way to display the ratio between two values. For example, assume cell A1 contains 3, and cell B1 contains 24. The ratio between these two values is 1:8.

Following is a formula, contributed by Douglas J. Roach, that displays the ratio between the values in cells A1 and B1:

=(LEFT(TEXT(A1/B1,"####/####"),FIND("/",TEXT(A1/B1,"####/####"))-1)&":"
&RIGHT(TEXT(A1/B1,"####/####"),LEN(TEXT(A1/B1,"####/####"))
-FIND("/",TEXT(A1/B1,"####/####"))))

The formula automatically reduces the "fraction" to the simplest form, and it allows up to four characters on either side of the colon.

Jerry Meng pointed out a much simpler formula that produces the same result, but does not have the four-character limit:

=A1/GCD(A1,B1)&":"&B1/GCD(A1,B1)

Jerry's formula uses the GCD function, which is available only when the Analysis Toolpak Add-In is installed.

Note: Be aware that the result of these formulas is actually a time value, not a fractional value. For example, the ratio of 1:8 is not the same as 1/8. Rather, it is represented internally as 1:08 am.

Excel's IF function provides some simple decision-making capability to a worksheet. The IF function accepts three arguments:

  • The condition being evaluated (should result in either TRUE or FALSE)
  • The value to display if the condition is TRUE
  • The value to display if the condition is FALSE

The formula below, for example, returns 1 if cell A1 contains "A". If cell A1 does not contain "A", the formula returns an empty string.

=IF(A1="A",1,"")

For more decision-making power, you can "nest" IF functions within a formula. In other words, you can use an IF function as the second argument for an IF function. Here's an example:

=IF(A1="A",1,IF(A1="B",2,IF(A1="C",3,"")))

This formula checks cell A1. If it contains "A", the formula returns 1. If it doesn't contain "A", then the second argument is evaluated. The second argument contains another IF function that determines if A1 contains a "B". If so, the formula returns 2; if not, the formula evaluates the IF function contained in the second argument and checks to see if A1 contains "C". If so, it returns 3; otherwise, it returns an empty string.

Excel allows up to seven levels of nested IF functions. The formula below works correctly, but Excel will not allow you to nest the IF functions any deeper than this.

=IF(A1="A",1,IF(A1="B",2,IF(A1="C",3,IF(A1="D",4,
 IF(A1="E",5,IF(A1="F",6,IF(A1="G",7,IF(A1="H",8,""))))))))

The sections that follow present various ways to get around the limit of seven nested IF functions. Be aware that these techniques may not be appropriate for all situations.

Using a VLOOKUP formula

In many cases, you can avoid using IF functions and use a VLOOKUP function. This will require a separate table in your worksheet. In the figure below, the lookup table is in B1:C10. The formula in A2 is:

=VLOOKUP(A1,B1:C10,2)

Using defined names

Another way to overcome the nested IF function limit is to use named formulas. Chip Pearson describes this technique at his web site, so I won't repeat it here.

Using the CONCATENATE function

Yet another option was suggested to me by B. Ganesh: Use the CONCATENATE function. In this case, each argument for CONCATENATE consists of an IF function. Here's an example:

=CONCATENATE(IF(A1="A",1,""),IF(A1="B",2,""),IF(A1="C",3,""),
IF(A1="D",4,""),IF(A1="E",5,""),IF(A1="F",6,""),IF(A1="G",7,""),
IF(A1="H",8,""),IF(A1="I",9,""),IF(A1="J",10,""))

The CONCATENATE function can handle as many as 30 arguments -- which equates to testing 30 different conditions.

And, as Alan Williams pointed out, you can avoid using the CONCATENATE function and use the concatenation operator (&):

   =IF(A1="A",1,"")&IF(A1="B",2,"")&IF(A1="C",3,"")
    &IF(A1="D",4,"")&IF(A1="E",5,"")&IF(A1="F",6,"")
   &IF(A1="G",7,"")&IF(A1="H",8,"")&IF(A1="I",9,"")
   &IF(A1="J",10,"")

This method is not limited to 30 comparisons.

Use Boolean multiplication

Another alternative, suggest by Daniel Filer is to use Boolean multiplication. This technique takes advantage of the fact that, when multiplying, TRUE is treated as 1 and FALSE is treated as 0. Here's an example:

=(A1="A")*1+(A1="B")*2+(A1="C")*3+(A1="D")*4+(A1="E")*5
+(A1="F")*6+(A1="G")*7+(A1="H")*8+(A1="I")*9+(A1="J")*10

Creating a custom VBA function

The final alternative is to create a custom worksheet function, using VBA. The advantage is that you can customize the function to meet your requirements, and your formulas can be simplified quite a bit.

This tip describes how to create what I call a "megaformula" -- a single formula that does the work of several intermediate formulas.

An Example

The goal is to create a formula that returns the string of characters following the final occurrence of a specified character. For example, consider the text string below (which happens to be a URL):

http://spreadsheetpage.com/index.php/tips

Excel does not provide a straightforward way to extract the characters following the final slash character (i.e., "tips") from this string. It is possible, however, do do so by using a number of intermediate formulas. The figure below shows a multi-formula solution. The original text is in cell A1. Formulas in A2:A6 are used to produce the desired result. The formulas are displayed in column B.

Following is a description of the intermediate formulas (which will eventually be combined into a single formula).

  1. Count the number of slash characters (Cell A2)
    The formula in cell A2 returns the number of slash characters in cell A1. Excel doesn't provide a direct way to count specific characters in a cell, so this formula is relatively complex.
  2. Replace the last slash character with an arbitrary character (Cell A3)
    The formula in A3 uses the SUBSTITUTE function to replace the last slash character (calculated in A2) with a new character. I chose CHAR(1) because there is little chance of this character actually appearing in the original text string.
  3. Get the position of the new character (Cell A4)
    The formula in A4 uses the FIND function to determine the position of the new character.
  4. Count the number of characters after the new character (Cell A5)
    The formula in A5 subtracts the position of the new character from the length of the original string. The result is the number of characters after the new character.
  5. Get the text after the new character (Cell A6)
    The formula in A6 uses the RIGHT function to extract the characters -- the end result.

Combining the Five Formulas Into One

Next, these five formulas will be combined into a single formula.

  1. Activate the cell that displays the final result (in this case, cell A6). Notice that it contains a reference to cell A5.
  2. Activate cell A5. Press F2 and select the formula text (but omit the initial equal sign), and press Ctrl+C to copy the text. Press Esc.
  3. Re-activate cell A6 and paste the copied text to replace the reference to cell A5. The formula in A6 is now:
=RIGHT(A1,LEN(A1)-A4)
  1. The formula contains a reference to cell A4, so activate A4 and copy the formula as text. Then replace the reference to cell A4 with the copied formula text. The formula now looks like this:
RIGHT(A1,LEN(A1)-FIND(CHAR(1),A3))
  1. Replace the reference to cell A3 with the formula text from cell A3. The formula now looks like this:
=RIGHT(A1,LEN(A1)-FIND(CHAR(1),SUBSTITUTE(A1,"/",CHAR(1),A2)))
  1. Replace the reference to cell A2 with the formula text from cell A2. The formula now looks like this:
=RIGHT(A1,LEN(A1)-FIND(CHAR(1),SUBSTITUTE(A1,"/",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"/","")))))

The formula now refers only to cell A1, and the intermediate formula are no longer necessary. This single formula does the work of five other formulas.

This general technique can be applied to other situations in which a final result uses several intermediate formulas.

NOTE: You may think that using such a complex formula would cause the worksheet to calculate more slowly. In fact, you may find just the opposite: Using a single formula in place of multiple formulas may speed up recalculation. Any calculation speed differences, however, will probably not be noticeable unless you have thousands of copies of the formula.

Caveat

Keep in mind that a complex formula such as this is virtually impossible to understand. Therefore, use this type of formula only when you are absolutely certain that it works correctly and you are sure that you will never need to modify it in the future. Better yet, keep a copy of those intermediate formulas -- just in case.

This tip describes a technique that should be in the arsenal of every Excel user. It describes how to use formulas to transform data.

The figure below shows a simple example. The text in column A consists of lower case letters. The goal is to transform these cells so they display "proper" case. This will be done by creating formulas that use Excel's PROPER function.

The steps below are specific to this example. But they can easily be adapted to other types of data transformations.

Creating the formulas

In this case, the formulas will go in column D. As you'll see, this is just a temporary location. The formula results will eventually replace the names in column A.

  1. Enter the following formula in cell D2:
=PROPER(A2)
  1. Copy the formula down the column to accommodate the data. In this case, the formula is copied down to cell D11. The worksheet now looks like this (the formula cells are selected, so they appear highlighted).

Copying and pasting the formula cells

In this step, the formula cells are copied, and pasted as values -- overwriting the original data in column A.

  1. Select the formula cells. In this case, D2:D11.
  2. Choose Edit - Copy
  3. Select the first cell in the original data column (in this case, cell A2).
  4. Choose Edit - Paste Special. This displays the Paste Special dialog box.
  5. In the Paste Special dialog box, click the Value option button. This step is critical. It pastes the results of the formulas -- not the formulas.
  6. Click OK.

At this point, the worksheet looks like this:

Deleting the temporary formulas

The formulas in column D are no longer necessary, so you can delete them.

Q. I have a range of time values, but when I try to sum them, the total is never greater than 24 hours.

When you add a range that contains time values, Excel ignores the hours that exceed 24. The solution is to use a custom number format.

  1. Activate the cell that contains your total time
  2. Choose Format, Cells.
  3. In the Format Cells dialog box, click the Number tab.
  4. Choose Custom from the Category list
  5. Type [h]:mm into the box labeled Type.

Using brackets around the hour portion of the format string tells Excel to display hours that exceed 24 hours.

Q. I find that sometimes my formulas do not get fully calculated. This often happens when I use custom functions created with VBA.

Microsoft has acknowledged some problems with the Excel calculation engine in some version of Excel. In order to be assured that all of your formulas have been calculated, press Ctrl-Alt-F9 to force a complete recalculation.

This key combination will also update formulas that use custom VBA functions.

Q. Can I write a formula that returns the number of distinct entries in a range?

First, let's clarify the question. We're hunting for a formula that, given the range that contains the values 100, 99, 98, 100, 98, 100, 98, would return 3. In other words, this range contains three different values, some of them repeated.

This type of counting requires an array formula. The formula below, for example, counts the number of distinct entries in the range A1:D100.

=SUM(1/COUNTIF(A1:D100, A1:D100))

When you enter this formula, you must press Ctrl-Shift-Enter. Pressing only Enter will give you the wrong result. Excel will place brackets around the formula to remind you that you've created an array formula.

The preceding formula works fine in many cases, but it will return an error if the range contains any blank cells. The formula below (also an array formula, so input it with Ctrl-Shift-Enter) is more complex, but it will handle a range that contains a blank cell.

=SUM(IF(COUNTIF(A1:D100,A1:D100)=0, "", 1/COUNTIF(A1:D100,A1:D100)))

Hiding Your Formulas

Posted by sato | 1:45 AM

Q. I've created some clever formulas, and I don't want anyone else to see them. Is it possible to hide the formulas but display the results?

Every cell has two key properties: locked and hidden. A locked cell can't be changed, and the contents of a hidden cell don't appear in the formula bar when the cell is selected. By default, every cell is locked and not hidden. But it's important to remember that these attributes have no effect unless the worksheet itself is protected.

First, to change the attributes, select the appropriate cell or range and then choose Format, Cells. In the Format Cells dialog box, click the Protection tab and select Locked or Hidden (or both). Unlock cells that accept user input, and lock formula and other cells that should stay unchanged (such as titles). To prevent others from seeing your formulas, lock and hide the formula cells: The results of the formulas will be visible, but the formulas will not.

Now, to protect the worksheet, choose Tools, Protection, Protect Sheet to bring up the Protect Sheet dialog box. Make sure the Contents box is checked. You can enter a password to prevent others from unprotecting the sheet. Locked cells in a protected sheet cannot be edited, and other worksheet changes are disabled. For example, no one can insert rows or columns, change column width, or create embedded charts.

NOTE: Keep in mind that it is very easy to break the password for a protected sheet. If you are looking for real security, this is not the solution.

Q. I have a price list stored in a worksheet, and I need to increase all prices by 5 percent. Can I do this without reentering all the prices?

Excel provides two ways to accomplish this. The "traditional" technique goes something like this:

  1. Insert or find a blank column near the prices.
  2. In that column's first cell, enter a formula to multiply the price in that row by 1.05.
  3. Copy the formula down the column.
  4. Select and copy the entire column of formulas
  5. Select the original prices, and choose Edit, Paste Special.
  6. In the Paste Special dialog box, select Values to overwrite the original prices with the formulas' results.
  7. And finally, delete the column of formulas.

The other, more efficient approach also uses the Paste Special dialog box. To increase a range of values (prices, in this example) by 5 percent:

  1. Enter 1.05 into any blank cell.
  2. Select the cell and choose Edit, Copy.
  3. Select the range of values and choose Edit, Paste Special.
  4. Choose the Multiply option and click OK.
  5. Delete the cell that contains the 1.05.

Sometimes a formula may return an error message. Usually, you'll want to know when a formula error occurs. But now and then you may prefer to avoid the messages. You can do so by using an IF() function to check for an error.

For example, the formula below displays a blank if the division results in an error.

=IF(ISERROR(A1/B1),"",A1/B1) 

You can adapt this technique to any operation. The original formula serves as the argument for the ISERROR() function, and it repeats as the last argument of the IF() function. Like this:

=IF(ISERROR(OriginalFormula),"",OriginalFormula) 

Q. Is it possible to round a dollar amount to the nearest 25 cents? For example, if a number appears as $1.65, I would like to convert it to $1.75. Excel's ROUND() function seems to work only with whole numbers.

Yes, you can use Excel's ROUND() function to achieve the rounding you want. The following formula, which assumes that your value is in cell A1, will do the job for you.

=ROUND(A1/.25,0)*.25

The formula divides the original value by .25 and then multiplies the result by .25. You can, of course, use a similar formula to round values to other fractions. For example, to round a dollar amount to the nearest nickel, simply substitute .05 for each of the two occurrences of ".25" in the preceding formula.

Your worksheet may be set up with formulas that operate on a number of input cells. Here's an easy way to clear all input values while keeping the formulas intact.

Press F5 to display the Go To dialog box, and click the Special button. In the Go To Special dialog, choose the Constants button and select Numbers. When you click OK, the nonformula numeric cells will be selected. Press Delete to delete the values. The Go To Special dialog box has many other options for selecting cells of a particular type.

Q. My Excel workbook has a sheet for each month, named January, February, and so on. I also have a summary sheet that displays key calculations for a particular month. For example, one of my formulas is:

=SUM(February!F1:F10) 

Is there any way that I can enter the month name into a cell on my summary sheet, and then have my formulas use the data for the specified sheet?

Yes. Excel's INDIRECT function was designed specifically for this sort of thing. This function accepts a text string as an argument, and then evaluates the text string to arrive at a cell or range reference. In your case, assume that cell B1 on your summary worksheet holds the month name. The following formula utilizes the INDIRECT function to create the range reference used by the SUM function:

=SUM(INDIRECT(B1&"!F1:F10"))

Note that I use the ampersand operator to join the month name with the cell reference (expressed as text). Refer to the figure below. If cell B1 contains the text March, the SUM function returns the sum of the range March!F1:F10.

All spreadsheets support lookup functions, tools that return a value from a table by looking up another value in the table. An income tax table is a good example. You can write a formula that uses the VLOOKUP function to determine the tax rate for a given income amount.

The lookup functions in Excel are only appropriate for one-way lookups, however. If you need to perform a two-way lookup, you'll need more than the standard functions. The figure below shows a simple example.

The formula in cell H4 looks up the entries in cells H2 and H3 and then returns the corresponding value from the table. The formula in H4 is:

=INDEX(A1:E14, MATCH(H2,A1:A14,0), MATCH(H3,A1:E1,0)).

The formula uses the INDEX function, with three arguments. The first is the entire table range (A1:A14). The second uses the MATCH function to return the offset of the desired month in column A. The third argument uses the MATCH function to return the offset of the desired product in row 1.

You may prefer to take advantage of Excel's natural-language formulas. For example, enter the following formula to return Sprocket sales for June:

=June Sprockets 

If natural-language formulas aren't working, select Tools, Options, click the Calculation tab, and place a check mark next to "Accept labels in formulas." Be aware that using natural language formulas is not 100% reliable!

A companion file is available: Click here to download

Q. When I use Excel's AutoFiltering, the status bar displays the number of qualifying rows. But for no apparent reason, that number often vanishes. How do I keep this number visible while I work?

AutoFiltering a list hides rows that don't meet your filter criteria. After applying filtering criteria, Excel shows the record count on the status bar--but this value disappears when the sheet is calculated.

To display a permanent count of the visible rows in an AutoFiltered list, create a formula using Excel's SUBTOTAL function. The first argument for SUBTOTAL specifies the type of operation (an argument of 2 displays a count of the visible cells in a range).

The figure below shows a list in rows 6 through 3006. The formula in cell D3 is:

=SUBTOTAL(2,A6:A3006)

The formula counts the number of visible cells in the range (minus the header row). Apply different filtering criteria, and the formula updates to show the new count. The SUBTOTAL function only works for AutoFiltering and outlining. If you hide rows manually, it won't return the correct result.

Q. I need to calculate the sum of the three largest values in a range of 100 cells. The range isn’t sorted, so I can’t use a SUM function. Do you have any suggestions about how I could handle this problem?

Excel’s LARGE function returns the nth-largest value in a range, in which n is the function’s second argument. You need a formula that calls the LARGE function three times and then sums the results. The following formula, which assumes the numbers are located in the range A1:A100, will do the job:

=LARGE(A1:A100,1)+ LARGE(A1:A100,2)+ LARGE(A1:A100,3)

Another approach is to use an array formula like this one:

=SUM(LARGE(A1:A100,{1,2,3}))

The formula first passes an array of three values to the LARGE function, and then uses the SUM function to add the values returned by the LARGE function. Notice that the values 1 through 3 are enclosed in brackets rather than parentheses. After typing an array formula, press Ctrl-Shift-Enter instead of Enter.

Formulas of this type can become unwieldy as n gets larger. For example, to sum the top 30 values in a range, a formula must contain a list of integers from 1 to 30. Here is a more general version of the array formula:

=SUM(LARGE(A1:A100,ROW(INDIRECT ("1:30"))))

This formula uses the ROW function to generate a series of integers between 1 and 30, and uses this array as the second argument for the LARGE function. To sum a different quantity of numbers, just change the 30 to the desired number.

Sometimes you just don't want data to repeat itself. On an order form or an inventory sheet, for instance, you may not want a part number entered in one cell to repeat in another cell. You can use Excel's Data Validation feature to to prevent a value from appearing more than once in a range.

In the example below, the range A2:A20 requires unique part numbers. If the user enters a number that already exists, a message box pops up and asks for a different one.

To create this type of message box for your worksheet:

  1. Select the cells for which you need to punch in unique entries (here, the correct range to select is A2:A20).

  2. Choose Data, Validation and click the Settings tab.

  3. Choose Custom from the Allow drop-down list. The Custom option requires a logical formula that will return either "True" or "False." This example requires a formula that will return "True" only if the content of the cell does not match one that already exists in the range. The COUNTIF function will do the job. Type the following formula into the Formula field:

    =COUNTIF($A$2:$A$20,A2)=1 

    This formula counts the number of cells in range A2:A20 that contain the same value that appears in cell A2. If the count is 1, the formula returns "True"; otherwise, it returns "False." Notice that the first argument for COUNTIF is an absolute reference to the entire validation range. In contrast, the second argument is a relative reference to the upper left cell in the validation range (it will be adjusted for each of the other cells in the range).

  4. Next, to create the warning that appears in a pop-up message box when a duplicate value is entered into the selected range, click the Error Alert tab in the Data Validation dialog box. For the Style, select Stop (this option rejects existing values). Enter a title for the message box (such as Duplicate Data) and type your error message.

  5. Click OK and try it out.

You'll find that you can enter any data into the validation range, but if you type an entry that already exists, you'll get the warning message. Click Retry to edit the cell's contents or choose Cancel to clear the cell.

While Data Validation is a useful feature, it contains a potentially serious design flaw. If you copy a cell and paste it to a cell that uses the feature, the Data Validation rules are wiped out. This problem also applies to cells that use Conditional Formatting. You'll need to keep this in mind when you're cutting and pasting in mission-critical applications.

A companion file is available: Click here to download

In the eyes of Excel, the world began on January 1, 1900. Excel is not capable of working with dates earlier than that.

People who use Excel to store historical information often need to work with pre-1900 dates. The only way to create a date such as July 4, 1776, in Excel is to enter it into a cell and have the program interpret it as text. Unfortunately, you can't manipulate dates stored as text -- if you want to alter their formatting, for example, or if you need to calculate the day of the week they fell on.

To address this problem, I created an add-in (for Excel 97 or later versions) called Extended Date Functions. With this add-in installed, you'll have access to eight new worksheet functions that let you work with dates in any year from 0100 through 9999.

Note: Be careful if you plan to insert dates that occurred before 1752. Differences between the historical American, British, Gregorian, and Julian calendars can result in inaccurate computations.

Excel includes three functions (ROUND, ROUNDUP, and ROUNDDOWN) that round values to a specified number of digits. In some cases, however, you may need to round a value to a specified number of significant digits.

For example, you might want to express the value 1,432,187 in terms of two significant digits (that is, as 1,400,000). Here's an elegant solution. The formula below rounds the value in cell A1 to the number of significant digits specified in cell A2:

=ROUND(A1,A2-1-INT(LOG10(ABS(A1))))

If you've ever had to figure out which of the year's 365 days a particular date falls on, or how many days remain in the year, you've probably found that Excel lacks functions to perform the calculation. But you can create formulas to do the job.

The formula below returns the day of the year for a date in cell A1:

=A1-DATE(YEAR(A1),1,0)

Note: Excel automatically formats the cell as a date, so change the number format to another option (like General).

To calculate the number of days remaining in the year (assuming that the date is in cell A1), use the following formula:

=DATE(YEAR(A1),12,31)-A1

It's fairly easy to create a formula that generates consecutively number items in nonconsecutive cells. Refer to the figure below.

Column A consists of formulas that refer to column B. The formula in cell A1 is:

 =IF(B1<>"",COUNTA($B$1:B1)&".","")

This formula, which is copied down to the other cells in column A, displays the next consecutive item number if the corresponding cell in column B is not empty. If the cell in column B is empty, the formula displays nothing.

As items are added or deleted from column B, the numbering updates automatically.

Did you know that you could combine text and values in a single cell?

For example, assume cell A12 contains the value 1435. Enter the following formula into another cell:

="Total: "&A12 

The formula cell will display: "Total: 1435."

The ampersand is a concatenation operator that joins the text with the contents of cell A12.

Applying a number format to the cell containing the formula has no effect, because the cell contains text, not a value. As a work-around, modify the formula to use the TEXT function (the second argument for the TEXT function consists of a standard Excel number-format string).

="Total: "&TEXT(A12,"$#,##0.00")

This formula will display "Total: $1,435.00."

Here's another example formula that uses the NOW function to display some text along with the current date and time:

="Report printed on "&TEXT(NOW(),"mmmm d, yyyy at h:mm AM/PM")

In the real world, a simple average often isn't adequate for your needs.

For example, an instructor might calculate student grades by averaging a series of test scores but omitting the two lowest scores. Or you might want to compute an average that ignores both the highest and lowest values.

In cases such as these, the AVERAGE function won't do, so you must create a more complex formula. The following Excel formula computes the average of the values contained in a range named "scores," but excludes the highest and lowest values:

=(SUM(scores)-MIN(scores)-MAX(scores))/(COUNT(scores)-2)

Here's an example that calculates an average excluding the two lowest scores:

=(SUM(scores)-MIN(scores)-SMALL(scores,2))/(COUNT(scores)-2)

Excel's AutoFilter feature definitely ranks right up there when it comes to handy tools. This feature, which you access with the Data, Filter, AutoFilter command, works with a range of cells set up as a database or list. When AutoFiltering is turned on, the row headers display drop-down arrows that let you specify criteria (such as "Age greater than 30"). Rows that don't match your criteria are hidden, but they are redisplayed when you turn off AutoFiltering.

One problem with AutoFiltering is that you can't tell which criteria are in effect. Stephen Bullen developed a custom VBA worksheet function that displays the current AutoFilter criteria in a cell. The instructions that follow are for Excel 97 or later.

Press Alt+F11 and insert a new module for the active workbook. Then enter the VBA code for the FilterCriteria shown below.

Function FilterCriteria(Rng As Range) As String
    'By Stephen Bullen
    Dim Filter As String
    Filter = ""
    On Error GoTo Finish
    With Rng.Parent.AutoFilter
        If Intersect(Rng, .Range) Is Nothing Then GoTo Finish
        With .Filters(Rng.Column - .Range.Column + 1)
            If Not .On Then GoTo Finish
            Filter = .Criteria1
            Select Case .Operator
                Case xlAnd
                    Filter = Filter & " AND " & .Criteria2
                Case xlOr
                    Filter = Filter & " OR " & .Criteria2
            End Select
        End With
    End With
Finish:
    FilterCriteria = Filter
End Function

After you've entered the VBA code, you can use the function in your formulas. The single-cell argument for the FilterCriteria function can refer to any cell within the column of interest. The formula will return the current AutoFilter criteria (if any) for the specified column. When you turn AutoFiltering off, the formulas don't display anything.

The figure below shows the FilterCriteria in action. The function is used in the cells in row 1. For example, cell A1 contains this formula:

=FilterCriteria(A3) 

As you can see, the list is currently filtered to show rows in which column A contains January, column C contains a code of A or B, and column D contains a value greater than 125 (column B is not filtered, so the formula in cell B1 displays nothing). The rows that don't match these criteria are hidden.

How many times have you accidentally deleted or overwritten cells containing formulas only to discover the mistake after it's too late? One solution is to write-protect important cells. Another approach is to give those cells a visual flag.

This clever technique was submitted by David Hager. It uses Conditional Formatting (available in Excel 97 or later) to apply special formatting to cells that contain formulas--something that's not normally possible. With this technique you can set up your worksheet so that all formula cells get a yellow background, for example, or so that negative values are in boldface.

Follow these steps:

  1. Select Insert, Name, Define.
  2. In the Define Name dialog box, enter the following in the 'Names in workbook' box
    CellHasFormula 
  3. Then enter the following formula in the "Refers to" box
    =GET.CELL(48,INDIRECT("rc",FALSE))
  4. Click Add, and then OK.
  5. Select all the cells to which you want to apply the conditional formatting.
  6. Select Format, Conditional Formatting
  7. In the Conditional Formatting dialog box, select Formula Is from the drop-down list, and then enter this formula in the adjacent box (see the figure below):
    =CellHasFormula
  8. Click the Format button and select the type of formatting you want for the cells that contain a formula.
  9. Click OK.

After you've completed these steps, every cell that contains a formula and is within the range you selected in Step 4 will display the formatting of your choice.

How does it work? The key component is creating a named formula in Steps 2 and 3. This formula, unlike standard formulas, doesn't reside in a cell, but it still acts like a formula by returning a value -- in this case either 'True' or 'False'. The formula uses the GET.CELL function, which is part of the XLM macro language (VBA's predecessor) and cannot be used directly in a worksheet. Using a value of 48 as the first argument for GET.CELL causes the function to return 'True' if the cell contains a formula. The INDIRECT function essentially creates a reference to each cell in the selected range.

Excel lacks a function for calculating the number of days in a particular month, so you'll need to construct your own formula. If cell A1 contains a date, this formula will return the number of days in the month: =DAY(DATE(YEAR(A1),MONTH(A1)+1,1)-1)

In Excel, you can compare the cells in two ranges with an array formula. For instance, to see if all of the values in A1:A100 are identical to those in B1:B100, type this array formula: =SUM(IF(A1:A100=B1:B100,0,1)) Note: This is an array formula and it must be entered using Ctrl-Shift-Enter. The formula will return the number of corresponding cells that are different. If the formula returns 0, it means that the two ranges are identical.

Q. I often import data into Excel from various applications, including Access. I've found that values are sometimes imported as text, which means I can't use them in calculations or with commands that require values. I've tried formatting the cells as values, with no success. The only way I've found to convert the text into values is to edit the cell and then press Enter. Is there an easier way to make these conversions?

This is a common problem in Excel. The good news is the Excel 2002 is able to identify such cells and you can easily correct them If you're using an older version of Excel, you can use this method:

  1. Select any empty cell
  2. Enter the value 1 into that cell
  3. Choose Edit, Copy
  4. Select all the cells that need to be converted
  5. Choose Edit, Paste Special
  6. In the Paste Special dialog box, select the Multiply option, then click OK.

This operation multiplies each cell by 1, and in the process converts the cell's contents to a value.

Because Excel stores dates and times as numeric values, it's possible to add or subtract one from the other.

However, if you have a workbook containing only times (no dates), you may have discovered that subtracting one time from another doesn't always work. Negative time values appear as a series of hash marks (########), even though you've assigned the [h]:mm format to the cells.

By default, Excel uses a date system that begins with January 1, 1900. A negative time value generates a date/time combination that falls before this date, which is invalid.

The solution is to use the optional 1904 date system. Select Tools, Options, click the Calculation tab, and check the 1904 date system box to change the starting date to January 2, 1904. Your negative times will now be displayed correctly, as shown below.

Be careful if you workbook contains links to other files that don't use the 1904 date system. In such a case, the mismatch of date systems could cause erroneous results.

Q. Whenever I open a particular Excel workbook, I get a message asking if I want to update the links. I've examined every formula in the workbook, and I am absolutely certain that the workbook contains no links to any other file. What can I do to convince Excel that the workbook has no links?

You've encountered the infamous "phantom link" phenomenon. I've never known Excel to be wrong about identifying links, so there's an excellent chance that your workbook does contain one or more links -- but they are probably not formula links.

Follow these steps to identify and eradicate any links in a workbook.

  1. Select Edit, Links. In many cases, this command may not be available. If it is available, the Links dialog box will tell you the name of the source file for the link. Click the Change Source button and change the link so it refers to the active file.
  2. Select Insert, Name, Define. Scroll through the list of names in the Define Name dialog box and examine the Refers to box (see the figure below). If a name refers to another workbook or contains an erroneous reference such as #REF!, delete the name. This is, by far, the most common cause of phantom links
  3. If you have a chart in your workbook, click on each data series in the chart and examine the SERIES formula displayed in the formula bar. If the SERIES formula refers to another workbook, you've identified your link. To eliminate the link move or copy the chart's data into the current workbook and recreate your chart.
  4. If your workbook contains any custom dialog sheets, select each object in each dialog sheet and examine the formula bar. If any object contains a reference to another workbook, edit or delete the reference.

Next, save your workbook and then re-open it. It should open up without asking you to update the links.

When you add a trendline to a chart, Excel provides an option to display the trendline equation in the chart. This tip describes how to create formulas that generate the trendline coefficients. You can then use these formulas to calculate predicted y values for give values of x.

These equations assume that your sheet has two named ranges: x and y.

Linear Trendline

Equation: y = m * x + b
m: =SLOPE(y,x)
b: =INTERCEPT(y,x)

Logarithmic Trendline

Equation: y = (c * LN(x)) - b
c: =INDEX(LINEST(y,LN(x)),1)
b: =INDEX(LINEST(y,LN(x)),1,2)

Power Trendline

Equation: y=c*x^b
c: =EXP(INDEX(LINEST(LN(y),LN(x),,),1,2))
b: =INDEX(LINEST(LN(y),LN(x),,),1)

Exponential Trendline

Equation: y = c *e ^(b * x)
c: =EXP(INDEX(LINEST(LN(y),x),1,2))
b: =INDEX(LINEST(LN(y),x),1)

2nd Order Polynomial Trendline

Equation: y = (c2 * x^2) + (c1 * x ^1) + b
c2: =INDEX(LINEST(y,x^{1,2}),1)
C1: =INDEX(LINEST(y,x^{1,2}),1,2)
b = =INDEX(LINEST(y,x^{1,2}),1,3)

3rd Order Polynomial Trendline

Equation: y = (c3 * x^3) + (c2 * x^2) + (c1 * x^1) + b
c3: =INDEX(LINEST(y,x^{1,2,3}),1)
c2: =INDEX(LINEST(y,x^{1,2,3}),1,2)
C1: =INDEX(LINEST(y,x^{1,2,3}),1,3)
b: =INDEX(LINEST(y,x^{1,2,3}),1,4)

Higher Order Polynomial Trendline

Notice the pattern in the two preceding sets of formulas.

If you peruse the Excel newsgroups, you've probably realized that one of the most common questions involves summing or counting using multiple criteria. If your data is set up as a database table you can use database functions such as DCOUNT or DSUM. These functions, however, require the use of a separate criteria range on your worksheet.

This tip provides a number of examples that should solve most of your counting and summing problems. Unlike DCOUNT and DSUM, these formulas don't require a criteria range.

The example formulas presented in this tip use the simple database table shown below. You will need to adjust the formulas to account for your own data.

http://spreadsheetpage.com/graphics/tips/table.gif (5737 bytes)

Sum of Sales, where Month="Jan"

This is a straightforward use of the SUMIF function (it uses a single criterion):

  =SUMIF(A2:A10,"Jan",C2:C10)

Count of Sales, where Month="Jan"

This is a straightforward use of the COUNTIF function (single criterion):

  =COUNTIF(A2:A10,"Jan")

Sum of Sales, where Month<>"Jan"

Another simple use of SUMIF (single criterion):

  =SUMIF(A2:A10,"<>Jan",C2:C10)

Sum of Sales where Month="Jan" or "Feb"

For multiple OR criteria in the same field, use multiple SUMIF functions:

  =SUMIF(A2:A10,"Jan",C2:C10)+SUMIF(A2:A10,"Feb",C2:C10)

Sum of Sales where Month="Jan" AND Region="North"

For multiple criteria in different fields, the SUMIF function doesn't work. However, you can use an array formula. When you enter this formula, use Ctrl+Shift+Enter:

  =SUM((A2:A10="Jan")*(B2:B10="North")*C2:C10)

Sum of Sales where Month="Jan" AND Region<>"North"

Requires an array formula similar to the previous formula. When you enter this formula, use Ctrl+Shift+Enter:

  =SUM((A2:A10="Jan")*(B2:B10<>"North")*C2:C10)

Count of Sales where Month="Jan" AND Region="North"

For multiple criteria in different fields, the COUNTIF function doesn't work. However, you can use an array formula. When you enter this formula, use Ctrl+Shift+Enter:

  =SUM((A2:A10="Jan")*(B2:B10="North"))

Sum of Sales where Month="Jan" AND Sales>= 200

Requires an array formula similar to the previous example. When you enter this formula, use Ctrl+Shift+Enter:

  =SUM((A2:A10="Jan")*(C2:C10>=200)*(C2:C10))

Sum of Sales between 300 and 400

This also requires an array formula. When you enter this formula, use Ctrl+Shift+Enter:

  =SUM((C2:C10>=300)*(C2:C10<=400)*(C2:C10))

Count of Sales between 300 and 400

This also requires an array formula. When you enter this formula, use Ctrl+Shift+Enter:

  =SUM((C2:C10>=300)*(C2:C10<=400))

Excel provides many ways to count cells in a range that meet various criteria:

  • The DCOUNT function. The data must be set up in a table, and a separate criterion range is required.
  • The COUNT function. Simply counts the number of cells in a range that contain a number.
  • The COUNTA function. Counts the number of non-empty cells in a range.
  • The COUNTBLANK function. Counts the number of empty cells in a range.
  • The COUNTIF function. Very flexible, but often not quite flexible enough.
  • An array formula. Useful when the other techniques won't work.

Formula Examples

Listed below are some formula examples that demonstrate various counting techniques. These formula all use a range named data.

To count the number of cells that contain a negative number:

  =COUNTIF(data,"<0")

To count the number of cells that contain the word "yes" (not case sensitive):

   =COUNTIF(data,"yes")

To count the number of cells that contain any text:

   =COUNTIF(data,"*")

To count the number of cells that contain text that begins with the letter "s" (not case-sensitive):

   =COUNTIF(data,"s*")

To count the number of cells that contain the letter "s" (not case-sensitive):

   =COUNTIF(data,"*s*")

To count the number of cells that contain either "yes" or "no" (not case-sensitive):

   =COUNTIF(data,"yes")+COUNTIF(data,"no") 

To count the number of three-letter words:

   =COUNTIF(data,"???")

To count the number of cells that contain a value between 1 and 10:

   =COUNTIF(data,">=1")-COUNTIF(data,">10")

To count the number of unique numeric values (ignores text entries):

   =SUM(IF(FREQUENCY(data,data)>0,1,0))

To count the number of cells that contain an error value (this is an array formula, entered with Ctrl+Shift+Enter):

   =SUM(IF(ISERR(data),1,0))

Using the formulas in VBA

You can also use these techniques in your VBA code. For example the VBA statement below calculates the number of three-letter words in a range named data, and assigns the value to the NumWords variable:

  NumWords = Application.COUNTIF(Sheets("Sheet1").Range("data"), "???")

The other formula examples listed above can also be converted to VBA.

Most users have discovered that Excel has an option that lets you display formulas directly in their cells: Choose Tools Options, click the View tab, and select the Formulas checkbox. However, Excel doesn't provide a way to generate a concise list of all formulas in a worksheet. The VBA macro below inserts a new worksheet, then creates a list of all formulas and their current values.

NOTE: My Power Utility Pak add-in includes a more sophisticated version of this subroutine, plus several other auditing tools.

To use this subroutine:

  1. Copy the code below to a VBA module. You can also store it in your Personal Macro Workbook, or create an add-in.
  2. Activate the worksheet that contains the formulas you want to list.
  3. Execute the ListFormulas subroutine. The subroutine will insert a new worksheet that contains a list of the formulas and their values.

The ListFormulas Subroutine

Sub ListFormulas()
    Dim FormulaCells As Range, Cell As Range
    Dim FormulaSheet As Worksheet
    Dim Row As Integer
    
'   Create a Range object for all formula cells
    On Error Resume Next
    Set FormulaCells = Range("A1").SpecialCells(xlFormulas, 23)
    
'   Exit if no formulas are found
    If FormulaCells Is Nothing Then
        MsgBox "No Formulas."
        Exit Sub
    End If
    
'   Add a new worksheet
    Application.ScreenUpdating = False
    Set FormulaSheet = ActiveWorkbook.Worksheets.Add
    FormulaSheet.Name = "Formulas in " & FormulaCells.Parent.Name
    

'   Set up the column headings
    With FormulaSheet
        Range("A1") = "Address"
        Range("B1") = "Formula"
        Range("C1") = "Value"

        Range("A1:C1").Font.Bold = True
    End With
    
'   Process each formula
    Row = 2
    For Each Cell In FormulaCells
        Application.StatusBar = Format((Row - 1) / FormulaCells.Count, "0%")
        With FormulaSheet
            Cells(Row, 1) = Cell.Address _
                (RowAbsolute:=False, ColumnAbsolute:=False)
            Cells(Row, 2) = " " & Cell.Formula
            Cells(Row, 3) = Cell.Value
            Row = Row + 1
        End With
    Next Cell
    
'   Adjust column widths
    FormulaSheet.Columns("A:C").AutoFit
    Application.StatusBar = False
End Sub 

Naming Techniques

Posted by sato | 1:37 AM

Most Excel users know how to name cells and ranges. Using named cells and ranges can make your formulas more readable, and less prone to errors. Most users, however, don't realize that Excel lets you provide names for other types of items. This document describes some useful naming techniques that you may not be aware of.

Naming a constant

If formulas in your worksheet use a constant value (such as an interest rate), the common procedure is to insert the value for the constant into a cell. Then, if you give a name to the cell (such as InterestRate), you can use the name in your formulas. Here's how create a named constant that doesn't appear in a cell:

  1. Select the Insert Name Define command to display the Define Name dialog box.
  2. Enter the name (such as InterestRate) in the field labeled Names in workbook.
  3. Enter the value for the name in the Refers to field (this field normally holds a formula). For example, you can enter =.075.
  4. Click OK

Try it out by entering the name into a cell (preceded by an equal sign). For example, if you defined a name called InterestRate, enter the following into a cell:

  =InterestRate 

This formula will return the constant value that you defined for the InterestRate name. And this value does not appear in any cell.

Names are actually named formulas

Here's another way of looking at names. Whenever you create a name, Excel actually creates a name for a formula. For example, if you give a name (such as Amount) to cell D4, Excel creates a name for this formula:

  =$D$4 

You can use the Define Name dialog box and edit the formula for a name. And you can use all of the standard operators and worksheet functions. Try this:

  1. Create a name for cell D4. Call it Amount.
  2. Enter =Amount into any cell. The cell will display the value in cell D4.
  3. Use the Insert Name Define command and edit the refers to field so it appears as =$D$4*2

You'll find that entering =Amount now displays the value in cell D4 multiplied by 2.

Using relative references

When you create a name for a cell or range, Excel always uses absolute cell references for the range. For example, if you give the name Months to range A1:A12, Excel associates $A$1:$A$12 (an absolute reference) with the name Months. You can override the absolute references for a name and enter relative references. To see how this works, follow the steps below to create a relative name called CellBelow.

  1. Select cell A1.
  2. Select the Insert Name Define command to display the Define Name dialog box.
  3. Enter the name CellBelow in the field labeled Names in workbook.
  4. Replace the value in the Refers to field with =A2 (this is a relative reference)
  5. Click OK

Try it out by entering the following formula into any cell:

  =CellBelow 

You'll find that this formula always returns the contents of the cell directly below.

NOTE: It's important to understand that the formula you enter in Step 4 above depends on the active cell. Since cell A1 was the active cell, =A2 is the formula that returns the cell below. If, for example, cell C6 was the active cell when you created the name, you would enter =C7 in step 4.

Using mixed references

You can also used "mixed" references for you names. Here's a practical example of how to create a name that uses mixed references. This name, SumAbove, is a formula that returns the sum of all values above the cell.

  1. Activate cell A3.
  2. Select the Insert Name Define command to display the Define Name dialog box.
  3. In the Names in workbook field, enter SumAbove.
  4. In the Refers to field, enter =SUM(A$1:A2)

Notice that the formula in Step 3 is a mixed reference (the row part is absolute, but the column part is relative). Try it out by entering =SumAbove into any cell. You'll find that this formula returns the sum of all cells in the column from Row 1 to the row directly above the cell.

If you import data you might encounter time values stored as Unix timestamps. Unix time is defined as the number of seconds since midnight (GMT time) on January 1, 1970 -- also known as the Unix epoch.

For example, here's the Unix timestamp for August 4, 2008 at 10:19:08 pm (GMT):

1217888348

To create an Excel formula to convert a Unix timestamp to a readable data and time, start by converting the seconds to days. This formula assumes that the Unix timestamp is in cell A1:

=(((A1/60)/60)/24)

Then, you need to add the result to the date value for January 1, 1970. The modified formula is:

=(((A1/60)/60)/24)+DATE(1970,1,1)

Finally, you need to adjust the formula for the GMT offset. For example, if you're in New York the GMT offset is -5. Therefore, the final formula is:

=(((A1/60)/60)/24)+DATE(1970,1,1)+(-5/24)

A simpler (but much less clear) formula that returns the same result is:

=(A1/86400)+25569+(-5/24)

Both of these formulas return a date/time serial number, so you need to apply a number format to make it readable as a date and time.

Calculating Easter

Posted by sato | 1:36 AM

Easter is one of the most difficult holidays to calculate. Several years ago, a Web site had a contest to see who could come up with the best formula to calculate the date of Easter for any year. Here's one of the formulas submitted (it assumes that cell A1 contains a year):

=DOLLAR(("4/"&A1)/7+MOD(19*MOD(A1,19)-7,30)*14%,)*7-6

Just for fun, I calculated the date of Easter for 300 years from 1900 through 2199. Then I created a pivot table, and grouped the dates by day. And then, a pivot chart:

During this 300-year period, the most common date for Easter is March 31 (it occurs 13 times on that data). The least common is March 24 (only one occurrence). I also learned that the next time Easter falls on April Fool's Day will be in 2018.

A companion file is available: Click here to download

Many events are scheduled for a particular occurrence of the day within a month. For example, payday might be the last Friday of every month. Or, a meeting might be scheduled for every second Monday of the month.

Excel doesn't have a function that can calculate these types of dates, but it's possible to create a formula. In the figure below, the formula in cell D4 calculates the date based on the parameters in column C. The formula in D4 is:

=DATE(C3,C4,1+((C6-(C5>=WEEKDAY(DATE(C3,C4,1))))*7)+(C5-WEEKDAY(DATE(C3,C4,1))))

This formula is not always accurate, however. If you specify a day number that doesn't exist (for example, the 6th Friday), it returns a date in the following month.

Cell D6 contains a modified formula that displays "(none)" if the date isn't in the month specified. This formula is much longer:

=IF(MONTH(DATE(C3,C4,1+((C6-(C5>=WEEKDAY(DATE(C3,C4,1))))*7)+
(C5-WEEKDAY(DATE(C3,C4,1)))))<>C4,"(none)",DATE(C3,C4,1+
((C6-(C5>=WEEKDAY(DATE(C3,C4,1))))*7)+(C5-WEEKDAY(DATE(C3,C4,1)))))

In some cases, you might need to determine the last occurrence of a day in a particular month. This calculation requires a different formula (refer to the figure below):

=DATE(C9,C10+1,1)-1+IF(C11>WEEKDAY(DATE(C9,C10+1,1)-1),
C11-WEEKDAY(DATE(C9,C10+1,1)-1)-7,C11-WEEKDAY(DATE(C9,C10+1,1)-1))

In this figure, the formula in cell D10 displays the date of the last Friday in March, 2008.

The download file for this tip contains another example that has an easy-to-use interface. The user can select the parameters from drop-down lists. The megaformula in the Calculated Date column is very complex because it needs to covert words into values.

Excel's Data, Subtotals command inserts subtotal formulas into a list. This is a very useful command, but it's often difficult to identify the subtotal rows.

You may want to make the subtotal rows stand out by applying special formatting. However, this can't be done by any of Excel's autoformats. Use the outline controls on the left side of the workbook to collapse the outline so only the subtotal rows are visible. Press F5, select Visible Cells Only, and click OK. Then apply formatting to the selected cells.

When you expand the outline, only the subtotal rows will have the formatting you applied.

Excel's Insert - Comment command lets you annotate a cell by typing a comment. Once the comment is created, you can change its formatting. To do this, right-click the cell and select Edit Comment from the shortcut menu. When the comment is displayed, click anywhere on its border to select the entire comment object. Now you can use the standard toolbar buttons to change the font, text size, or colors.

To change the default formatting of your cell comments (so you don't have to repeat that process each time), you need to go outside Excel and use the Windows Display Settings dialog box. Excel uses the formatting specified for Windows' ToolTips (the text that appear when your pointer hovers near toolbar buttons).

You can access the Display Settings dialog box from the Control Panel. Or, you can right-click the desktop and choose Properties. Access the Appearance tab of the Display Properties dialog box, and select the ToolTip item. You can then modify the font, the font size, the background color, the foreground color, and the Bold and Italic attributes.

NOTE: If you're using Windows XP, you need to click the Advanced button in the Appearance tab of the Display Properties dialog box. This brings up the Advanced Appearance dialog box, where you can make the change.

Be aware that this will affect all comments that have not been formatting. If you've already applied formatting to a comment (for example, changed the background color), that comment will not be affected by this change.

Q. How can I make text in a cell display in multiple lines?

When entering text into the cell, press Alt-Enter to insert a line break.

When you do so, Excel will automatically apply text wrapping to the cell. To reformat existing cells so they sport wrapped text, select the cells and then choose Format, Cells. On the Alignment tab, select "Wrap text," and click OK.

Q. When I enter a value, it appears with two decimal places. For example, when I enter 154 it shows up as 1.54. What's wrong?

Somehow Excel's fixed-decimal mode was turned on. To return to normal, select Tools, Options to display the Options dialog box. Then click the Edit tab and remove the checkmark from the "Fixed decimal" option.

Of course, this feature can be useful when entering some types of data, but most of the time, you'll want to keep the fixed-decimal mode turned off.

Excel's conditional formatting feature (available in Excel 97 or later) offers an easy way to apply special formatting to cells if a particular condition is met. This feature is even more useful when you understand how to use a formula in your conditional formatting specification.

The worksheet below shows student grades on two tests. Conditional formatting highlights students who scored higher on the second test. This formatting is dynamic; if you change the test scores, the formatting adjusts automatically.

To apply conditional formatting, select range A2:C15 and choose Format, Conditional Formatting. The Conditional Formatting dialog box will appear with two input boxes. In the first box, choose Formula Is, pressTab, and enter the following formula:

=$C2>$B2

Click Format and choose a format to distinguish the cells (the example uses background shading). Click OK, and the formatting will be applied.

The conditional formatting formula is evaluated for each cell in the range. The trick here is to use mixed cell references (the column references are absolute, but the row references are relative). To see how this works, activate any cell within the range and choose Format, Conditional Formatting so you can examine the conditional formatting formula for that cell. You'll find that cell A7, for example, uses this formula:

=$C7>$B7

Some types of data, such as stock market quotes, normally display as fractions, not decimals. To enter a fraction in Excel, type the whole number (or integer) followed by a space, and then type the fraction, using a slash (for example, 5/8). If you type only a fraction, Excel may interpret it as a date (so it might read 5/8 as May 8). To avoid this mistranslation, enter 0, a space, and then the fraction.

When you enter a fractional value, Excel automatically applies a fraction number format that reduces it to the smallest possible denominator. For example, if you enter 16 2/8, Excel displays the number as 16 1/4. In some cases, however, you'll want the fractions to use a common denominator. For example, you might want the value 16 2/8 to be shown as 16 4/16. To obtain this result, select your cells and choose Format, Cells. Then select the Number tab and choose Fraction from the Category list. Finally, select the desired number format from the Type list.

The worksheet below shows some examples of numbers expressed as fractions. Column B shows the numbers produced using Excel's default formatting. Column C has the same values formatted as 16ths.

You can also express fractional data using a decimal point. For instance, the number 9 4/16 could appear as 9.04. Here, the digits to the right of the decimal represent 16ths. To display values in this format, use Excel's DOLLARFR() function. It's available only when the Analysis ToolPak is installed (select Tools, Add-ins to install it). The DOLLARFR() function takes two arguments: the number and an integer for the denominator. The formula =DOLLARFR(9.25,16), for example, returns 9.04.

This function is also useful for nondollar data. So, if you work with feet and inches, you can represent 11.5 feet as 11.06 (11 feet, 6 inches) by using this formula:

 =DOLLARFR(11.5,12)

The value will then appear as "11 [feet] 6 [inches]."

The DOLLARFR() function is for display only. You can't use the value it returns in other calculations or in charts. To perform calculations on such values, reconvert them into decimal values by using the DOLLARDE() function (also part of the Analysis ToolPak).

You may have discovered that Excel 2000 (and later versions) supports automatic cell hyperlinks. Whenever you type something that resembles a URL or an e-mail address into a cell, this feature automatically converts the text into a clickable hyperlink. But what if you don't want to create a hyperlink?

If you use Excel 2000, you're out of luck. There is no way to turn this potentially annoying feature off. But you can, however, override it. If Excel creates a hyperlink from your cell entry, click the Undo button (or press Ctrl-Z) to restore the cell's contents to normal text. Or, you can precede the cell entry with an apostrophe.

Note: If you're using Excel 2002 or later, you can turn automatic hyperlinks on or off in the AutoCorrect dialog box

Surprisingly, Excel doesn't provide a direct way to remove all hyperlinks on a worksheet. In fact, the only way to accomplish this is one cell at a time: Activate the cell that contains the hyperlink, right-click, and then select Hyperlink, Remove Hyperlink. Unfortunately, this command is available only when you have selected a single cell. To quickly deactivate all hyperlinks, you need to use a macro.

To create the macro, press Alt-F11 to activate the Visual Basic Editor, select Insert, Module to insert a new VBA module into your project, and then enter the following code:

Sub ZapHyperlinks() 
    Cells.Hyperlinks.Delete
End Sub

When you execute the ZapHyperlinks macro, all hyperlinks on the active sheet are deleted and replaced with normal text.

You've probably seen an Excel worksheet (like the sheet on the left, below) in which one entry in column A applies to several rows of data. Sort such a list and you get a real mess, because rows with empty cells in the sort column move to the top or bottom (depending on the sort order).

When a list is small, you can enter the missing cell values manually. But if your database is huge, you need a better way of filling in those cell values. Here's how:

  1. Select the range (A3:A14 in the example above)
  2. Press Ctrl-G to get the Go To dialog box.
  3. In the Go To dialog box, click Special.
  4. Select the Blanks option.
  5. Type = followed by the address of the first cell with an entry in the column (=A3 in the example above), and press Ctrl-Enter.
  6. Reselect the range and choose Edit, Copy.
  7. Then select Edit, Paste Special, choose the Values option, and click OK.

The missing entries will be filled in, as in the sheet on the right in the above figure.

One way to make your data legible is to apply cell shading to every other row in a range. Excel's Conditional Formatting feature (available in Excel or later) makes this a simple task.

  1. Select the range that you want to format
  2. Choose Format, Conditional Formatting
  3. In the Conditional Formatting dialog box, select Formula Is from the drop-down list, and enter this formula:
    =MOD(ROW(),2)=0
  4. Click the Format button, select the Patterns tab, and specify a color for the shaded rows.
  5. Click OK twice to return to your worksheet.

The best part is that the row shading is dynamic. You'll find that the row shading persists even if you insert or delete rows within the original range.

Excel's Conditional Formatting feature has many uses. Suppose you need to compare two lists, and identify the items that are different. The figure below shows an example. These lists happen to contain text, but this technique also works with numeric data.

The first list is in A2:B19, and this range is named OldList. The second list is in D2:E19, and the range is named NewList. The ranges were named using the Insert - Name - Define command. Naming the ranges is not necessary, but it makes them easier to work with.

As you can see, items in OldList that do not appear in NewList are highlighted with a yellow background. Items in NewList that do not appear in OldList are highlighted with a green background. These colors are the result of Conditional Formatting.

How to do it

  1. Start by selecting the OldList range.
  2. Choose Format - Conditional Formatting
  3. In the Conditional Formatting dialog box, use the drop-down list to choose Formula is.
  4. Enter this formula:
    =COUNTIF(NewList,A2)=0
  5. Click the Format button and specify the formatting to apply when the condition is true (a yellow background in this example).
  6. Click OK

The cells in the NewList range will use a similar conditional formatting formula.

  1. Select the NewList range.
  2. Choose Format - Conditional Formatting
  3. In the Conditional Formatting dialog box, use the drop-down list to choose Formula is.
  4. Enter this formula:
    =COUNTIF(OldList,D2)=0
  5. Click the Format button and specify the formatting to apply when the condition is true (a green background in this example).
  6. Click OK

Both of these conditional formatting formulas use the COUNTIF function. This function counts the number of times a particular value appears in a range. If the formula returns 0, it means that the item does not appear in the range. Therefore, the conditional formatting kicks in and the cell's background color is changed.

The cell reference in the COUNTIF function should always be the upper left cell of the selected range.

A companion file is available: Click here to download

I got lots of Excel workbooks via email. A significant number of them have some downright ugly color choices. Beauty is in the eye of the beholder, but there's no excuse for making color choices that result in illegible text.

The World Wide Web Consortium (W3C) has created some formulas that can help you determine if your foreground and background colors are legible: Ensure that foreground and background color combinations provide sufficient contrast when viewed by someone having color deficits or when viewed on a black and white screen.

The W3C presents two formulas, each of which returns a value:

  • Color Brightness Difference: returns a value between 0 and 255
  • Color Difference: Returns a value between 0 and 765

I converted their formulas into VBA functions, and formulas that use these functions are shown in Columns B and C:

To be an acceptable color combination, the Color Difference score should be 500 or greater, and the Brightness Difference score should be 125 or greater. I used conditional formatting to highlight values that exceed these minimums.

Column D has a simple formula that determines if both score meet the minimum requirement.

These formulas seem to work quite well. The color combination deemed Acceptable are all very legible. Bottom line: You can't go wrong with black text on a white background. Reserve the fancy colors for column headers, or for special areas of a worksheet that you want to be noticed.

A companion file is available: Click here to download

Many users are surprised to discover that Excel cannot work with dates prior to the year 1900. I create an add-in that addresses this deficiency. The Extended Date Functions add-in (XDate) allows you to work with dates in the years 0100 through 9999.

When the XDate add-in is installed, you can use any of the following new worksheet functions in your formulas:

  • XDATE(y,m,d,fmt): Returns a date for a given year, month, and day. As an option, you can provide a date formatting string.
  • XDATEADD(xdate1,days,fmt): Adds a specified number of days to a date. As an option, you can provide a date formatting string.
  • XDATEDIF(xdate1,xdate2): Returns the number of days between two dates.
  • XDATEYEARDIF(xdate1,xdate2): Returns the number of full years between two dates (useful for calculating ages).
  • XDATEYEAR(xdate1): Returns the year of a date.
  • XDATEMONTH(xdate1): Returns the  month of a date.
  • XDATEDAY(xdate1): returns the day of a date.
  • XDATEDOW(xdate1): Returns the day of the week of a date (as an integer between 1 and 7).

These are all VBA functions.

Applications:

The XDate add-in is particularly useful for genealogists and others who need to perform simple calculations using pre-1900 dates. The figure below, for example, shows the XDATEYEARDIF function being used to calculate ages.

Requirements:

The XDate add-in requires Excel 97 or later.

Limitations:

Be careful if you use dates prior to 1752. Differences between the historical American, British, Gregorian, and Julian calendars can result in inaccurate computations.

Note:

My Power Utility Pak also includes the XDATE functions. However, they are not packaged in an add-in. Rather, you can add the functions directly to the VBA project for your workbook. As a result, you can distribute the workbook without a dependent add-in.

Documentation:

Complete context-sensitive online help is included.

Installation:

Installation is a two-step process:

  1. Extract the files
    Download and execute the xdate.zip file. Extract the files into any directory.
  2. Install the add-in
    Start Excel and select the Tools - Add-Ins command. In the Add-Ins dialog box, click the Browse button and locate xdate.xla (the file you extracted in Step #2). Click OK.

You can type the functions manually, or use Excel's Paste Function dialog box. To access the Paste Function dialog, click the Paste Function button, or select Insert - Function.  The XDate Functions are listed in the 'Date & Time' Category. When a function is selected in the Paste Function dialog, press F1 to read the online help.

The topic of "protecting" a spreadsheet receives a great deal of attention in the Excel newsgroups. This document provides answers to some common questions.

Excel provides three primary ways to protect information in a spreadsheet:

NOTE: This document was written prior to the release of Excel 2007.

Worksheet Protection

Questions in this section deal with protecting the contents of cells and objects on a worksheet.

How do I protect a worksheet?

Activate the worksheet to be protected, then choose Tools - Protection - Protect Sheet. You will be asked to provide a password (optional). If you do provide a password, that password will be required to unprotect the worksheet.

I tried the procedure outlined above, and it doesn't let me change any cells! I only want to protect some of the cells, not all of them.

Every cell has two key attributes: Locked and Hidden. By default, all cells are locked, but they are not hidden. Furthermore, the Locked and Hidden attributes come into play only when the worksheet is protected. In order to allow a particular cell to be changed when the worksheet is protected, you must unlock that cell.

How do I unlock a cell?

  1. Select the cell or cells that you want to unlock.
  2. Choose Format - Cells
  3. In the Format Cells dialog box, click the Protection tab
  4. Remove the checkmark from the Locked checkbox.

Remember: Locking or unlocking cells has no effect unless the worksheet is protected.

How do I hide a cell?

  1. Select the cell or cells that you want to unlock.
  2. Choose Format - Cells
  3. In the Format Cells dialog box, click the Protection tab
  4. Add a checkmark to the Hidden checkbox.

Remember: Changing the Hidden attribute of a cell has no effect unless the worksheet is protected.

I made some cells hidden and then protected the worksheet. But I can still see them. What's wrong?

When a cell's Hidden attribute is set, the cell is still visible. However, it's contents do not appear in the Formula bar. Making a cell Hidden is usually done for cells that contain formulas. When a formula cell is Hidden and the worksheet is protected, the user cannot view the formula.

I protected my worksheet, but now I can't even do simple things like sorting a range. What's wrong?

Nothing is wrong. That's the way worksheet protection works. Unless you use Excel 2002 or later.

How is worksheet protection different in Excel 2002 and later?

Excel 2002 and later provides you with a great deal more flexibility when protecting worksheets. When you protect a worksheet using Excel 2002 or later, you are given a number of options that let you specify what the user can do when the worksheet is protected:

  • Select locked cells
  • Delete columns
  • Select unlocked cells
  • Delete rows
  • Format cells
  • Sort
  • Format columns
  • Use AutoFilter
  • Format rows
  • Use PivotTable reports
  • Insert columns
  • Edit objects
  • Insert rows
  • Edit scenarios
  • Insert hyperlinks

Why aren't these options available in earlier versions of Excel?

Good question. Only Microsoft knows for sure. The limitations of protected worksheets have been known (and complained about) for a long time. For some reason, Microsoft never got around to addressing this problem until Excel 2002.

Can I lock cells such that only specific users can modify them?

Yes, but it requires Excel 2002 or later.

How can I find out more about the protection options available in Excel 2002 or later?

Start with Excel's Help system. If you're a VBA programmer, you may be interested in this MSDN article that discusses the Protection object.

Can I set things up so my VBA macro can make changes to Locked cells on a protected sheet?

Yes, you can write a macro that protects the worksheet, but still allows changes via macro code. The trick is to protect the sheet with the UserInterfaceOnly parameter. Here's an example:

ActiveSheet.Protect UserInterfaceOnly:=True

After this statement is executed, the worksheet is protected -- but your VBA code will still be able to make changes to locked cells and perform other operation that are not possible on a protected worksheet.

If I protect my worksheet with a password, is it really secure?

No. Don't confuse protection with security. Worksheet protection is not a security feature. Fact is, Excel uses a very simple encryption system for worksheet protection. When you protect a worksheet with a password, that password -- as well as many others -- can be used to unprotect the worksheet. Consequently, it's very easy to "break" a password-protected worksheet.

Worksheet protection is not really intended to prevent people from accessing data in a worksheet. If someone really wants to get your data, they can. If you really need to keep your data secure, Excel is not the best platform to use.

So are you saying that protecting a worksheet is pointless?

Not at all. Protecting a worksheet is useful for preventing accidental erasure of formulas. A common example is a template that contains input cells and formulas that calculate a result. Typically, the formula cells would be Locked (and maybe Hidden) the input cells would be Unlocked, and the worksheet would be protected. This helps ensure that a novice user will not accidentally delete a formula.

Are there any other reasons to protect a worksheet?

Protecting a worksheet can also facilitate data entry. When a worksheet is locked, you can use the Tab key to move among the Unlocked cells. Pressing Tab moves to the next Unlocked cell. Locked cells are skipped over.

OK, I protected my worksheet with a password. Now I can't remember the password I used.

First, keep in mind that password are case-sensitive. If you entered the password as xyzzy, it won't be unprotected if you enter XYZZY.

Here's a link to a VBA procedure that may be able to derive a password to unprotect the worksheet. This procedure has been around for a long time, and is widely available -- so I don't have any qualms about reproducing it here. The original author is not known.

If that fails, you can try one of the commercial password-breaking programs. I haven't tried any of them, so I have no recommendations.

How can I hide a worksheet so it can't be unhidden?

You can designate a sheet as "very hidden." This will keep the average user from viewing the sheet. To make a sheet very hidden, use a VBA statement such as:

Sheets("Sheet1").Visible = xlVeryHidden

A "very hidden" sheet will not appear in the list of hidden sheets, which appears when the user selects Format - Sheet - Unhide. Unhiding this sheet, however, is a trivial task for anyone who knows VBA.

Can I prevent someone from copying the cells in my worksheet and pasting them to a new worksheet?

Probably not. If someone really wants to copy data from your worksheet, they can find a way.

Workbook Protection

Questions in this section deal with protecting workbooks.

What types of workbook protection are available?

Excel provides three ways to protect a workbook:

  • Require a password to open the workbook
  • Prevent users from adding sheets, deleting sheets, hiding sheets, and unhiding sheets
  • Prevent users from changing the size or position of windows

How can I save a workbook so a password is required to open it?

Choose File - Save As. In the Save As dialog box, click the Tools button and choose General Options to display the Save Options dialog box, in which you can specify a password to open the file. If you're using Excel 2002, you can click the Advanced button to specify encryption options (for additional security). Note: The exact procedure varies slightly if you're using an older version of Excel. Consult Excel's Help for more information.

The Save Options dialog box (described above) also has a "Password to modify" field. What's that for?

If you enter a password in this field, the user must enter the password in order to overwrite the file after making changes to it. If the password is not provided, the user can save the file, but he/she must provide a different file name.

If I require a password to open my workbook, is it secure?

It depends on the version of Excel. Password-cracking products exist. These products typically work very well with versions prior to Excel 97. But for Excel 97 and later, they typically rely on "brute force" methods. Therefore, you can improve the security of your file by using a long string of random characters as your password.

How can I prevent a user for adding or deleting sheets?

You need to protect the workbook's structure. Select Tools - Protection - Protect Workbook. In the Protect Workbook dialog box, make sure that the Structure checkbox is checked. If you specify a password, that password will be required to unprotect the workbook.

When a workbook's structure is protected, the user may not:

  • Add a sheet
  • Delete a sheet
  • Hide a sheet
  • Unhide a sheet
  • Rename a sheet
  • Move a sheet

How can I distribute a workbook such that it can't be copied?

You can't.

VB Project Protection

How can I prevent others from viewing or changing my VBA code?

If you use Excel 97 or later... Activate the VB Editor and select your project in the Projects window. Then choose Tools - xxxx Properties (where xxxx corresponds to your Project name). In the Project Properties dialog box, click the Protection tab. Place a checkmark next to Lock project for viewing, and enter a password (twice). Click OK, then save your file. When the file is closed and then re-opened, a password will be required to view or modify the code.

Is my add-in secure?

The type of VB Project protection used in Excel 97 and later is much more secure than in previous versions. However, several commercial password-cracking programs are available. These products seem to use "brute force" methods that rely on dictionaries of common passwords. Therefore, you can improve the security of your file by using a long string of random characters as your password.

Can I write VBA code to protect or unprotect my VB Project?

No. The VBE object model has no provisions for this -- presumably an attempt to thwart password-cracking programs. It may be possible to use the SendKeys statement, but it's not completely reliable.

A companion file is available: Click here to download

I created an add-in that displays a new CommandBar that functions as a simple calculator. It may not be the most useful tool (it's limited to only the four basic mathematical operations), and I'll be the first to admit that it's fairly ugly. But it does demonstrate some useful VBA programming techniques.

The code is too lengthy to list here, but the VBA project for the add-in file is not protected so you can examine it.

NOTE: This add-in does not work with Excel 2007.

Installation:

  1. Download the Toolbar Calculator add-in
  2. Start Excel and select the Tools - Add-Ins command. 
  3. In the Add-Ins dialog box, click the Browse button and locate calctoolbar.xla.
  4. Click OK
  5. The toolbar will appear
  6. Select Tools - Toolbar Calculator to toggle the toolbar on and off.

Many users are surprised to discover that Windows does not provide a direct way to get a list of file names contained in a directory. This tip describes how to create such a list in a text file, which can then be imported into Excel.

To generate a list of file names, you'll need to use a DOS command typed in a DOS command window. To open a DOS command window:

  1. Click the Windows Start button
  2. Click Run
  3. Type "cmd" (no quotes) and press Enter. if "cmd" doesn't work, use "command".

You'll get a window like the one shown below.

Next, you need to type a DOS command to generate the file list. For example, if you would like to generate a list of all files in the root directory of drive D, type the following at the command prompt and press Enter:

dir d:\

To list the files in a particular directory, add the directory name after the drive:

dir d:\my files\

The file names will be listed in the window. Usually, you'll want these files to be sent to a file. To redirect the output to a file, use the > character and specify a file name. For example, to send the file names to a text file named filelist.txt in the root directory of drive C, use this command:

dir d:\ >c:\filelist.txt

If you would like the file list to include the files in all subdirectories of drive D, use the /s switch:

dir d:\ /s >c:\filelist.txt

The directory listing will contain lots of additional information. To get the file names only (bare format), use the /b switch:

dir d:\ /s /b >c:\filelist.txt

To find out about other options available for the DIR command (such as including file dates and times), type this command:

dir /?

After the text file is generated, you can import it into Excel by using the File - Open command.

NOTE: If you need do this on a regular basis, you may be interested in this article from Microsoft, which describes how to create a batch file that lists file names in Notepad.

This document describes the solution to several common problems involving Excel setup.

Excel crashes when it starts

When Excel is started, it opens an *.xlb file, which contains your menu and toolbar customizations. If this file is damaged, it may cause Excel to crash when it it started. Also, this file may (for some reason) be very large. In such a case, this may also cause Excel to crash. Typically, your *.xlb file should be 500K or smaller.

If Excel crashes when it is started, try deleting your *.xlb file. To do so:

  1. Close Excel
  2. Search your hard drive for *.xlb. The filename and location will vary.
  3. Create a backup copy of this file and then delete the file.
  4. Re-start Excel. Hopefully, Excel will now start up normally.

NOTE: Deleting your *.xlb file will also delete any toolbar or menu customizations.

Many documents open automatically

If Excel automatically opens lots of files at start-up, here are two things to check:

  1. Your XLStart directory. Files stored in your XLStart directory are opened automatically when Excel starts. Move the files in this folder to a different folder.
  2. Your Alternate startup directory. Select Tools - Options. In the Options dialog box, click the General tab. Locate the setting called At startup, open all files in. If this field is not empty, delete its contents.

Excel's menus are messed up

If your menus change, or if there is a delay before all menu items are not listed, you need to make a change.

  1. Select View - Toolbars - Customize.
  2. In the Customize dialog box, click the Options tab.
  3. Place a checkmark next to the item labeled Always show full menus.

NOTE: This is, without a doubt, the dumbest option ever created! Why would anyone want their menus to change?

Commands are missing from the menu

If the steps in the preceding section don't solve the problem, you can reset Excel's menu bar:

  1. Select View - Toolbars - Customize.
  2. In the Customize dialog box, click the Toolbars tab.
  3. Scroll down the Toolbars list and select Worksheet Menu Bar.
  4. Click the Reset button

NOTE: This will return the menu to its default state, and destroy any menu customizations that may have been done.

Excel displays extraneous menu commands

Another common problem is extraneous menu items. For example, you may have used an add-in that added a new menu item to the Tools menu. And, for whatever reason, the add-in did not remove that menu item. To remove the menu item:

  1. Select View - Toolbars - Customize
  2. When the Customize dialog box is displayed, access the extraneous menu item and "drag it away." That will delete it.
  3. Click OK to close the Customize dialog box.

Double-clicking an Excel file does not work

Normally, double-clicking an XLS file starts Excel and opens that file. If this doesn't work for you, you'll need to re-register Excel. Do do so:

  1. Close Excel
  2. Click the Windows Start button
  3. Click Run, to display the Run dialog box
  4. Type the following, and click OK:
    excel / regserver
  5. You'll see a message box that display the progress. When the message box closes, Excel should be back to normal.

You get a macro warning when no macros exist

When you open a workbook, you may be prompted to enable or disable macros --even though no macros exist in the workbook. Press Alt+F11 to activate the Visual Basic Editor. Locate your workbook in the projects window:

  1. If the workbook contains any VBA modules (for example, Module1), delete the module. Even an empty VBA module may trigger the macro warning.
  2. Examine the code modules to ThisWorkbook, and the code module for each Sheet (for example, Sheet1). Make sure that these modules do not contain any macro code. You cannot delete these code module, but they must be empty to avoid the macro warning dialog box.

You get an erroneous "file is being edited by" message

When you open a file that is in use, you'll get a message that tells you the file must be opened in read-only mode. In some cases, you may get this message even though the file is definitely not in use. This can be caused by an Excel crash, in which the file was not released. The only way around it is to re-start Windows.

Numbers are entered with the wrong number of decimal places

For example, entering 154 appears as 1.54 in the cell. Somehow Excel's fixed-decimal mode was turned on. To return to normal:

  1. Select Tools - Options to display the Options dialog box.
  2. Click the Edit tab
  3. Remove the checkmark from the Fixed decimal option.

Of course, this feature can be useful when entering some types of data, but most of the time, you'll want to keep the fixed-decimal mode turned off.

Numbers, not letters appear in the column header

Normally, Excel columns are labeled with letters. If they actually appear as numbers, you can change it back to the default:

  1. Select Tools - Options to display the Options dialog box.
  2. Click the General tab
  3. Remove the checkmark from the R1C1 reference style option.