VBA Introduction to procedures


A Sub is a procedure that performs a specific task but does not return a specific value.

Sub ProcedureName ([argument_list])
End Sub

If no access modifier is specified, a procedure is Public by default.

A Function is a procedure that is given data and returns a value, ideally without global or module-scope side-effects.

Function ProcedureName ([argument_list]) [As ReturnType]
End Function

A Property is a procedure that encapsulates module data. A property can have up to 3 accessors: Get to return a value or object reference, Let to assign a value, and/or Set to assign an object reference.

Property Get|Let|Set PropertyName([argument_list]) [As ReturnType]
End Property

Properties are usually used in class modules (although they are allowed in standard modules as well), exposing accessor to data that is otherwise inaccessible to the calling code. A property that only exposes a Get accessor is "read-only"; a property that would only expose a Let and/or Set accessor is "write-only". Write-only properties are not considered a good programming practice - if the client code can write a value, it should be able to read it back. Consider implementing a Sub procedure instead of making a write-only property.

Returning a value

A Function or Property Get procedure can (and should!) return a value to its caller. This is done by assigning the identifier of the procedure:

Property Get Foo() As Integer
    Foo = 42
End Property