You are on page 1of 6

1

Programming 1
User Defined Functions (UDF’s) - one glitch and one inconvenience!

Anyone who has experimented with UDF’s in any version of Excel later than Excel 5 will have
noticed two annoying features. These will be looked at first before we do any more advanced
work.

The Glitch

Open Excel and centre align all Cells.


In Cell B6 type ‘x’ and from B8 to B21 fill with a range of integers from –3 to 10.
Highlight Cells B6 to B21 and select Insert ⎢ Name ⎢ Create, etc, to name the range ‘x’.
In Cell A3 type h and in Cell A4 type 0, then highlight Cells A3 to A4 and select Insert ⎢ Name ⎢
Create, etc, to name the Cell ‘h’.

Next, select File ⎢ SaveAs, and type “glitch1”. Save to your floppy disk.
In Cells C6 to G6 type in ‘a’ to ‘e’, one to each Cell.
In C8 type = x^3 – 4*x^2 + 4/(x + 5) , and press Return. This should give a Cell output of - 61.
Next, double click on the fill handle button of Cell C8 to automatically fill the ‘a’ column.

Note that, if you instead have a column of - 61’s then your worksheet will still be in
the ‘Manual Calculation’ Mode. If you wish to reset to ‘Automatic Calculation’ Mode
then select Tools ⎢ Options ⎢ Calculation Tab, and then click in the “Automatic” option
followed by OK. If you do not wish to change back then simply press the Special
Function Key F9 once – but I suggest that you do change back.

Now, select File ⎢ SaveAs, and type “glitch1a”. Save to your floppy disk.

Next, press Alt+Special Function Key F11, that is, Alt+F11. This opens up the Visual Basic for
Applications (VBA) window into which we are now going to write the previous function.
Select Insert ⎢ Module, this opens up a window into which we type the following code:

(Recall that the editor will fill much of this code in automatically – provided we press either the
Return or Tab buttons at the appropriate moment.)

Function f(x As Single) As Single


f = x ^ 3 - 4 * x ^ 2 + 4 / (x + 5)
End Function

Click on the Excel Icon in the Standard Toolbar to return to the Excel worksheet and now in Cell
D8 type in = f(x) , and press Return. What will be shown is the error message “#VALUE”.
Regardless of this error, double click on the fill handle of the Cell to fill down the formula.
Next, in Cell B4 type = f(h) , and press Return. This time you should have the value 0.8 in the
Cell (If you once again have “#VALUE” then it may be because you didn’t alter the argument to
the function f( ) from ‘x’ to ‘h’)
Repeat this previous operation but instead in Cell C24. It should again give 0.8. Thus, single
Named Cells experience no problems with User Defined Functions (UDF’s)
2

First ‘Fixit’

In Cell E8 type in =f(VALUE(x)) , and press Return (Upper case is not necessary) and double
click on the fill handle of the Cell to fill down the formula. This works, but it is neither
particularly succinct nor mathematically clear.

Second ‘Fixit’

In Cell F8 type in = f(x+0) , and press Return and double click on the fill handle of the Cell to fill
down the formula. This works but again it could be mathematical confusing.

Third ‘Fixit’

In Cell G8 type in = f(x + h) , and press Return and double click on the fill handle of the Cell to
fill down the formula. This works and gives the correct answer to what we expect of f(x) (because
at present h is set equal to zero). Now this may not be exactly what we were after BUT the fact
that the combination of a Named Range of values with a Named Cell put into the argument of our
UDF will have much use later on, and will then have greater mathematical meaning. Recall setting
up the Central Derivative Module from page 11 in the “Named Ranges 3” exercise. In that case
the UDF was acting on a single Cell and not a Range of Cells. We now know that such a UDF can
also return values from a Range of Cells.

Notice that f(1*x), f(2*x), f(x/5), etc, or f(p*x), f(x/q), etc, would also return full range values
for appropriate choices of p and q – useful for transformation graphs.

Therefore, at present I suggest that you actually type in the function in terms of x as you have done
in column C and then copy this formula down. Then a click on any Cell in this range will show
you the mathematical form of the function in the formula bar, in this case = x^3-4*x^2+4/(x+5).
Next, open the VBA editor with Alt+F11 and define the same function in a module, and then this
will be what you use in later work in the worksheet (Provided that you will be using an argument
to the function other than a sole ‘x’ – as has been discussed in depth above).

Recall again that for a single, Named Cell rather than a Named Range of Cells then the straight
forward Cell entry of = f(x) will evaluate the function correctly without either of the above ‘fixes’

The Inconvenience

Open Excel, Centre align all Cells.


Select File ⎢ SaveAs, and type “vba_func”. Save to your floppy disk.
In Cell B4 type x, and in B5 type in the value 2. Give this data Cell the Name x.
In Cell C5 type = ACosh(x) + x –3, and press Return, the cell should have the value 0.316958.

Next, press Alt+Special Function Key F11, that is, Alt+F11. This opens up the Visual Basic for
Applications (VBA) window into which we are now going to write the previous function.
Select Insert ⎢ Module, this opens up a window into which we type the following code:

Function f(x As Single) As Single


f = ACosh(x) + x -3
End Function
3
Click on the Excel Icon in the Standard Toolbar to return to the Excel worksheet and now in Cell
D5 type = f(x) , and press Return. What will be shown is the following error message below.

The cause of this problem is that the VBA language does not know what the ArcCosh of x means,
unlike the actual Excel worksheet. In fact VBA has a surprisingly sparse collection of known
mathematical functions ‘pre-programmed’ in to it. To see a listing of available VBA mathematical
functions first get into the VBA screen using Alt+F11, then anywhere on an open (module)
window type vba.math. , and on typing in the last period (full stop!) you will have the available
functions displayed in a ‘pop-up’ list. As you will see things are rather limited, however, where
there is a will there is a way!

