TechnologyUK - Programming (VB6) Logo

Modules and Procedures

A module is a file, also called a source file (as with C and other programming languages) that belongs to a program and in which you can store program code.

Creating a Form

  1. In the folder where you keep your Visual Basic projects, create a new folder called "Modules1".
  2. Start Visual Basic and select Standard EXE by pressing Enter
  3. Save the new project in the folder "Modules1" using the filename "Main.frm" for the form, and "Modules1.vbp" for the project filename.
  4. Create a form with the controls shown below and save your project.

The Geometric Calculations form (version 1)


"Geometric Calculations" Form Properties
ControlNameCaption Additional Properties
Label   Side:  
TextBox txtSide 0.00 Alignment: 1-Right Justify
Label   Perimeter:  
TextBox txtPerimeter 0.00 Alignment: 1-Right Justify
Button cmdCalcPerimeter Calculate  
Label   Area:  
TextBox txtArea 0.00 Alignment: 1-Right Justify
Button cmdCalcArea Calculate  


Creating a Module

When you create a form, a module is automatically created and associated with it. You can access a form's module by right-clicking the form and selecting View Code. To create your own module using the Project menu:

  1. Click Project>Add Module>Open to create the new module.
  2. From the File menu, select Save As and save the module with the name "ModGeometry".

The module will be created as a file with the extension .bas and added to the project. Any code contained within the module will be available to other parts of your program, and any modules added to your project will appear in the Project window in the Modules node.



Procedures

Two types of procedures are used in Visual Basic programs - those that are built in to the Visual Basic programming language, and those that you will create yourself. There are two categories of procedures in Visual Basic - functions and sub routines. The difference between the two is that a function returns a result, while a sub routine does not.



Sub Routines

You create a sub routine by typing the Sub keyword, followed by a name (which should be chosen to reflect the purpose of the sub routine), followed by parentheses. To end the sub routine, type the keywords End Sub. The syntax of a sub routine is shown below.

Sub ProcedureName()

End Sub

A widely used convention is to start the name of a procedure with a capital letter. If a combination of words is used, each word should begin with a capital letter, e.g. CalculatePrice, or PrintRecord. The code that is placed between Sub and End Sub is called the body of the procedure, and defines what the procedure actually does. Variables required by the procedure can be declared within the procedure body as follows:

Sub ProcedureName()
    Dim strFirstName As String
     strFirstName = "Fred"
End Sub

You can declare any number of variables inside a procedure. The actions performed by the procedure will depend on the purpose of the procedure. The above procedure simply declares a string variable and assigns it the value "Fred".



Creating a Sub Routine for our "Geometric Calculations" Program

  1. In the Project window, double click on the Module1 node to open the code window for the module.
  2. Type the words Sub SquarePerimeter and press Enter. This produces the following code:

Sub SquarePerimeter()

End Sub

You can also create a procedure using the main menu. Create another procedure as follows:

  1. Click Tools>Add Procedure. A dialog box will appear as shown below.

    The Add Procedure dialogue box


  2. In the Name box, type "SquareArea".
  3. Click OK.
  4. Add the code for the two procedures as shown below, and save your project.

The code for the two procedures is as follows:

Sub SquarePerimeter()
    Dim dblSide As Double
    Dim dblPerimeter As Double
    dblSide = Form1.txtSide
    dblPerimeter = dblSide * 4
    Form1.txtPerimeter.Text = dblPerimeter
End Sub


Public Sub SquareArea()
    Dim dblSide As Double
    Dim dblArea As Double
    dblSide = Form1.txtSide
    dblArea = dblSide * dblSide
    Form1.txtArea.Text = dblArea
End Sub



Calling a Sub Routine

Using a procedure is also referred to as calling it. To call a sub routine, type its name in the section of code where it is to be used. In the following example, the sub routine InitialiseVariables() is called when the form loads:

Private Sub FormLoad()
    InitialiseVariables
End Sub



Calling a Sub Procedure in our "Geometric Calculations" Program

  1. Display the form.
  2. Double-click the top Calculate button. The code window for the form will open and you will see that the following code has been created:

    Private Sub cmdCalcArea_Click()

    End Sub

  3. In the body of this procedure, type SquarePerimeter.
  4. Now double-click the top Calculate button, and within the body of its procedure type SquareArea. Your code should now appear as follows:

    Private Sub cmdCalcArea_Click()
        SquareArea
    End Sub

    Private Sub cmdCalcPerimeter_Click()
        SquarePerimeter
    End Sub

  5. Run and test the application to check that it works (you will need to type a value into the Side box before clicking on the Calculate buttons).

