# Sub
{: .no_toc }

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

Syntax:
> [ *attributes* ]  
> [ **Public** \| **Private** \| **Friend** \| **Protected** ] [ **Static** ] [ **Overridable** ] **Sub** *name* [ *callconv* ] [ **(** **Of** *typevars* **)** ] [ **(** *arglist* **)** ] [ *binding-clause* ]  
> &nbsp;&nbsp;&nbsp;&nbsp; [ *statements* ] ...  
> &nbsp;&nbsp;&nbsp;&nbsp; [ **Exit Sub** ] ...  
> &nbsp;&nbsp;&nbsp;&nbsp; [ *statements* ] ...  
> **End Sub**

*attributes*
: *optional* One or more of the [supported attributes](/tB/Core/Attributes.md) for procedures.

**Public**
: *optional* Indicates that the **Sub** procedure is accessible to all other procedures in all modules. If used in a module that contains an **Option Private**, the procedure is not available outside the project.

**Private**
: *optional* Indicates that the **Sub** procedure is accessible only to other procedures in the module where it is declared.

**[Friend](/tB/Core/Friend.md)**
: *optional* Used only in a class module. Indicates that the **Sub** procedure is visible throughout the project, but not visible to a controller of an instance of an object.

**[Protected](/tB/Core/Protected.md)**
: *optional* (twinBASIC) Used only in a class. Indicates that the **Sub** procedure is accessible from inside the declaring class and from classes that derive from it via [**Inherits**](/Features/Language/Inheritance.md#inherits-for-complete-oop), but not from outside callers.

**[Static](/tB/Core/Static.md)**
: *optional* Indicates that the **Sub** procedure's local variables are preserved between calls. The **Static** attribute doesn't affect variables that are declared outside the **Sub**, even if they are used in the procedure.

**Overridable**
: *optional* (twinBASIC) Marks the **Sub** as an inheritance hook that classes derived via [**Inherits**](/Features/Language/Inheritance.md#inherits-for-complete-oop) may replace with an **Overrides** clause. Meaningful only on a member of a class that participates in an **Inherits** hierarchy.

*name*
: Name of the **Sub**; follows standard variable naming conventions. The special name `New` declares an instance constructor --- see [Inheritance](/Features/Language/Inheritance.md) for chained construction with `*baseclass*.New(...)`.

*callconv*
: *optional* The calling convention: **CDecl**, **ThisCall** or **FastCall**. The default is stdcall. Needed when native code calls the procedure through a pointer, or when it implements an interface member declared with a convention. See [Calling Conventions](/Features/Advanced/API-Declarations.md#calling-conventions).

**Of** *typevars*
: *optional* One or more type variable names, following standard variable naming conventions. The names are separated by commas. Causes the procedure to be a generic **Sub**.

*arglist*
: *optional* List of variables representing arguments that are passed to the **Sub** procedure when it is called. Multiple variables are separated by commas. See [*arglist*](#arglist) below for syntax.

*binding-clause*
: *optional* (twinBASIC) One of three trailing clauses that bind this body to a member declared elsewhere:

  - **Handles** *object*.*event* [ **,** *object*.*event* … ] --- connects this **Sub** as a handler for the named event(s), replacing the traditional `Object_Event` naming convention. See [**Handles** statement](/tB/Core/Handles.md).
  - **Implements** *iface*.*member* [ **,** *iface2*.*member2* … ] --- provides the body for the named [**Interface**](/tB/Core/Interface.md) (or [**Class**](/tB/Core/Class.md)) member, replacing the traditional `Iface_Member` naming convention. A comma-separated list permits one body to satisfy several interfaces' members at once. See [**Implements** statement](/tB/Core/Implements.md).
  - **Overrides** *base*.*member* --- supplies the body for an **Overridable** *member* inherited via [**Inherits**](/Features/Language/Inheritance.md#inherits-for-complete-oop). Combine with **Overridable** on the same header to allow further-derived classes to override again.

*statements*
: *optional* Any group of statements to be executed within the **Sub** procedure.

**[Exit Sub](/tB/Core/Exit.md)**
: *optional* Immediately returns from the **Sub** procedure. (A bare [**Return**](/tB/Core/Return.md) statement does *not* exit a **Sub** --- it is reserved for the [**GoSub...Return**](/tB/Core/GoSub-Return.md) construct.)

### *arglist*

Syntax: One or more of  
[ **Optional** ] [ **ByVal** \| **ByRef** ] [ **[ParamArray](/tB/Core/ParamArray.md)** ] *varname* [ **()** ] [ **As** *type* ] [ **=** *defaultvalue* ]

**Optional**
: *optional* Indicates that an argument is not required. If used, all subsequent arguments in *arglist* must also be optional and declared by using the **Optional** keyword. **Optional** can't be used for any argument if **ParamArray** is used.

**ByVal**
: *optional* Indicates that the argument is passed by value. See [Passing arguments ByRef and ByVal](#passing-arguments-byref-and-byval).

**ByRef**
: *optional* Indicates that the argument is passed by reference. **ByRef** is the default unlike in Visual Basic .NET.

**[ParamArray](/tB/Core/ParamArray.md)**
: *optional* Used only as the last argument in *arglist* to indicate that the final argument is an **Optional** array of **Variant** elements. The **ParamArray** keyword permits passing an arbitrary number of arguments. It may not be used with **ByVal**, **ByRef**, or **Optional**.

*varname*
: Name of the variable representing the argument; follows standard variable naming conventions.

*type*
: *optional* Data type of the argument passed to the procedure; may be **Byte**, **Boolean**, **Integer**, **Long**, **Currency**, **Single**, **Double**, **Decimal**, **Date**, **String** (variable length only), **Object**, **Variant**, a specific object type, or the name of a generic type argument. If the parameter is not **Optional**, a user-defined type may also be specified.  
If the name of a generic type parameter is used, it becomes bound to the concrete type of the argument passed to the procedure. The name binding has the scope of the body of the procedure.

*defaultvalue*
: *optional* Any constant or constant expression. Valid for **Optional** parameters only. If the type is an **Object**, an explicit default value can only be **Nothing**.

If not explicitly specified by using **Public**, **Private**, or **Friend**, **Sub** procedures are public by default.

If **Static** isn't used, the value of local variables is not preserved between calls.

The **Friend** keyword can only be used in class modules. However, **Friend** procedures can be accessed by procedures in any module of a project. A **Friend** procedure does not appear in the type library of its parent class.

**Sub** procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The **Static** keyword usually is not used with recursive **Sub** procedures.

All executable code must be in procedures. A **Sub** procedure cannot be defined inside another **[Sub](/tB/Core/Sub.md)**, **[Function](/tB/Core/Function.md)**, or **[Property](/tB/Core/Property.md)** procedure.

The **[Exit Sub](/tB/Core/Exit.md)** statement causes an immediate exit from a **Sub** procedure. Program execution continues with the statement following 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.

A **Sub** procedure is called by using the procedure name followed by the argument list. See the **[Call](/tB/Core/Call.md)** statement for specific information about how to call **Sub** procedures.

Variables used in **Sub** procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using **Dim** or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything defined at the module level has the same name. When a procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that the procedure is referring to that module-level name. To avoid this kind of conflict, explicitly declare variables. Use an **[Option Explicit](/tB/Core/Option.md#Explicit)** statement to force explicit declaration of variables.

> [!NOTE]
> **GoSub**, **GoTo**, and **Return** cannot enter or exit a **Sub** procedure. Use [**Exit Sub**](/tB/Core/Exit.md) to leave a **Sub** early.

### Passing arguments ByRef and ByVal
{: index="ByRef; ByVal" }

An argument is passed [by reference](/tB/Gloss.md#by-reference) unless its parameter is declared **ByVal**. A **ByRef** parameter is another name for the caller's variable, so when the procedure assigns to it, the caller's variable changes. A **ByVal** parameter is a copy: the procedure can change it freely, and the caller's variable keeps its value.

**ByRef** reaches the caller's variable only when the caller passes a variable, an array element, or a field of a user-defined type. A constant, an expression, or a variable enclosed in its own parentheses is evaluated into a temporary copy, and the procedure's changes to that copy are lost.

For an object, what is passed is the reference. The procedure can change the object's properties either way, since both references point at the same object. Only a **ByRef** parameter lets the procedure **Set** the caller's variable to a different object.

This is how a procedure hands back more than one result; see [Returning more than one value](/tB/Core/Function.md#returning-more-than-one-value).

```tb check_build
Sub AddOne(ByRef Counter As Long, ByVal Copy As Long)
    Counter = Counter + 1   ' Changes the caller's variable.
    Copy = Copy + 1         ' Changes only the local copy.
End Sub

Sub TryAddOne()
    Dim a As Long, b As Long
    AddOne a, b
    Debug.Print a, b        ' 1  0
    AddOne (a), b           ' The parentheses pass a copy of a.
    Debug.Print a, b        ' 1  0
End Sub
```

### Optional arguments and default values
{: index="optional parameters" }

A parameter declared **Optional** can be left out of a call. Give it a *defaultvalue* in its declaration, and the procedure sees that value whenever the caller leaves the argument out. An **Optional** parameter of type **Variant** with no default can instead be tested with [**IsMissing**](/tB/Modules/Information/IsMissing.md), which returns **True** when the argument was left out.

A caller leaves out an argument by leaving its place empty between commas, or by passing the others as [named arguments](/tB/Core/Call.md#named-arguments).

```tb check_build
Sub Greet(Name As String, Optional Greeting As String = "Hello", Optional Suffix As Variant)
    If IsMissing(Suffix) Then Suffix = "!"
    Debug.Print Greeting & ", " & Name & Suffix
End Sub

Sub TryGreet()
    Greet "Ada"                 ' Hello, Ada!
    Greet "Ada", "Hi"           ' Hi, Ada!
    Greet "Ada", , "?"          ' Hello, Ada?
End Sub
```

### Example

This example uses the **Sub** statement to define the name, arguments, and code that form the body of a **Sub** procedure.

```tb check_build
' Sub procedure definition.
' Sub procedure with two arguments.
Sub SubComputeArea(Length As Double, TheWidth As Double)
    Dim Area As Double ' Declare local variable.

    If Length = 0 Or TheWidth = 0 Then
        ' If either argument = 0.
        Exit Sub ' Exit Sub immediately.
    End If

    Area = Length * TheWidth ' Calculate area of rectangle.
    Debug.Print Area ' Print Area to Debug window.
End Sub
```

### See Also

- [**Call** statement](/tB/Core/Call.md)
- [**Function** statement](/tB/Core/Function.md)
- [**Property** statement](/tB/Core/Property.md)
- [**Exit** statement](/tB/Core/Exit.md)
- [**Return** statement](/tB/Core/Return.md)
- [**Implements** statement](/tB/Core/Implements.md)
- [**Handles** statement](/tB/Core/Handles.md)
- [**Protected** statement](/tB/Core/Protected.md)
- [Handler Method Syntax](/Features/Language/Handlers.md)
- [Inheritance](/Features/Language/Inheritance.md)
- [Generics](/Features/Language/Generics.md)
