A Sub statement defines the subroutine’s name. It declares the parameters that the subroutine takes as arguments and defines the parameters’ data types. Code between the Sub statement and an End Sub statement determines what the subroutine does when it runs.

The syntax for defining a subroutine is as follows:

[attribute_list] [inheritance_mode] [accessibility]
Sub subroutine_name([parameters]) [ Implements interface.subroutine ]
    [ statements ]
End Sub

The following sections describe the pieces of this declaration.


The optional attribute list is a comma-separated list of attributes that apply to the subroutine. An attribute further refines the definition of a class, method, variable, or other item to give more information to the compiler and the runtime system.

Applying an attribute to a class, variable, method, or other code entity is sometimes called decorating the entity.

Attributes are specialized and address issues that arise when you perform very specific programming tasks. For example, the Conditional attribute means the subroutine is conditional upon the definition of some compiler constant. Example program AttributeConditional uses the following code to demonstrate the Conditional attribute:

#Const DEBUG_LIST_CUSTOMERS = True ' #Const DEBUG_LIST_EMPLOYEES = True Private Sub Form1_Load() Handles MyBase.Load ListCustomers() ListEmployees() txtResults.Select(0, 0) End Sub <Conditional("DEBUG_LIST_CUSTOMERS")> Private ...

Get Visual Basic 2012 Programmer's Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.