You are on page 1of 11

Visual Basic Modules and Procedures

PREPARED BY: JANARTHANAN.R ASST.PROFESSOR

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:

Image: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: Image: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:

Image: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 toDisplayResult() 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".

Sub Procedures (Visual Basic)


A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure performs a task and then returns control to the calling code, but it does not return a value to the calling code. Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub statement and ending with the first End Sub, Exit Sub, or Return statement encountered. You can define a Sub procedure in modules, classes, and structures. By default, it is Public, which means you can call it from anywhere in your application that has access to the module, class, or structure in which you defined it. The term, method, describes a Sub or Function procedure that is accessed from outside its defining module, class, or structure. For more information, see Procedures in Visual Basic. A Sub procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code. Declaration Syntax

A Sub procedure is a block of code that is executed in response to an event. By breaking the code in a module into Sub procedures, it becomes much easier to find or modify the code in your application. The syntax for a Sub procedure is: ( we will postpone the discussion on Private/Public/Static to later) [Private|Public][Static]Sub procedurename (arguments) statements End Sub Each time the Sub procedure is called, the statements between Sub and End Sub are executed. Sub procedures can be placed in standard modules, class modules, and form modules. Sub procedures are by default Public in all modules, which means they can be called from anywhere in the application. The arguments for a procedure are like a variable declaration, declaring values that are passed in from the calling procedure. We will explore this after we have defined variables In VB, it's useful to distinguish between two types of Sub procedures, event procedures and general procedures. Event Procedures

When an object in VB recognizes that an event has occurred, it automatically invokes the event procedure using the name corresponding to the event. Because the name establishes an association between the object and the code, event procedures are said to be attached to forms and controls. Syntax for a control event Private Sub controlname_eventname (arguments ) statements End Syntax for a form event Sub Private Sub Form_eventname (arguments) statements End Sub An event procedure for a control combines the control's actual name (specified in the Name property), an underscore (_), and the event name. For instance, if you want a command button named cmdPlay to invoke an event procedure when it is clicked, use the procedure cmdPlay_Click. An event procedure for a form combines the word "Form" an underscore, and the event name. If you want a form to invoke an event procedure when it is clicked, use the procedureForm_Click. (Like controls, forms do have unique names, but they are not used in the names of event procedures.) If you are using the MDI form, the event procedure combines the word "MDIForm," an underscore, and the event name, as in MDIForm_Load. All event procedures use the same general syntax. Although you can write event procedures from scratch, it's easier to use the code procedures provided by VB, which automatically include the correct procedure names. You can select a template in the Code Editor window by selecting an object from the Object box and then selecting a procedure from the Procedure box. We will now examine event procedures and how to program them Run the program we have created so far by clicking the blue forward filled triangle on the toolbar The program compiles and executes. You should see the image of the form with the controls we created. Click on any of the command button. Note that nothing happens ! While the command button by default can recognize the mouse click we have not instructed the program to respond to this event. Exit/terminate the program by clicking the " X " sign in the title bar of the application window This should put us back in VB. For the following I have retained default names for the various objects on the form. You should work with the changes you had made earlier because this increases the effectiveness of what you learn today. Select Object View

Select the second Command Button you created in the Properties Window Change the caption to read "Exit" Double click on the second Command Button you created This should place the code view screen in the center area and provide a template for the click event procedure. This is the mouse click event. We are now ready to write our first event procedure Private Sub Command2_Click() End ' exits application - this is a comment - anything right of the single quote is ignored by compiler End Sub Run the application Click the command button The application should terminate and put us back into VB design environment We have successfully executed an event procedure.

