Visual Basic 2005


Add to MY Favorites...

Back to Vicky's Home Page Teaching Home Page Visual Basic 2005 Html For Kids

Creating Functions and Subs

Functions and Subs are both blocks of code with a single (hopefully) task.  Functions return a value or values; subs do not.

Creating a Sub

A sub is just a block of code that can be called from anywhere in the form's code. The code can be called repeatedly within the form's code, but the code is only entered once.

 

Private Sub MakeFullName()

Dim First as string

Dim Second as string

Dim FullName as string

 

First = txtFirstName

Second = txtSecondName

FullName = First & " " &  Second

MsgBox("Hello "& FullName "." )

End Sub

Nothing is passed to the sub.  The code gets executed with the following statement:

 
Call MakeFullName()

or simply:

 
MakeFullName()

 

Creating a Function

The function will receive variable data from another part of the program.  When variables are received by a function, they are called parameters. The parameter statement includes how the variable contents will be passed, and a declaration of type. In the example below, two variables received will be girls and boys.  Both will be passed ByVal and both will be the type Integer.  These variables do not get a Dim statement in the function code.

ByVal means the value of the variable will be passed; a copy of the contents, but not the variable itself.  This means that no changes can occur to the variable contents.

ByRef means the reference to the variable will be passed.  This is also called pointing to the variable. Any changes made to the variable within the function will be made to the variable's actual data content.

 

Private Sub Add(ByVal first As Integer, ByVal second As Integer)

Dim result As Integer

result = first + second

MsgBox("The total is "& result "." )

End Sub

The following statement calls the function and passes two variables to it; txtFirstNumber.Text and txtSecondNumber.text. Whatever is in these textboxes will become the values of first and second in the Add function. The variables passed are called arguments.

The text box txtResult will be assigned the result of the function.

 

txtResult = Add(txtFirstNumber.Text, txtSecondNumber.Text)

The function has more flexibility as to how it can be used. The result could be the number of students, boys and girls; or the number of fruit, oranges and apples.

 


 
Another page developed by
vicky@vickywoodard.com
Copyright © 2006 Vicky K. Woodard
All rights reserved
Last updated: 8/17/2006