Visual Basic - Use The Optional Keyword To Identify Parameters That The User Isn't Required To Supply (VB 6/.NET)


If you'd like to have optional arguments in the argument list of your subroutine or function, you can do so quite easily with the Optional keyword. The syntax for this keyword is:


  • Function myFunctionOpt(Optional ByVal var1 _ As Object = val, Optional ByVal var2 As _ Object = val,...)

The Optional keyword should precede any argument the user isn't required to supply. The ByVal/ByRef keyword is required only for VB.NET. If the user omits the argument when calling the function, VB uses the value in val as a default. The default value is also only required for Visual Basic .NET. Optional values must follow any required parameters in the function's parameter list. To call a function or subroutine containing optional parameters, enter a comma for each parameter even if you don't supply a value, like so:


  • myFunctionOpt(,7)

Go back