Home / Visual Basic Tutorial / Procedure / Sub Procedures

Sub Procedures

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.
[Private|Public][Static]Sub procedurename (arguments)
End Sub
Each time when 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, that means they can be called from anywhere in application.
Note that:
Sub Procedures are the procedures that do not return a value.
The arguments for a procedure are like a variable declaration.
Event Procedures
When an object in Visual Basic recognizes that an event has occurred then it automatically invokes event procedure
That event procedure will use procedure name corresponding to that event.
Private Sub Form_eventname (arguments)
End Sub
CmdSave_Click():-Here Click is an event and CmdSave_Click() is the procedure associated with it.
Syntax for a Control Event:
Private Sub Control_Eventname(arguments)
Statements Block
End sub
Syntax for a Form Event:
Private Sub Form_eventname(arguments)
Statements Block
End sub
Private Sub Form_Load().
This is the main event procedure for a form .When a form is loaded in application then this procedure is called first.
General Procedures
general procedure tells the application how to perform a specific task. Once a general procedure is defined, it must be specifically invoked by the application.
General procedure remains idle until called upon to respond to events caused by the user or by system.
For Animated Presentation Click Here
Why create general procedures?
One reason is that several different event procedures might need the same task repeatedly.
A good programming strategy is to put common statements in a separate procedure (a general procedure). An event procedure calls that general procedure.
This eliminates the need to duplicate code and also makes the application easier to maintain.
Suppose you display some message after each event code execution then you will use event procedure.
For adding procedure to your application follow the steps given below:
(1) Go to Tools menu and select Add Procedure form. Or, Use key combination Alt+T+P.
The window will be shown like this:
(2) Write name of procedure Display in the name Box and select type Sub according to figure given above.
(3) Write code for display() after Clicking OK in the previous Step.The code Window will display like this:
(4) Now call procedure in any event associated your application.
( Calling Procedure display() )