Function Procedures
A Function procedure is another kind of procedure, similar to a Sub procedure for it can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Sub procedure, a Function procedure can return a value to the calling procedure. There are three differences between Sub and Function procedures: (books on line) Generally, you call a function by including the function procedure name and arguments on the right side of a larger statement or expression returnvalue = function() Function procedures have data types, just as variables do. This determines the type of the return value. (In the absence of an As clause, the type is the default Variant type.) You return a value by assigning it to the procedurename itself. When the Function procedure returns a value, this value can then become part of a larger expression. Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can use the Function statement to write your own Function procedures. The syntax for a Function procedure is: [Private|Public][Static]Function procedurename (arguments) [As type] statements End Function

Scope of variables (SUMMARY)

Depending on how it is declared, a variable is scoped as either a procedure-level (local) or module-level variable. Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. When the procedure finishes, the value of the variable disappears. In addition, the value of a variable in a procedure is local to that procedure that is, you can't access a variable in one procedure from another procedure. These characteristics allow you to use the same variable names in different procedures without worrying about conflicts or accidental changes. It is a good practice to explicitly declare all variables used in the program. To enforce this you can use the following line in the declaration sections of all modules in the project Option Explicit

Additional Scope : Static/Private/Public Variables


Static Variables : A variable declared with Static keyword like Static I As Integer ( contrast with Dim I As Integer) exists the entire time the application is running - while the variables defined with Dim keyword exists only as long as the procedure is executing Public Variables: Can only be used in the (general) section Public I As Integer This makes I available to all procedures in all other modules too. Private Variables: Can only be used in the (general) section Private I As Integer This makes I available to all the procedures in the current module. Same as using Dim at the module level If public variables in different modules share the same name, it's possible to differentiate between them in code by referring to both the module and variable names. For example, if there is a public Integer variable intX declared in both Form1 and in Module1, you can refer to them as Module1.intX and Form1.intX to get the correct values. The names of your private module-level and public module-level variables can also conflict with the names of your procedures. A variable in the module cannot have the same name as any procedures or types defined in the module. It can, however, have the same name as public procedures, types, or variables defined in other modules. In this case, when the variable is accessed from another module, it must be qualified with the module name.

Using Optional Arguments


You can specify arguments to a procedure as optional by placing the Optional keyword in the argument list. If you specify an optional argument, all subsequent arguments in the argument list must also be optional and declared with the Optional keyword. The two pieces of sample code below assume there is a form with a command button and list box. For example, this code provides all optional arguments: Add command button 4 and a list box to your project Dim strName As String Dim varAddress As Variant --------------Sub ListText(Optional x As String, Optional y _ As Variant) List1.AddItem x List1.AddItem y End Sub

Private Sub Command4_Click() strName = "yourname" varAddress = 12345 ' Both arguments are provided. Call ListText(strName, varAddress) End Sub The above code provides all the required arguments- the optional keyword did not take effect Another Example Dim strName As String Dim varAddress As Variant -------------------Sub ListText(x As String, Optional y As Variant) List1.AddItem x If Not IsMissing(y) Then ' This is a VB built in function List1.AddItem y ' This is an If statement - next topic End If End Sub

Private Sub Command4_Click() strName = "yourname" ' Second argument is not _ ' provided. Call ListText(strName) End Sub

In the case where an optional argument is not provided, the argument is actually assigned as a variant with the value of Empty. The example above shows how to test for missing optional arguments using the IsMissing function. Top

Providing a Default for an Optional Argument


It's also possible to specify a default value for an optional argument. The following example returns a default value if the optional argument isn't passed to the function procedure: Sub ListText(x As String, Optional y As _ Variant = 12345) List1.AddItem x List1.AddItem y End Sub

Private Sub Command4_Click() strName = "yourname" ' Second argument is not provided. Call ListText(strName) ' Adds "yourname" and "12345". End Sub

Arrays in Visual Basic


An array is a set of values that are logically related to each other, such as the number of students in each grade in a grammar school. By using an array, you can refer to these related values by the same name, and use a number thats called an index or subscript to tell them apart. The individual values are called the elements of the array. Theyre contiguous from index 0 through the highest index value. In contrast to an array, a variable that contain a single value is called a scalar variable.

THANK YOU

You might also like