A subroutine is a block of code like function that do a specific task. The difference between subroutine and function is that a subroutine does not return a value. However, you may pass arguments to a subroutine in VB 6.
The syntax for subroutine is given below, the keywords within square bracket () are optional.
[Private | Public | Friend] [Static] Sub-name [(argument list)] ... [Statements] ... [Exist Sub] ... [Statements] ... End Sub
Public keyword allows procedures from all forms and modules to access the public procedures.
Private keyword only allows access to procedures from forms and modules where private procedure is declared.
Friend keyword used in class modules (modules that implement classes) allows the procedure to be visible throughout the project except to the controller of the instance of an object.
Static keyword preserve the value of local variable (those declared inside the procedure) between calls. You can call a procedure several times, it would not lose the value of a static local variable.
Argument list is a list of variables that it passed to the procedure. You can have multiple arguments each separated by a comma.
Argument List: Sub Procedure
Argument list has following syntax:
[Optional] [ByVal | ByRef] [ParamArray] varname [()] [As type] = [default value]
Optional means that the argument is not required.
ByVal means the argument is passed to the procedure by value. ByRef means that the argument is passed as a reference rather than the value.
ParamArray is the last argument in the argument list and it indicates that the final argument is an array of Variant elements.
Varname is the name of the argument being passed to the procedure.
type is the data type of the argument.
defualt value is a constant or a constant expression set when you use the [Optional] keyword.
Exit Sub cause the sub procedure to immediately exit itself.
End sub is to end the sub procedure.
Example: Sub Procedure
Here is an example of sub procedure.
Sub Matrix (Optional MatValues as Variant) If IsMissing (MatValues) Then ' If value is not passed MsgBox("Value not passed to the Matrix") Else ... End If End Sub
In the next article, we will learn about VB 6 function which is similar to sub procedure.