11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

A Multifunctional Function<br />

Chapter 25: VBA Custom Function Examples 677<br />

This section demonstrates a technique that may be helpful in some situations — the technique of<br />

making a single worksheet function act like multiple functions. The following VBA custom function,<br />

named STATFUNCTION, takes two arguments — the range (rng) and the operation (op).<br />

Depending on the value of op, the function returns a value computed by using any of the following<br />

worksheet functions: AVERAGE, COUNT, MAX, MEDIAN, MIN, MODE, STDEV, SUM, or VAR.<br />

For example, you can use this function in your worksheet:<br />

=STATFUNCTION(B1:B24,A24)<br />

The result of the formula depends on the contents of cell A24, which should be a string, such as<br />

Average, Count, Max, and so on. You can adapt this technique for other types of functions.<br />

Function STATFUNCTION(rng As Variant, op As String) As Variant<br />

Select Case UCase(op)<br />

Case “SUM”<br />

STATFUNCTION = Application.Sum(rng)<br />

Case “AVERAGE”<br />

STATFUNCTION = Application.Average(rng)<br />

Case “MEDIAN”<br />

STATFUNCTION = Application.Median(rng)<br />

Case “MODE”<br />

STATFUNCTION = Application.Mode(rng)<br />

Case “COUNT”<br />

STATFUNCTION = Application.Count(rng)<br />

Case “MAX”<br />

STATFUNCTION = Application.Max(rng)<br />

Case “MIN”<br />

STATFUNCTION = Application.Min(rng)<br />

Case “VAR”<br />

STATFUNCTION = Application.Var(rng)<br />

Case “STDEV”<br />

STATFUNCTION = Application.StDev(rng)<br />

Case Else<br />

STATFUNCTION = CVErr(xlErrNA)<br />

End Select<br />

End Function<br />

Figure 25-2 shows the STATFUNCTION function that is used in conjunction with a drop-down list<br />

generated by Excel’s Data➜Data Tools➜Data Validation command. The formula in cell C14 is as<br />

follows:<br />

=STATFUNCTION(C1:C12,B14)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!