The Geometric Calculations form



Functions

Functions are procedures, like sub routines, but a function sends a value back to the routine that calls it, i.e. it "returns a value". When creating a function, a slightly different function is used, as we shall see. To illustrate the use of functions, we will need to modify our form as follows:


The Geometric Calculations form (version 2)


"Geometric Calculations" Form Properties (Version 2)
ControlNameCaption Additional Properties
Label   Length:  
TextBox txtLength 0.00 Alignment: 1-Right Justify
Label   Height:  
TextBox txtHeight 0.00 Alignment: 1-Right Justify
Button cmdCalculate Calculate  
Label   Perimeter:  
TextBox txtPerimeter 0.00 Alignment: 1-Right Justify
Label   Area:  
TextBox txtArea 0.00 Alignment: 1-Right Justify


Once you have done this, save your project.

You create a function by typing the Function keyword, followed by a name (which should be chosen to reflect the purpose of the function), followed by parentheses. Because the function (unlike a sub routine) returns a value, you should specify the type of value the function will return by typing the As keyword to the right of the closing parenthesis, followed by the data type of the value to be returned. To end the function, type the keywords End Function. The syntax of a sub routine is shown below.

Function FunctionName() As DataType

End Function

The naming convention used should be the same as for subroutines. As with sub routines, the code that is placed between Function and End Function is called the body of the function, and defines what the function actually does. Variables required by the function can be declared within the function body as follows:

Function GreetAlien() As String
    Dim Greeting As String
    Greeting = "Hello and welcome to Earth!"
    GreetAlien = Greeting
End Function

You can declare any number of variables inside a procedure. The actions performed by the procedure will depend on the purpose of the procedure. The above procedure simply declares a string variable and assigns it the value "Hello and welcome to Earth!". The value to be returned is determined by typing the name of the function, followed by the equals sign (=), followed by the value to be returned. In the above example, the function returns the string value "Hello and welcome to Earth!".



Creating functions for our "Geometric Calculations" Program

  1. Open the Module1 code window and delete the two sub routines previously created.
  2. Type the words Function RectPerimeter and press Enter. This produces the following code:

Function RectPerimeter()

End Function

You can also create a function using the main menu. Create another function as follows:

  1. Click Tools>Add Procedure. A dialog box will appear as shown below.


    The Add Procedure dialogue box


  2. In the Name box, type "RectArea".
  3. In the Type section, select the Function radio button.
  4. Click OK.
  5. Add the code for the two functions as shown below, and save your project.

The code for the two functions is as follows:

Function RectPerimeter()
    Dim dblLength As Double
    Dim dblHeight As Double
    dblLength = Form1.txtLength.Text
    dblHeight = Form1.txtHeight.Text
    RectPerimeter = (dblLength + dblHeight) * 2
End Function


Public Function RectArea()
    Dim dblLength As Double
    Dim dblHeight As Double
    dblLength = Form1.txtLength.Text
    dblHeight = Form1.txtHeight.Text
    RectArea = dblLength * dblHeight
End Function



Calling a Function

A function is called in much the same way as a sub routine, by typing its name in the section of code where it is to be used. In the following example, the function GreetAlien()is called when the form loads:

Private Sub Form_Load()
    Caption = GreetAlien
End Sub

Since the primary purpose of a function is to return a value, in the above example the return value of the GreetAlien() function is assigned to the Caption property of the form when it loads.



Calling a Function in our "Geometric Calculations" Program

  1. Display the form and double-click the Calculate button. The code window for the form will open and you will see that the following code has been created:

    Private Sub cmdCalculate_Click()

    End Sub

  2. In the body of this procedure, enter the code shown below:

    Private Sub cmdCalculate_Click()
        txtPerimeter = RectPerimeter
        txtArea = RectArea
    End Sub

  3. Run and test the application to check that it works (you will need to type values into the Length and Height boxes before clicking on the Calculate button).

The Geometric Calculations form


Arguments and Parameters

Up until now, we have declared the variables needed by the procedures we have created within the body of the procedure. Sometimes, however, we may require an external variable in order to carry out a particular task. An external variable that is passed to a procedure is called an argument. When creating a procedure that will use an external variable in this way, the argument is declared by typing its name within the parentheses that follow the procedure's name. The construction used for a sub routine is shown below:

Sub ProcedureName(Argument)

End Sub

And here is the construction used for a function:

Function ProcedureName(Argument)

End Function

