Functions and procedures

For the convenience of a piece of code that is used repeatedly in several places, may be packaged into the procedure. In VBScript language there are two kinds of procedures: Sub and Function.

Sub - a sequence of commands framed by the keyword Sub and End Sub. Sub can take the input parameters, but never returns a value.

Function - sequence of statements framed by the keyword Function and End Function, returns the result and therefore may be an element of expression.

The names of the subs and functions must be unique.

Defining subs and functions has the following syntax:

[Public [Default] | Private] Sub name [(arglist)]


   [Exit Sub]


 End Sub


[Public [Default] | Private] Function name [(arglist)]


   [Exit Function]


 End Function

The parameter list has the following syntax:

 [ByRef | ByVal] varname [, ...]

Parameters can be passed by value (ByVal) or by reference (ByRef). By default, all parameters are passed by value. Constants and the results of expression evaluation may be passed only by value.

The following example shows the transfer of parameters into the sub:

 Sub DoCalculation(ByRef A, ByVal B, ByVal C)

   A = C * 2

   B = C / 2

 End Sub

 Sub TestVar

   Dim V1, V2

   V1 = 1

   V2 = 2

   DoCalculation V1, V2, 10

   ' after DoCalculation execution

   ' V1 = 20

   ' V2 = 2

 End Sub

The parameters are indicated in parentheses when a function or sub is called by using the Call.

Call DoCalculation(V1, V2, 10)