Passing Arguments by Value
You can also use the ByVal or ByRef keyword to define how parameters are passed to your procedure. The important distinction is that ByVal takes a copy of the variable that is being passed and does not alter the original value of the variable within the subroutine or function. ByRef uses the original variable itself and any changes to the value that are made within the subroutine or function are reflected through the entire scope of the variable. The ByRef methodology can often lead to bugs that are hard to track down. Your function may alter the value of your variable, but this may not be apparent when you are looking at the chain of your code.
It is generally accepted by programmers that ByRef is not a good idea unless you know exactly what you are doing.
Function MyFunction (ByVal Target as String)
The ByVal keyword ensures that parameters are passed by value rather than by a reference to a value from a variable. Passing a value by reference can easily allow bugs to creep into your code. To demonstrate this, if you pass by reference using a variable name, the value of that variable can be changed by the procedure that the variable is passed to-for example,
x = 100 z = Adjust(x) Function Adjust(ByRef Target as Integer)
The variable x will be modified by what is going on within the function Adjust. However, if you pass by value, as shown here, only a copy of the variable is passed to the procedure:
x = 100 z = Adjust(x) Function Adjust(ByVal Target as Integer)
If the procedure changes this value, the change affects only the copy, not the variable itself. The variable x will always keep its value of 100.
Normally, you would not expect a function to modify an argument, but it can happen and can lead to hard-to-find bugs within the code. Sometimes you do require the function to modify the value of a variable, which is when it would be appropriate to use ByRef, but generally ByValue is used the most.