Sub Procedures [Part 1]


Learn about Scope of a Variable before starting this lesson.


As we have discussed in lesson 8, that procedures are of three types : 

  1. Sub Procedure, 
  2. Function Procedure,
  3. Property Procedure. 

The Property Procedure will be explained later in the tutorial.


Again Sub Procedures are of two types :

    a. Event Procedure,
    b. General Procedure.


Every procedure has a unique name, a scope and a list of arguments. The function procedure, in addition, has a return value. Sub procedure and property procedure does not return value.





Scope of a procedure

A procedure can be Private, Public or Friend. You can invoke a Private procedure only from within the module. A Public procedure can be called from anywhere of the current project -- from within the module, from other modules of your application project, and in some cases from outside the program using COM. And a friend procedure can be called from anywhere of the current project but not from outside.




Understanding the Event Procedure

An event procedure does not return any value and you can call it from other procedures of the module. The procedure is called using the Call command.

Example:
Private Sub Command1_Click()
    Call Command2_Click
End Sub
____________________________________________________________
Private Sub Command2_Click()
    Print "hello"
    MsgBox "hello"
End Sub

 So if you click the Command1 button, the Command2_Click event procedure is called, and the lines of code inside it are executed.

You may omit the Call command while calling a procedure.


Example:

Private Sub Command1_Click()
    Command2_Click
End Sub
__________________________________________________________
Private Sub Command2_Click()
    MsgBox "hello"
End Sub




Public event procedure

Example: Place a CommandButton on Form1. Now add a new form from the menu : Project > Add Form > Form. Place a CommandButton on Form2. 


'In Form1
Private Sub Command1_Click()
    Call Form2.Command1_Click
End Sub


'In form2
Public Sub Command1_Click()   'Scope is Public
    MsgBox "You have called a procedure of form2"
End Sub

 When you'll click the CommandButton on Form1, Command1_Click procedure of the form2 module will be called. As the scope of the procedure in Form2 is Public, the procedure is accessible from anywhere of the current project, and if the procedure is Private, the procedure cannot be invoked from other modules. In the Form2 module, if you change the procedure scope to Private, it can then only be called from the Form2 module. This aspect will be clearer when you'll learn about working with multiple forms in the next lessons.