Logo

Modules, Functions and Procedures

 

Introduction to Modules and Procedures

 

Introduction

A module is a file, also called a source file (as in C/C++, Pascal, and other languages) that belongs to a program and in which you write code. For example, while we were using forms so far, we couldn't write code on a form. We had to access the Code Editor.

Practical Learning: Introducing Modules

  1. Start Visual Basic and, in the opening dialog box, double-click Standard EXE
  2. To save the project, on the main menu, click File -> Save Project
  3. Locate your MS Visual Basic folder created in the first lesson and display it in the Save In combo box
  4. In the Save File As dialog box, click the Create New Folder button Create New Folder
  5. Type Modules1 and press Enter twice to display the new folder in the Save In combo box
  6. Replace the name of the file in the File Name edit box with Main and press Enter
  7. Type Modules1 to replace the name of the project and press Enter. If are asked whether you want to add the project to SourceSafe, click No
  8. Display the form and design it as follows:
     
    Geometric Calculations
    Control Name Caption 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  
  9. Save all

 

Creating a Module

There are two main ways you obtain a module for your program. When you create a form, a module is automatically created and associated to it. You can access the module of a form by right-clicking it and click View Code. Besides the modules created for your forms, you can create your own modules any time. To create a new module, on the main menu, you can click Project -> Add Module. In the Add Module dialog box, you can click Open. Once a new module has been added to your project, it is treated as a file. As such, you should save it to give it a friendlier name. The name of a module can be used to indicate the type of code included in that module.

