VBA Optional Arguments


Example

Some procedures have optional arguments. Optional arguments always come after required arguments, but the procedure can be called without them.

For example, if the function, ProcedureName were to have two required arguments (argument1, argument2), and one optional argument, optArgument3, it could be called at least four ways:

' Without optional argument
result = ProcedureName("A", "B")

' With optional argument
result = ProcedureName("A", "B", "C")

' Using named arguments (allows a different order)
result = ProcedureName(optArgument3:="C", argument1:="A", argument2:="B")

' Mixing named and unnamed arguments 
result = ProcedureName("A", "B", optArgument3:="C")

The structure of the function header being called here would look something like this:

Function ProcedureName(argument1 As String, argument2 As String, Optional optArgument3 As String) As String

The Optional keyword indicates that this argument can be omitted. As mentioned before - any optional arguments introduced in the header must appear at the end, after any required arguments.

You can also provide a default value for the argument in the case that a value isn't passed to the function:

Function ProcedureName(argument1 As String, argument2 As String, Optional optArgument3 As String = "C") As String

In this function, if the argument for c isn't supplied it's value will default to "C". If a value is supplied then this will override the default value.