The listing on the next page gives many useful mathematical functions re-written in terms of some
of the available VBA functions. Note that in an expression such as:

Arccosh = Log(x + Sqr(x * x - 1)),


I have deliberately left out the argument of the actual function. This is due to how it must be
implemented in the VBA Module code. For example, consider the Module code given below, both
of which output the same value, that of cosh −1 (x) or arc cosh ( x) :

Function f(x As Single) As Single or Function f(x As Single) As Single


Arccosh = Log(x + Sqr(x * x - 1)) f = Log(x + Sqr(x * x - 1)) + x - 3
f = Arccosh + x – 3 End Function
End Function

I think that the first is preferable since we are reminded exactly which function we are using.

Now rewrite your previous module code to be either of the previous two and before returning back
to the Excel worksheet either select Run ⎢ Reset, or simply click on the small blue square on the
toolbar. The purpose of this action is to enter your changes and stop the Editor’s Debug mode. On
returning to the worksheet, make sure that your answer is identical to that in C5. Save your file.
4

Construction of functions based on VBA functions

Sec = 1 / Cos(x)
Cosec = 1 / Sin(x)
Cotan = 1 / Tan(x)
Arcsin = Atn(x / Sqr(-x * x + 1))
Arccos = Atn(-x / Sqr(-x * x + 1)) + 2 * Atn(1)
Arcsec = Atn(x / Sqr(x * x - 1)) + Sgn((x) - 1) * (2 * Atn(1))
Arccosec = Atn(x / Sqr(x * x - 1)) + (Sgn(x) - 1) * (2 * Atn(1))
Arccotan = Atn(x) + 2 * Atn(1)
Sinh = (Exp(x) - Exp(-x)) / 2
Cosh = (Exp(x) + Exp(-x)) / 2
Tanh = (Exp(x) - Exp(-x)) / (Exp(x) + Exp(-x))
Sech = 2 / (Exp(x) + Exp(-x))
Cosech = 2 / (Exp(x) - Exp(-x))
Cotanh = (Exp(x) + Exp(-x)) / (Exp(x) - Exp(-x))
Arcsinh = Log(x + Sqr(x * x + 1))
Arccosh = Log(x + Sqr(x * x - 1))
Arctanh = Log((1 + x) / (1 - x)) / 2
Arcsech = Log((Sqr(-x * x + 1) + 1) / x)
Arccosech = Log((Sgn(x) * Sqr(x * x + 1) + 1) / x)
Arccotanh = Log((x + 1) / (x - 1)) / 2
LogN = Log(x) / Log(n)

Note that not all of the above functions are available as standard functions in Excel either. To find
out which are first change to the Excel workbook and then click on any clear Cell and then select
Insert ⎢ Function. This will display the “Paste Function” Dialogue Box, as shown below. Then
choose “Math & Trig” and scroll through the
available functions. Those that aren’t in the list, such
as cosech -1 ( x) , etc, can either be inputted as a UDF,
as described above, or as the corresponding
equivalent form:
Log((Sgn(x) * Sqr(x * x + 1) + 1) / x)
But, notice the following necessary alterations for use
within the Excel workbook rather than for VBA, viz:
Log((Sign(x) * Sqrt(x * x + 1) + 1) / x)
since the Excel workbook has different ‘calls’ for the
same function – confused yet? Personally I would go
for a UDF to clarify the working.
5
The Application.WorksheetFunction

Before you begin to think that having to know all and more of the above formulae constructions is
completely beyond you Excel has a very simple, albeit wordy way of ‘grabbing’ any functions
found in the Excel Worksheet and putting them into VBA code. The above module code for the
ArcCosh function would instead need to be written:

Function f(x As Double) As Double


f = Application.WorksheetFunction.Acosh (x)
End Function

Notice now that the worksheet function ‘Acosh’ must have its argument set as a double-precision,
floating-point number.

The importance of this seemingly innocuous example cannot be overstated; the


Application.WorksheetFunction in your code should almost always be used. The
reasoning being that your own attempts at designing a suitable function, though
admirable, will almost always cause your code to run slower and may also contain
mistakes.

Notice that when you are typing the phrase “Application.WorksheetFunction.Acosh(x)” then you
will actually only need to type the final ‘(x)’ believe it or not! – see the stages below!

(1) Right click after the ‘=’ sign. (2) Scroll down to the word ‘Application’
Click on either “List Properties/Methods” and either select it and press the ‘Tab’
or “Complete Word” button or double click it.
6
(3) Next type a period “.” , this will open
another drop-down menu. Now either
scroll down or just type ‘w’ – this will
automatically scroll you down to the
start of the options that begin with the
letter ‘w’. Again, either select the
required option: ‘WorksheetFunction’
and then press the ‘Tab’ button or
double click the required option.

(4) Again type a period “.” , this will open


another drop-down menu. Similarly,
either select the required option:
‘Acosh’ and then press the ‘Tab’
button or double click the required
option.

(5) Now type the opening bracket and notice the information box that appears. It gives
you important information regarding how many arguments the function can accept
and what type of arguments must be used.

(6) Finally type in your functions dummy argument – it need not be x – and close the
bracket.
Thus only (x) needed to be typed!!

Finally, be aware that there will be times when you have to write your own custom function,
possibly because it is neither present in the Excel Worksheet or the VBA function lists. A simple
mathematical example is the Hyperbolic Secant. Here then, the Table on Page 4 above is of use.

You might also like