Lect 5
Lect 5
• Examples:
a) Function F(x) - You can now use this function on an Excel
F=2*x+5 WS in the same way as you use a built-in
End Function function, e.g. “=F(5)“Ø 15
b) Function FF(x) - The variable h only exists temporarily
h=2*x inside the function FF.
FF = h + 5 - Note: F(x) is the same function as FF(x)
End Function
c) Function G(x,y,z) - As for built-in functions you can have
G = y*x + z more than one input variable (argument).
End Function - Note: G(x,2,5) gives the same as F(x)
d) Function Q(a,b,c,x) - You can add comments to enhance the
' quadratic equation readability. VBA does not execute text
Q = a*x^2 + b*x +c following a single quote.
End Function “=Q(2,3,10,2)“ Ø 24 49
e) Function S(x, y, z)
S = 2 * Application.WorksheetFunction.SUM(x, y, z)
End Function
- You can use Excel built-in functions inside UDF by
Application.WorksheetFunction.FunctionName, e.g.
FunctionName = SUM. “=S(1,2,3)“ Ø 12
f) Function Squareroot(x)
Squareroot = 2*Sqr(x)
End Function
- Some built-in functions can be used in VBA under slightly
different names, e.g. SQRT =Sqr. “=Squareroot(9)“ Ø 6
- Other functions are: Abs, Atn, Cos, Exp, Fix, Int, Log, Mod,
Rnd, Sgn, Sin, Tan (For a list with explanations use the
help function and search for “Math Functions“. You also
get a list for “derived Math Functions“ such as Hsin,...) 50
- Examples:
a) Write a UDF which computes the weekday for a date
Function DD(da As Date)
DD = Weekday(da)
End Function
· Format the cell A1 as date and enter 25/10/2005
· “=DD(A1)“ Ø 3
b) Write a UDF which calculates the age in years given the
birthdate.
Function age(birthdate As Date)
age = Int((Now() - birthdate) / 365)
End Function
· (Now() - birthdate) ≡ the age in days
· Int( x ) ≡ extracts the integer part of x
· age ≡ the age in integer numbers of years 55
! Declaration of constants
• Constants are variables which do not change their value during
the execution of the program (UDF).
· Constants are used to keep the programming structure clear and
to avoid tedious re-typing or time consuming re-calculations.
· You can declare constants
i) such that they are only available inside the program or
ii) such that they are available in the entire worksheet.
Syntax: i) Const name [as type] = value
ii) Public Const name [as type] = value
Function .....
It is important to do the Public Const statement
before the Function statement.
· Expl. a) Const Pihalf = 1.570796327
b) Const Errmess as string = “Division by zero!!!“ 56
c) Public Const Errmess as string = “Division by zero!!!“
! Program Structures
• So far we have only seen sequential structures (line by line)
1 ...................
2 ...................
3 ...................
• You can change this way of execution by control structures
· branching or decision structures
1 ...................
2 ................... Flow chart
If/Case If/Case