Visual Basic Modules and Procedures

From Techotopia
Revision as of 18:57, 4 June 2009 by Neil (Talk | contribs) (Defining Visual Basic Functions)

Jump to: navigation, search
PreviousTable of ContentsNext
Building a Visual Basic Status BarUnderstanding Visual Basic Variable and Constant Types


<google>BUY_VISUAL_BASIC</google>


A key part of developing applications using Visual Basic is ensuring that the code is carefully structured. This involves segmenting the code into projects, modules and procedures so that it is easy to understand and maintain.

A complete Visual Basic application is typically contained in a single project. Within a project, code is placed in separate code files called modules, and within each module, the Visual Basic code is further separated into self contained and re-usable procedures.

The topic of projects was covered in Creating a New Visual Basic Project. In this chapter we will look in detail at Visual Basic modules and procedures.


Contents


Visual Basic Code Modules

Visual Basic application source code is structured into module files with a .vb suffix. By default, Visual Studio creates a separate module file for each form in an application containing the code to construct the form. For example, the code to create a form called Form1 will be placed in a module file named Form1.Designer.vb. Similarly, any code that has been defined by the developer to handle events from controls in the form will be placed by Visual Studio into a module file called Form1.vb.

When writing additional Visual Basic for an application, the code should ideally be logically grouped to together with other source code in a module file. When we say logically grouped we mean that the code should be grouped with other code of a similar nature. For example, code to work with files might be placed in a module called FileIO.vb, while mathematical procedures might all reside in a file named Math.vb. The idea is to ensure Visual Basic code is placed in a file where it makes sense for it to be located. This will differ between applications, but it is worth investing the time to ensure code is well structured as doing so makes subsequent maintenance of the code by you or other developers much easier.

We mentioned previously that Visual Studio places the code to construct each form in separate module files. We now need to learn how to create a new module in a project to contain our own Visual Basic code. Begin by creating a new Windows Application project in Visual Studio called vbModules. Add two TextBox controls (named value1TextBox and value2TextBox) and a button (labeled Calculate) to the Form so that appears as follows:

<google>ADSDAQBOX_FLOW</google> Visual basic procedures form.jpg

Once the new project has been opened and the first form is visible, select Add Module... from the Project menu. The Add Item window will appear with the Module item pre-selected:

Visual studio add module.jpg

Name the new module Math.vb and click the Add button. The new module will be added to the project and a new tab labeled Math.vb for accessing the module code appears in the design area:

Visual basic new module.jpg

Now that we have added a new module to our project the next step is to add Visual Basic code to that module. Before we can do that, however, we need to learn about Visual Basic procedures.

Visual Basic Code Procedures

Visual Basic procedures provide a way to break up code into logical and re-usable sections that can be called from other sections of Visual Basic code. For example, you might have a section of Visual Basic code that calculates the interest due on a loan. It is also possible that you need to perform this calculation from a number of different places in your application code. Rather than duplicating the code to perform this task at each code location where it is needed, it is more efficient to place the calculation code in a procedure, and then call that procedure each time it is needed.

Visual Basic provides two types of procedures:

  • functions - Functions are procedures which perform a task and return a value when completed.
  • subroutines - Subroutines are procedures which perform a task but return no value when completed.

It is especially useful to be able to return values from functions. For example, the function may need to return the result of the task it performed (perhaps the result of a calculation). A function might also return a True or False value to indicate when the task was performed successfully. The Visual Basic code which called the function then acts based on the returned value.

In the case of both subroutines and functions, values (known as parameters) may optionally be passed into the procedure.


Defining Visual Basic Subroutines

Subroutines are declared inside Visual Basic Modules. Our newly created module in Visual Studio contains the following:

Module Math

End Module

We are now going to add a subroutine called DisplayResult to this module. The syntax for a Visual Basic subroutine is as follows:

scope Sub subroutineName(parameters)
End Sub

The scope value is either Private or Public depending on whether the Subroutine is to be accessible from Visual Basic code outside of the current module. Sub is the Visual Basic keyword which indicates this is a Subroutine rather than a Function. subroutineName is the name of the Subroutine and is used when this specific procedure is to be called. The parameters value allows the parameters accepted by this Subroutine to be declared (see below).

