Sub Statement

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax


Sub name [(arglist)] 
   [statements]
   [Exit Sub]
   [statements]
End Sub 
  • name: Name of the Sub; follows standard variable naming conventions.

  • arglist: List of variables representing arguments that are passed to the Sub procedure when it is called. Commas separate multiple variables.

  • statements: Any group of statements to be executed within the body of the Sub procedure.

    Arguments:

    The arglist argument has the following syntax and parts:

    [ByVal | ByRef] varname[( )]

    • ByVal: Indicates that the argument is passed by value.

    • ByRef: Indicates that the argument is passed by reference.

    • Varname: Name of the variable representing the argument; follows standard variable naming conventions.

Remarks

If not explicitly specified using either Public or Private, Sub procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Sub procedure is not preserved between calls to the procedure.

The Exit Sub statement causes an immediate exit from a Sub procedure. Program execution continues with the statement that follows the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures.

Example 1:


Sub mysub()
  'some statements
End Sub

Example 2:


Sub mysub(argument1, argument2)
  'some statements
End Sub