While calling a subroutine or function, each argument can be passed by reference or by value. When an argument is passed by reference, the called procedure can change the value of the variable. The change persists after the procedure is called. When an argument is passed by value, any changes that the called procedure makes to the value of the variable do not persist after the procedure is called.
In a Sub or Function declaration, each parameter can be specified as ByRef or ByVal. If neither is specified, the default is ByRef.
If ByVal is specified, the corresponding argument is always passed by value when the subroutine is called.
If ByRef (or neither) is specified, the argument can be passed by reference or by value when the subroutine is called. The argument is passed by value if it is enclosed in parentheses, and if the parentheses do not apply to the parameter list. The argument is also passed by value if the variable sent as an argument is in a class. Otherwise, it is passed by reference.
The following table summarizes this.
Keyword specified | Argument is passed by |
ByVal | Value. |
ByRef (default) | Reference or value, depending on other factors. |
In the following example, the ByRef keyword is specified for the MyParam variable. When the subroutine is called, a reference is passed to the variable MyArg. When the subroutine changes the value of MyParam, this also changes the value of MyArg. The local variable MyParam becomes an alias for MyArg.
MyParam = 5
End Sub
Dim MyArg
MyArg = 123
TestSub MyArg
' MyArg in changed in TestSub to 5.
In the following example, the ByVal keyword is used. Therefore, the argument is passed by value. The subroutine changes the value of MyParam. However, the value of MyArg remains unchanged.
MyParam = 5
End Sub
Dim MyArg
MyArg = 123
TestSub MyArg
' MyArg is still 123.
No comments:
Post a Comment