Microsoft Office Tutorials and References
In Depth Information
6.3.3 ByRef Versus ByVal Parameters
However, VBA can also use named arguments , in which case the previous call would be written
SaveAs FileName:="c:\temp\test.xls", _
CreateBackup:=True, _
Note the special syntax for named arguments, in particular, the colon before the equal sign.
This function call is a great improvement over the positional argument version. In general, the
advantages of named arguments over positional arguments are threefold:
Named arguments can improve readability and clarity.
Blank spaces (separated by commas) are required for missing optional arguments when
using a positional declaration, but not when using named arguments.
The order in which named arguments are listed is immaterial, which, of course, is not the
case for positional arguments.
Named arguments can improve readability quite a bit and are highly recommended. However,
they can require considerably more space, so for the short examples in this topic, we usually will
not use them.
6.3.3 ByRef Versus ByVal Parameters
Parameters come in two flavors: ByRef and ByVal . Many programmers do not have a clear
understanding of these concepts, but they are very important and not that difficult to understand.
To explain the difference, consider the two procedures in Example 6-4 . ProcedureA simply sets
the value of the module-level variable x to 5, displays that value, calls the procedure AddOne with
the argument x , and then displays the value of x again.
Example 6-4. Testing the ByVal and ByRef Keywords
Sub ProcedureA()
x = 5 ' Set x to 5
MsgBox x ' Display x
Call AddOne(x) ' Call AddOne
MsgBox x ' Display x again
End Sub
Sub AddOne(ByRef i As Integer)
i = i + 1
End Sub
Note the presence of the ByRef keyword in the AddOne procedure declaration. This keyword
tells VBA to pass a reference to the variable x to the AddOne procedure. Therefore, the AddOne
procedure, in effect, replaces its parameter i by the variable x . As a result, the line:
i = i + 1
effectively becomes:
x = x + 1
So, after AddOne is called, the variable x has the value 6.
Search JabSto ::

Custom Search