This article describes a technique that may be helpful in some situations – making a single worksheet function act like multiple functions. For example, the VBA listing below is for a custom function called StatFunction. It takes two arguments: the range (rng), and the operation (op). Depending on the value of op, the function will return any of the following: AVERAGE, COUNT, MAX, MEDIAN, MIN, MODE, STDEV, SUM, or VAR.
For example, you can use this function in your worksheet as follows:
The result of the formula depends on the contents of cell A24 — which should be a string such as Average, Count, Max, etc. You can adapt this technique for other types of functions.
The StatFunction Function
Function STATFUNCTION(rng, op)
Select Case UCase(op)
STATFUNCTION = Application.Sum(rng)
STATFUNCTION = Application.Average(rng)
STATFUNCTION = Application.Median(rng)
STATFUNCTION = Application.Mode(rng)
STATFUNCTION = Application.Count(rng)
STATFUNCTION = Application.Max(rng)
STATFUNCTION = Application.Min(rng)
STATFUNCTION = Application.Var(rng)
STATFUNCTION = Application.StDev(rng)
STATFUNCTION = Evaluate("NA()")