2.9. Functions and Subroutines


VB 2005 supports both functions and subroutines. Basically, support for functions and subroutines is the same in VB 2005 as it is in VB 6. However, VB 2005 provides you with an additional way to return values in a function by means of the new Return statement. VB 2005 programmers have three choices: they can write their own functions, continue using most of the VB 6 functions they have come to know and love, or tap into the rich functionality of the .NET Framework Class Library through the new My namespace (see "My Namespace," later in this chapter).

Exiting or Skipping a Loop

You can exit a loop at any time by using one of the following statements:

 Exit For Exit Do Exit While 

In VB 2005, you can transfer control immediately to the next iteration of a loop by using the Continue keyword. Consider the following:

 For i As Integer = 0 To 10 ' prints out all odd ' numbers from 0 to 10 If i Mod 2 = 0 Then Continue For MsgBox(i) Next 

The preceding code snippet prints out all the odd numbers from 0 to 10. Note that the Continue keyword can also be used with a While loop and a Do-While loop.


2.9.1. Function

A function is a block of code that performs some operations and then returns a value. For example, the following function Area takes in two input parameters, computes the area, and then returns the result:

      Public Function Area(ByVal length As Single, _                  ByVal breadth As Single) As Single          Dim result As Single          result = length * breadth          Return result      End Function 

To invoke a function, you simply call the function name with the required argument(s):

  Dim areaOfRect As Single = Area(4, 5) 

VB 6 Tip: In VB 6, only functions require the mandatory use of parentheses around the parameter list. But in VB 2005, all functions or subroutine calls require parentheses around the parameter list (even if the parameter list is empty).


The value returned by the Area function is then assigned to the areaOfRect variable.

In VB 6, you use the function name to return the value of a function, like this:

 Public Function Area(ByVal length As Single, _             ByVal breadth As Single) As Single         Dim result As Single         result = length * breadth         Area = result     End Function 

In VB 2005, you can either use the Return keyword or the function name to return the value of a function. Note that when a Return statement is encountered in a function, the execution is immediately transferred back to the statement that called it.

2.9.2. Subroutine

A subroutine is similar to a function, except that it does not return a value. For example, the following subroutine PrintMessage accepts a single input parameter and prints a message box.

 Public Sub PrintMessage(ByVal str As String)         MsgBox(str) End Sub 

To invoke a subroutine, you simply call the subroutine name and pass it the required argument(s):

 PrintMessage("File deletion completed.") 

VB 6 Tip: In VB 6, you can call the PrintMessage subroutine without using parentheses to enclose the parameter list:

 PrintMessage "File deletion completed." 


2.9.3. Passing Arguments

There are two ways to pass values to a subroutine or function:

  • By value

  • By reference

Let's take a closer look at these two methods in the following sections.

2.9.3.1. Passing by value

Consider the following subroutine:

 Public Sub ProcessValue(ByVal num As Integer)         num += 1         MsgBox("In ProcessValue(), num is " & num)     End Sub 

The ProcessValue subroutine takes a single input parameter: num. The parameter declaration is preceded by the ByVal keyword.

By default, Visual Basic 2005 passes an argument via ByVal. In VB 6, the default is ByRef (see "Passing by reference," next).

The following statements call the ProcessValue subroutine and display a value at each stage:

 Dim num As Integer = 5 MsgBox("Before ProcessValue(), num is " & num) ProcessValue(num) ' pass by value MsgBox("After ProcessValue(), num is " & num) 

You will realize that the value of num remains at 5 before and after calling the ProcessValue subroutine.

As you can deduce, even though the variable num is modified within the subroutine, the change is not reflected outside the subroutine. When you pass an argument by value, a copy of the variable is created to be used within the subroutine. When the subroutine exits, the variable is destroyed.

2.9.3.2. Passing by reference

Consider the following subroutine:

 Public Sub ProcessValue(ByRef num As Integer)         num += 1         MsgBox("In ProcessValue(), num is " & num)     End Sub 

The ProcessValue subroutine takes in a single input parameter: num. The parameter declaration is preceded with the ByRef keyword.

The following statements call the ProcessValue subroutine and display the value at every stage:

 Dim num As Integer = 5 MsgBox("Before ProcessValue(), num is " & num) ProcessValue(num) ' pass by value MsgBox("After ProcessValue(), num is " & num) 

In contrast to passing by value, when you pass an argument by reference, the subroutine receives a reference that points to the location where the argument is stored in memory. When the variable is modified within the subroutine, the change will affect the original variable. Hence, the change remains even after the subroutine exits.

2.9.3.3. Optional parameters

Consider the following definition of a modified PrintMessage subroutine:

 Public Sub PrintMessage(ByVal str1 As String, _ ByVal str2 As String, _           Optional ByVal str3 As String = "rocks!")        MsgBox(str1 & str2 & str3) End Sub 

This version of the PrintMessage subroutine takes three input parameters: str1, str2, and str3. The first two are required; str3 is an optional parameter, as called out by the Optional keyword. For an optional parameter, a default value is required.

Optional arguments must always be declared last in a subroutine definition. You can specify one or more optional parameters.

VB 6 Tip: In VB 6, optional parameters are not required to have default values, but in VB 2005, optional parameters must have default values.


When you call the subroutine, you pass the arguments in the order specified by the parameter list. The following subroutine calls PrintMessage, passes the strings "Visual" and "Basic" as arguments, using the optional arguments in one case but not in the others:

 '--- with and without optional arguments ' prints out Visual Basic rocks! PrintMessage("Visual ", "Basic ")     ' prints out Visual Basic rocks! PrintMessage("Visual ", "Basic ", ) ' prints out Visual Basic really rocks! PrintMessage("Visual ", "Basic ", "really rocks!") 

You can also leave out the optional argument by using a comma (,).



Visual Basic 2005 Jumpstart 2005
Visual Basic 2005 Jumpstart
ISBN: 059610071X
EAN: 2147483647
Year: 2005
Pages: 86
Authors: Wei-Meng Lee

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net