The Optional Keyword
In addition to the keywords ByVal and ByRef, you could also use the Optional
keyword to define a variable as not required, but passable.
In a function statement this might look like this
Public Function MyFunction(ByRef MyInteger As Integer, _ Optional MyNote
As String) As String
By doing as such, you would specify to the program that you don't have to insert
the MyNote variable for the function to actually perform an operation. You can
leave it to the user to provide specific additional elements for your statement
to evaluate.
The important thing to think about here is that ALL arguments passed as Optional
MUST be last in the statement definition. Every argument following the first
optional argument must also be an optional argument. All arguments can be optional,
but they can not be entered in mixed order.
To follow the principles of defaults in Visual Basic, I would say it is good
coding practice to keep ByRef first, since it is the default state, then followed
by ByVal arguments and at last the Optional arguments.
As you see form the end above, the final definition is that the function MyFunction
will return a value MyFunction As String as long you enter a correct and accepted
value for the MyInteger argument.
Default Values
A benefit of using the Optional keyword is the use of default values. This
can save on defining constants with yet another benefit. Constants can not change
values in the application. However providing specific default value to some statements
may well act as interchangeable constants.
Declaring constants in VB is not much different from variables however constants
are declared in the Declaration section of a form code or module.
Variables are declared inside Statements, while constants are declared prior
to any statements.
Const MyConstant As String = "A string constant"
In the same way as this declaration, you can define default values in the definition
part of a statement, but only for optional arguments.
To define the constant above as a default value only to be used in the following
function instead of defining it as a constant you could write;
Public Function MyFunction(ByRef MyInteger As Integer, _ Optional MyNote As
String = "A String Constant") As String
Also note the benefit with this action. You can now go in and change the default
value should you choose to do so. This would be impossible had you instead called
a constant inside the statement.