By Kardi Teknomo, PhD .


< Previous | Next | VB Tutorial | Contents >

VB Sub Procedure

In VB, it's useful to distinguish between three types of procedures:

  1. sub procedures
  2. Event procedures
  3. functions

A Sub procedure is a block of code that is executed when you call the procedure name. It does not return any value. By breaking the code in a module into Sub procedures, it becomes much easier to find or modify the code in your application.

Syntax :
[Private|Public] Sub procedurename (arguments)
statements
[Exit Sub]
statements
End Sub




Each time the procedure is called, the statements between Sub and End Sub are executed. Sub procedures can be placed either in standard modules, class modules, or form modules.

The arguments for a procedure are like a variable declaration, declaring values that are passed in from the calling procedure.

For Example: Start a standard Exe project. You can copy and paste the following code in the declaration section of your form

Option Explicit
Dim num As Integer
Private Sub Form_Click()
           num = num + 1
           MsgBox ("You have clicked me " & num & " times")
           CheckNumberOfClick (num)
End Sub
Sub CheckNumberOfClick(numClick As Integer)
           If numClick = 1 Then
               MsgBox "Click me more..."
           ElseIf numClick = 2 Then
               MsgBox "Ok enough clicking..."
           ElseIf numClick = 3 Then
               MsgBox "Too much clicks ..."
           Else
               MsgBox "I gonna reset the counter ..."
               num = 0
           End If
End Sub

Run the program and clicks the form at least 5 times. In the example above, sub procedure name CheckNumberOfClick has one argument name numClick of integer type. The sub procedure is called by event procedure Form_Click by passing global variable num .

< Previous | Next | VB Tutorial | Contents >

Rate this tutorial or give your comments about this tutorial

This tutorial is copyrighted .