Académique Documents
Professionnel Documents
Culture Documents
Function’s name
Variable’s name
Function
Function CtoF (temp)
declaration
CtoF=9⁄5∗𝑡𝑒𝑚𝑝+32
Calculation
End Function
Cautions for successful function coding
Function’s name as well as variables’ names must be
spelled exactly as they are throughout calculations.
𝑥2 X<10
𝑓 𝑥 =ቊ X>=10
𝑥
Solution
Function Math(x)
If x < 10 Then
Math = x ^ 2
Else
Math = Sqr(x)
End If
End Function
Exercise-3
Create a function to calculate water velocity in a pipe.
The input parameters are water discharge and pipe
diameter.
Solution(3)
Function VelocityPipe(Q, D)
Pi = WorksheetFunction.Pi
VelocityPipe = 4 * Q / Pi / D ^ 2
End Function
Exercise-4
Write a function to calculate Manning’s velocity equation.
The input variables are n, A,P and S.
Solution(4)
Function ManningVelocity(n, A, P, S)
R =A / P
ManningVelocity = (1 / n) * R ^ (2 / 3) * S ^ 0.5
End Function
Exercise-5
Write a function in VBA to calculate Manning’s equation.
The input parameters are water depth, n and slope. Assume
the bed width of the canal is 5 m and the side slope is
3H:1V.
Solution(5)
Function ManningVelocity2(d, n, s)
b=5
A = d*b+3*d^2
P = b + 2 * (10 * d ^ 2) ^ 0.5
R =A / P
ManningVelocity2 = (1 / n) * R ^ (2 / 3) * s ^ 0.5
End Function
Exercise-6
𝑛 1
Write a function in VBA to calculateσ𝑖=1 . Then try the
𝑖
function for n=2,3,4,5. Series expand such as:
2
1 1
+
1 2
𝑖=1
5
1 1 1 1 1
+ + + +
1 2 3 4 5
𝑖=1
Solution(5)
Function series1(n)
For i = 1 To n
s = s + (1 / i)
Next
series1 = s
End Function
Exercise-7
Write a function in VBA to calculate the summation of even
numbers for any natural number n.
Solution (7)
Function SumEven(n)
For i = 1 To n
If i < n Then
i=i+1
s=s+i
Else
End If
Next
SumEven = s
End Function
Exercise-8
Write a function in VBA to calculate the summation of the
odd numbers for any natural number.
Solution(8)
Function SumOdd(n)
s=0
For I = 0 To n
I=I+1
If I <= n Then
s=s+I
Else
End If
Next
SumOdd = s
End Function
Mod function
5 Mod 2 =1
The above syntax means that the result of division 5 by 2
has a digit after zero.
5/2=2.5
4 Mod 2 =0
The above syntax means that the result of division of 4 by
two does not have any digit after zero.