The Public keyword indicates the scope. This defines whether this subroutine is accessible from Visual Basic code residing in other modules. Setting the scope to Private would make the Subroutine inaccessible to Visual Basic code outside the current module.

The Sub keyword indicates that this is a Subroutine (as opposed to a Function) and as such, does not return a value on completion. Finally, the name of the Subroutine is provided. The parentheses are used to hold any parameters which may be passed through to the Subroutine when it is called. The End Sub code marks the end of the Subroutine. The Visual Basic code that constitutes the Subroutine is placed after the Subroutine declaration and the End Sub.

We can write code in the Subroutine to display a message window as follows:

Module Math

   Public Sub DisplayResult()

        MessageBox.Show("Test message")


   End Sub

End Module

Next, the Click event procedure of the button in our form needs to call the DisplayResult() Subroutine. Double click on the button in the form to display the event procedure code and add the call to DisplayResult() as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
               Handles Button1.Click

        DisplayResult()

End Sub

Once the above change has been made, press F5 to build and run the application. When the application is running, pressing the button should cause a message window to appear displaying the text "Test Message".

Passing Parameters to Functions and Subroutines

Parameters may be passed to both Functions and Subroutines in Visual Basic. Parameters may be passed by value or by reference. When a parameter is passed by value, the Function or Subroutine receives a copy of the data. As such, changes to the data do not affect the original object or variable. When parameters are passed by reference, however, the Function or Subroutine receives a pointer to the original variable or object. As such, any changes made in the Subroutine are made directly to the original variable or object. Parameters that are passed by value must be prefixed with the keyword ByValue in the Function or Subroutine declaration. Parameters passed by reference, however, are prefixed by the ByRef keyword. If no keyword is specified, ByVal is is assumed.

The parameter must also be named in the Subroutine or Function declaration together with the variable or object type. For example, to adapt the DisplayResult() Subroutine to accept an Integer parameter called result by value, and display the result in the message window:

Public Sub DisplayResult(ByVal result As Integer)

        MessageBox.Show("Result is " + Str(result))

End Sub

Alternatively, to pass the parameter by reference:

Public Sub DisplayResult(ByRef result As Integer)

        MessageBox.Show("Result is " + Str(result))

End Sub

Just for the sake of completeness, change the Button control event procedure to pass through a string (note that we will change this later to pass the result of the actual calculation):

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
           Handles Button1.Click

        DisplayResult(10)

End Sub

Press F5 to build and run the application. The message window should now display 'Result is 10'.

Defining Visual Basic Functions

Visual Basic Functions differ from Subroutines in that they return a value. The syntax for declaring a Function is as follows:

scope Function functionName(parameters) As datatype

The scope value is either Private or Public depending on whether the Function is to be accessible from Visual Basic code outside of the current module. Function is the Visual Basic keyword that indicates that this is a Function rather than a Subroutine. functionName is the name of the function. parameters allows the parameters accepted by this Function to be defined. Finally, datatype defines the type of value returned by the Function.

With this syntax in mind we can create a Function for our application that will accept the values from our two text fields as parameters, perform the calculation and return the result as an Integer:

Public Function PercentageOf(ByVal value1 As Integer, ByVal value2 As Integer) As Integer

        Dim result As Integer

        result = (value1 / value2) * 100

        Return result

End Function

In the above Function, we accept two strings (value1 and value2) and declare an Integer variable called result to hold the result of the calculation. We then divide value1 by value2 and multiply the result by 100 to get value1 as a percentage of value2. The result is assigned to the result variable and then returned to the code which called the function.

The final step, is to modify our Button control Click event procedure to call the PercentageOf() function, passing through the Text properties of our two TextBox controls. The result returned by this function is then passed to the DisplayResult() Subroutine where it is displayed in a message window:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
             Handles Button1.Click

        DisplayResult(PercentageOf(value1TextBox.Text, value2TextBox.Text))

End Sub

After making the above change, press F5 to build and run the application. Enter 10 into the left hand TextBox control, 100 into the right hand TextBox control and press the Calculate button. The MessageBox will appear declaring that the result is 10.


<google>BUY_VISUAL_BASIC_BOTTOM</google>