How Do I Set (or Leave Unchanged) Default Values of Function Parameters?

To specify a default value for a function or subroutine's parameters, simply place the keyword Optional in front of the parameter or parameters and include a value that you wish to be its default value as the following illustrates:

Function Add _
Optional SecondNumber As Integer = 5) _

As Integer

As you can see, the parameter has the keyword Optional placed in front of it and an "= 5" after it. This means that if this function is called without any arguments, then when the function uses the variable SecondNumber its value will be five; however, if the function does have a value passed into it then that value will be used.

There is an important rule with using default parameters: if a parameter has a default value, then all other parameters after it (going from left to right) in the parameter list must also have default values. The following demonstrates this:

'This is incorrect; because if the first parameter
'has a default value then the second parameter
'also needs one.

Add(Optional FirstNumber As Integer = 7, _
As Integer)

'Now both have a default value and this is correct.
Add(Optional FirstNumber As Integer = 7, _
SecondNumber As Integer = 9)

The following example demonstrates a function which adds two numbers together and returns the results, but uses the default value of zero for any missing arguments:

Sub main

Dim Result As Integer
'Pass two number to the function

Result = Add(3,5)

'Result will be the two numbers

'added together


'Pass only one number. The default of

'zero will be used for the missing number

Result = Add(3)

'Result will be the number

'added with the default zero

MsgBox Str

'Don't passing any numbers to

'the function. The default zeroes

'will be used

Result = Add()

MsgBox Str

End Sub

'This function will take two integers and
'return the sum to the calling function. If
'any argument is absent, then the corresponding
'default value (zero in this case) will be used.

Add _
Optional FirstNumber As Integer = 0, _
SecondNumber As Integer = 0) As Integer

'If either parameter doesn't have a value
'passed to it then zero will be used.

Add = FirstNumber + SecondNumber

End Function