Title: Visual Basic Functions
1Visual Basic Functions
- The least you need to know about functions.
Accompanying application illustration
2Functions
- A function is a type of subroutine which returns
a value based on a passed parameter. - ByVal functions do something useful with the
passed parameter but do not change it. - ByRef functions typically change the value of the
passed parameter.
Same rules of scope as Procedures
3ByVal Parameter
- Private Sub btnSolution1_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles btnSolution1.Click - DoubleIt(CDec(txtArgument1.Text))
- End Sub
- Private Function DoubleIt(ByVal decNumber1 As
Decimal) - txtFunction1.Text CStr(decNumber1 2)
- End Function
This function doubles the parameter passed to it
and displays it in a textbox. Any parameter
passed to this function will be known as
decNumber1 in this function.
4ByVal Parameter
- Private Sub btnSolution2_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs)
Handles _ btnSolution2.Click - txtFunction2.Text _
CStr(TripleIt(CDec(txtArgument2.Text))) - End Sub
- Private Function TripleIt(ByVal decNumber2 As
Decimal) As Decimal - TripleIt decNumber2 3End Function
This function triples the parameter passed to it.
The identifier for the function is treated as a
variable and is the means by which the value is
returned.
5ByRef Parameter
- Private Sub btnSolution3_Click(ByVal sender
As System.Object, _ ByVal e As System.EventArgs)
Handles btnSolution3.Click - Dim Argument3 As Decimal
- Argument3 CDec(txtArgument3.Text)
- TwiceIt(Argument3)
- txtFunction3.Text CStr(Argument3)
- End Sub
- Â
- Private Function TwiceIt(ByRef decNumber As
Decimal) - decNumber decNumber 2
- End Function
The value of Argument3 becomes doubled by the
function.
6Why use Functions?
- Functions reduce the amount of code in a program.
- A function can be called again and again from any
place in the program.
7Built-in Functions
and many more
8Built-in String Functions
9Randomize() function
- We need random numbers for games.
- Randomize(number) initializes the random-number
generator. - If you omit number, the value returned by the
system timer is used as the new seed value.
10Rnd() returns a random positive number less than
1, but greater than or equal to zero.
Recipe for a random integer CInt(Int((upperbound
- lowerbound 1) Rnd() lowerbound))