The argument is declared within the parentheses of the procedure in the same way that a function is declared elsewhere in your program, except that the Dim keyword is not used. A procedure can accept multiple arguments, and each argument can be of a different type. The following examples show a function that takes a string argument and returns a double-precision floating point value, and a sub routine that takes both a string variable and a currency variable.

Function CalculatePayroll (strName As String) As Double

End Function


Sub EvaluateInvoice (strEmplName As String, dblWage As Currency)

End Sub

Procedures can use the arguments passed to them in exactly the same way as locally declared variables. To demonstrate the use of arguments in procedures, change the RectPerimeter() and RectArea() functions in Module1 as follows, and save the project:

Function RectPerimeter(dblLength As Double, dblHeight As Double)
    RectPerimeter = (dblLength + dblHeight) * 2
End Function


Public Function RectArea(dblLength As Double, dblHeight As Double)
    RectArea = dblLength * dblHeight
End Function



Passing Arguments by Value

To call a procedure that takes an argument, type its name, followed by a value for each argument (the value provided for an argument is also known as a parameter). The procedure name and the first argument that follows it should be separated by a space. If more than one argument is used, the arguments should be separated using a comma. An example is given below.

Private Sub txtResult_GotFocus()
    Dim dblHours As Double
    Dim dblSalary As Double
    dblHours = txtHours
    dblSalary = txtSalary
    CalcAndShowSalary dblHours, dblSalary
End Sub


Sub CalcAndShowSalary(Hours As Double, Salary As Double)
    Dim dblResult As Double
    dblResult = Hours * Salary
    txtResult = dblResult
End Sub

Alternatively, you can use the Call keyword to call a procedure. If this method is used, the arguments must be placed within parentheses. The procedure call in the preceding example would then appear like this:

Call CalcAndShowSalary(dblHours, dblSalary)

Note that, if a procedure takes more than one argument, the values passed to the procedure must be supplied in the order in which they appear inside the parentheses of the procedure declaration. Alternatively, if the names of the argument are known, they can be used to identify the values, which can then be supplied in any order, as in the following example:

Function DisplayName(FirstName As String, LastName As String) As String
    Dim FullName As String
    FullName = FirstName & " " & LastName
    DisplayName = FullName
End Function


Private Sub Form_Load()
    Caption = DisplayName(LastName:="Wells", FirstName:="Chris")
End Sub

We now need to revise the code for the Calculate button as follows:

Private Sub cmdCalculate_Click()
    Dim dblLen As Double
    Dim dblHgt As Double
    Dim dblPerim As Double
    Dim dblArea As Double
    dblLen = txtLength.Text
    dblHgt = txtHeight.Text
    dblPerim = RectPerimeter(dblLen, dblHgt)
    dblArea = RectArea(dblLen, dblHgt)
    txtPerimeter.Text = dblPerim
    txtArea.Text = dblArea
End Sub

Once you have made the necessary changes, save the project and run the program to test it.



Passing Arguments by Reference

Passing an argument to a procedure by value makes a copy of the argument variable available to the procedure. The original variable is thus unaffected by any actions carried out within the procedure. An alternative technique involves passing the argument by reference. With this method, the address in memory of the argument variable is passed to the procedure. Any change in the value of an argument made by the procedure are applied to the original variable, not a copy. Passing an argument by reference requires the ByRef keyword before the name of the argument within the parentheses of the function declaration. To demonstrate this technique, make the following changes to the RectPerimeter() and RectArea() functions:

Function RectPerimeter(ByVal dblLength As Double, _
        ByVal dblHeight As Double)
    RectPerimeter = (dblLength + dblHeight) * 2
End Function


Sub RectArea(ByVal dblLength As Double, _
        ByVal dblHeight As Double, _
        ByRef dblSurface As Double)
    dblSurface = dblLength * dblHeight
End Sub

Now make the following changes to the code for the Calculate button:

Private Sub cmdCalculate_Click()
    Dim dblLen As Double
    Dim dblHgt As Double
    Dim dblPerim As Double
    Dim dblArea As Double
    dblLen = txtLength.Text
    dblHgt = txtHeight.Text
    dblPerim = RectPerimeter(dblLen, dblHgt)
    RectArea dblLen, dblHgt, dblArea
    txtPerimeter.Text = dblPerim
    txtArea.Text = dblArea
End Sub

Note that the changes we have made mean that the value of dblArea is passed to the RectArea() function by reference, which means that the value of dblArea will be changed by this function call.

Once you have made the necessary changes, save the project and run the program to test it.