Once a module is ready, you can type any piece of valid code in it. Such a module is automatically made available to other parts of your program. Just as you can write code in a module attached to a form, you can also write code in an independent module (unlike some other languages like C/C++ or Pascal, you usually don't need to reference one module from another; once a module has been created, you can use its contents as you wich).

Any existing module of your project is represented in the Project window with a button and a name in the Modules node. Therefore, to open a module, in Project window, you can double-click its node.

Practical Learning: Creating a Module

  1. To access the form's module, double-click anywhere in the form and notice that a source file opens
  2. To create a new module, on the Standard toolbar, click the arrow of the Add Form button and click Module
     
    Adding a New Module
  3. In the Add Module dialog box, make sure the Module icon is selected and click Open
     
    The Add Module dialog box
  4. To save the new module, on the Standard toolbar, click the Save button Save
  5. Change the name of the file to modGeometry and press Enter
  6. To change the name of the module in Visual Basic, in the Project window, click Module1. In the Properties window, click (Name). Type Routines and press Enter

Procedures

A procedure is an assignment you ask the compiler to take care of inside of your program. The assignment is performed behind the scenes. The program developer writes the function and the user would only see the result. In reality, there are two types of procedures you will use in your programs: those that have already been created thus made available to you, and those you will create yourself.

In Visual Basic, like most other languages, there are two categories of procedures: functions and sub routines (many other languages like Pascal make this distinction; some other languages like C++, C#, etc use only the name function to identify both categories).

 

Sub Routines

 

Introduction

As mentioned already, there are differences between a function and a sub routine. A sub routine is an assignment that is carried but doesn't give back a result.

To create a sub routine, start by typing the Sub keyword followed by a name because, like everything else, a procedure must have a name. The name of a procedure is always followed by parentheses. At the end of the sub routine, you must type End Sub. Therefore, the syntax of a sub routine is:

Sub ProcedureName()

End Sub

You can also initiate a sub routine by asking Visual Basic to generate one for you. To do that, on the main menu, you can click Tools -> Add Procedure... In the Add Procedure dialog box, specify a name for the procedure. Make sure the Sub radio button is selected and click OK.

The name of a procedure should follow the same rules we learned to name the variables, omitting the prefix:

  • If the procedure performs an action that can be represented with a verb, you can use that verb to name it. Here are examples: show, display
  • To make the name of a procedure stand, you should start it in uppercase. Examples are Show, Play, Dispose, Close
  • You should use explicit names that identify the purpose of the procedure. If a procedure would be used as a result of another procedure or a control's event, reflect it on the name of the sub procedure. Examples would be: afterupdate, longbefore.
  • If the name of a procedure is a combination of words, you should start each word in uppercase. Examples are: AfterUpdate, SayItLoud

The section between the Sub and the End Sub lines is referred to as the body of the procedure. The body of the procedure is used to define what and how the assignment should be carried. For example, if you need to use a variable, you can declare it and specify what kind of variable you need. There is no restriction on the type of variables that can be declared in a procedure. Here is an example in which a string variable is declared in the body of a sub routine:

Sub Assignment()
    Dim strFullName As String
End Sub

In the same way, you can declare as many variables as you need inside of a procedure. The actions you perform inside of a procedure depend on what you are trying to accomplish. For example, a procedure can simply be used to create a string. The above procedure can be changed as follows:

Sub Assignment()
    Dim strFullName As String
    strFullName = "Paul Bertrand Yamaguchi"
End Sub
 

Practical Learning: Creating a Sub Procedure

  1. To create a new sub procedure, in the Routines file, type sub SquarePerimeter and press Enter. This produces:
     
    Sub SquarePerimeter()
    
    End Sub
  2. To create another sub routine, on the main menu, click Tools -> Add Procedure...
  3. In the Name edit box, type SquareArea
     
    Add Procedure
  4. Click OK
  5. Implement both routines 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
  6. Save all

Calling a Sub Routine

Once you have sub routine, whether you created it or it shipped with Visual Basic, you can use it. Using a procedure is also referred to as calling it. Before calling a procedure, you should first locate the section of code in which you want to use it. For example, you may want to use it inside of a control's event. To call a simple sub routine, simply type its name in the section where you want to use. For example, you can call the assignment in the Load event of a form as follows:

Private Sub Form_Load()
    Assignment
End Sub

 

 

Practical Learning: Calling a Sub Procedure

  1. Display the form
  2. Double-click the top Calculate button and, in its body, type SquarePerimeter
  3. Double-click the bottom Calculate button and, in its body, type SquareArea
     
    Private Sub cmdCalcArea_Click()
        SquareArea
    End Sub
    
    Private Sub cmdCalcPerimeter_Click()
        SquarePerimeter
    End Sub
  4. Text the application
     
  5. Close the form and return to MSVB

Functions

 

Introduction

Like a sub routine, a function is used to perform an assignment. The main difference between a sub routine and a function is that, after carrying its assignment, a function gives back a result. We also say that a function "returns a value". To distinguish both, there is a different syntax you use for a function.

Practical Learning: Introducing Modules

  1. Display the form and change its design as follows:
     
    Control Name Caption Additional Properties
    Label   Length:  
    TextBox txtLength 0.00 Alignment: 1-Right Justify 
    Label   Height:  
    TextBox txtHeight 0.00 Alignment: 1-Right Justify
    Button   Calculate  
    Label   Perimeter:  
    TextBox txtPerimeter 0.00 Alignment: 1-Right Justify
    Label   Area:  
    TextBox txtArea 0.00 Alignment: 1-Right Justify
  2. Save all
 

Function Creation

To create a function, you use the Function keyword followed by a name and parentheses. Unlike a sub routine, because a function returns a value, you should/must specify the type of value the function will produce. To give this information, on the right side of the closing parentheses, type the As keyword, followed by a data type. To indicates where a function stops, type End Function. Based on this, the minimum syntax used to create a function is:

Function FunctionName() As DataType
    
End Function

The name of a function follows the same rules and suggestions we reviewed for sub routines. The DataType factor indicates the type of value that the function will return. If the function will produce a word or a group of words, you can create it as String. If the function will check something and determine whether it produce a true or a false value, you can create it as Boolean. The other data types are also valid in the contexts we reviewed them.

As mentioned already, the section between the Function and the End Function lines is the body of the function. It is used to describe what the function does. As done on a sub routine, one of the actions you can perform in a function is to declare a (local) variable and use it as you see fit. Here is an example:

Function CallMe() As String
    Dim Salute As String
    Salute = "You can call me Al"
End Function

After performing an assignment in a function, to indicate the value it returns, somewhere after the assignment and before the End Function line, type the name of the function, followed by the = sign, followed by the value the function returns. Here is an example in which a function returns a name:

Function CallMe() As String
    CallMe = "You can call me Al"
End Function

You can also use some local variables in the function to perform an assignment and then assign their result to the name of the function. Here is an example:

Function CallMe() As String
    Dim Salute As String
    Salute = "You can call me Al"
    CallMe = Salute
End Function
 

Practical Learning: Creating a Function

  1. Display the Routines module and delete (only) the previously implemented routines
  2. To create a new function, at the end of the file, type function RectPerimeter and press Enter
  3. To create another function, on the main menu, create Tools -> Add Procedure...
  4. In the Name edit box, type RectArea
  5. In the Type section, click Function
     
    Add Procedure - Creating a Function
  6. Press Enter
  7. Implement both functions 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
  8. Save all
 

Calling a Function

As done for the sub routines, in order to use a function in your program, must call it. Like a sub routine, to call a function, you can simply type its name in the desired section of the program. Here is an example:

Private Sub Form_Load()
    CallMe
End Sub

Since the primary purpose of a function is to return a value, to better take advantage of such a value, you can assign the name of a function to a property or a variable in the section where you are calling the function. In the following example, the return value of the CallMe function is assigned to the Caption property of the form from its own Load event:

Private Sub Form_Load()
    Caption = CallMe
End Sub

 Calling a Function

 

Practical Learning: Calling a Function

 
  1. Display the form and double-click the Calculate button
  2. Implement its event as follows:
     
    Private Sub cmdCalculate_Click()
        txtPerimeter = RectPerimeter
        txtArea = RectArea
    End Sub
  3. Test the application

Arguments and Parameters

 

Introduction

So far, to use a value in a procedure, we had to declare it. In some cases, a procedure may need an external value in order to carry its assignment. A value that is supplied to a procedure is called an argument.

When creating a procedure that will use an external value, declare the argument that represents that value between the parentheses of the procedure. For a sub routine, the syntax you use would be:

Sub ProcedureName(Argument)
      
End Sub

If you are creating a function, the syntax would be:

Function ProcedureName(Argument)
      
Function Sub

The argument must be declared as a normal variable, omitting only the Dim keyword. Here is an example that creates a function that takes a string as argument:

Function CalculatePayroll(strName As String) As Double
      
Function Sub

A certain procedure can take more than one argument. In this case, in the parentheses of the procedure, separate the arguments with a comma. Here is an example of a sub routine that takes two arguments:

Sub EvaluateInvoice(strEmplName As String, dblHourlySalary As Currency)
      
End Sub

In the body of a procedure that takes one or more arguments, use the argument(s) as you see fit as if they were locally declared variables. For example, you can involve them with values inside of the procedure. You can also exclusively use the values of the arguments to perform the assignment.

 

Practical Learning: Passing Arguments to a Procedure

 
  1. To pass arguments to a function, change the functions in the Routines module as follows:
     
    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
  2. Save

Passing Arguments (By Value)

 To call a procedure that takes an argument, type its name and a space, followed by value for each argument. The value provided for an argument is also called a parameter. If there is more than one argument, separate them with a comma. Here is an example:

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 sub routine. In this case, when calling a procedure using Call, you must include the argument(s) between the parentheses. using Call, the above GotFocus event could call the CalcAndShowSalary as follows:

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

If you use the above technique to call a procedure that takes more than one argument, you must provide the values of the arguments in the exact order they are listed inside of the parentheses of the function. Fortunately, you don't have to. If you know the name of the arguments, you can type them in any order and provide a value for each. To do that, on the right side of each argument, type the := operator followed by the desired value for the argument. Here is an 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:="Nguyen", FirstName:="Hermine")
End Sub

 

Practical Learning: Passing Arguments by Value

 
  1. Display the form and double-click the Calculate button
  2. To call the above functions, change the button's event 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
  3. Test the application
     
  4. Close the form and return to MSVB

Passing Arguments By Reference

When calling a procedure that took an argument, we were supplying a value for that argument. When this is done, the procedure that is called makes a copy of the value of the argument and make that copy available to calling procedure. That way, the argument itself is not accessed. This is referred to as passing an argument by value. This can be reinforced by typing the ByVal keyword on the left side of the argument. Here is an example:

Sub GetFullName(ByVal FullName As String)
    FullName = "Nguyen, Hermine"
End Sub

If you create a procedure that takes an argument by value and you have used the ByVal keyword on the argument, when calling the procedure, you don't need to use the ByVal keyword; just the name of the argument is enough, as done in the examples on arguments so far. Here is an example:

Private Sub Form_Load()
    Dim FName As String
    FName = "Albert Edou Nkoulou"
    GetFullName FName
    Caption = FName
End Sub

This would produce:

An alternative to this technique is to pass the address of the argument to the called procedure. When this is done, the called procedure doesn't receive a simple copy of the value of the argument: the argument is accessed at its root. That is, at its memory address. With this technique, any action carried on the argument will be kept. That is, if the value of the argument is modified, the argument would now have the new value, dismissing or losing the original value it had. This technique is referred to as passing an argument by reference.

To pass an argument by reference, on its left, type the ByRef keyword. This is done only when creating the function. When the called procedure finishes with the argument, the argument would keep whatever modification was made on its value. Now consider the following:

Private Sub Form_Load()
    Dim FName As String
    FName = "Albert Edou Nkoulou"
    GetFullName FName
    Caption = FName
End Sub

Sub GetFullName(ByRef FullName As String)
    FullName = "Nguyen, Hermine"
End Sub

This would produce:

Using this technique, you can pass as many arguments by reference as many arguments by value as you want. As you may already, this technique is also used to make a sub routine return a value, which a regular sub routine cannot do. Furthermore, passing arguments by reference allows a procedure to return as many values as possible while a regular function can return only one value.

 

Practical Learning: Passing Arguments by Reference

  1. Display the Routines module
  2. To pass an argument by reference, change the RectArea function as follows:
     
    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
  3. Display the module of the form and change the Click event of 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)
        RectArea dblLen, dblHgt, dblArea
        
        txtPerimeter.Text = dblPerim
        txtArea.Text = dblArea
    End Sub
  4. Test the application
  5. Close the form
 

Previous Copyright © 2001-2005 FunctionX, Inc. Next