885 User-Defi ned Functions with VBA
Note that we used Application.Combin(n, x) to compute
n
x
()
in our
function. As you might guess from its name (Application.Something),
this function is the Excel worksheet function Combin(). Most, but not
all,
4
Excel worksheet functions can be used in VBA in exactly the same
way. Some examples will be given in subsequent parts of this section. For
a complete list see the Help fi le.
One more thing to notice is the underscore ( _ ) preceded by a space
at the end of line 2. If a line gets too long to deal with,
5
it can be contin-
ued on the next line using this contraption (the second and third lines
of Binomial are one line as far as VBA is concerned).
Suppose we try to use our Binomial function to calculate Bino-
mial(0.5,10,15). This attempt won’t work:
1
2
3
4
5
AB C
0p.5
1n0
1x5
Binomial #VALUE! <-- =Binomial(B2,B3,B4)
THE BINOMIAL FUNCTION
4. When an equivalent function is available as a native VBA function, the corresponding
Excel function is not available in VBA. For example, in VBA use rnd() and not Appli-
cation.Rand(), and sqr() and not Application.Sqrt().
5. What’s too long? This is a matter of programming taste, but for our purposes 70–80
characters is considered too long.
The reason for the problem is that in the computation
n
x
()
used in
Binomial, we have to have x < n. In this case, VBA causes Excel to return
the error message #Value! The subject of Excel error values is somewhat
obscure, and therefore we cover it in the chapter appendix.
36.8 Using User-Defi ned Functions in User-Defi ned Functions
User-defi ned functions can be used in other user-defi ned functions, just
like Excel functions. The next function is a replacement for the COMBIN
worksheet function. COMBIN is defi ned as