Visual Basic Modules and Procedures
Visual Basic Modules and Procedures
Visual Basic Modules and Procedures
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.
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
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".
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
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
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
Private Sub Command4_Click() strName = "yourname" ' Second argument is not provided. Call ListText(strName) ' Adds "yourname" and "12345". End Sub
THANK YOU