Sub Procedures [Part 2]

Understanding the general sub procedure

General sub procedure can be very useful when you want to use a block of code repeatedly in your program. Instead of writing the same lines of code again and again, define a General Sub Procedure, and call it where you need. These procedures do not return values.

Say you need to print some lines of text again and again. So define a general sub procedure xprint , and call it wherever in the program its necessary.


Note: Public is the default scope for procedures, so you may omit it.


Example:

Sub txt()
    MsgBox "welcome"
End Sub


Example:

Private Sub Command1_Click()
    Call xprint      'Function calling

End Sub
___________________________________________________________
Private Sub xprint()   'Function Definition
    Print "Hello World"
    Print "";
    Print "*****"
    Print "New"
End Sub

___________________________________________________________
Private Sub Command2_Click()
    Call xprint      'Function calling
End Sub

Using sub procedures in your code is a good programmer's habit. Because it reduces the number of lines of code. Besides, a large complex program becomes very easy and comprehensive when you use your own sub procedure in the code.

You can change the scope to Public when you want to access the procedure from outside the module.




Public general sub procedure

Add a new form from menu : Project > Add Form > Form. Public general sub procedures are useful when want to invoke your procedure from wherever you want, from any module.

Example: 

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



'In form2

Public Sub xprint()
    Form2.Show
    Print "Hello World !"
    Print "";
    Print "***"
    Print "New"
End Sub
_____________________________________________________________
Private Sub Command1_Click()
    Call xprint
End Sub

The concept of Public general sub procedure will be clearer to you when you'll learn about working with multiple forms in the next chapters.