The difference between ByVal and ByRef
To say that the difference between the two is what it is passing, perhaps this sentence is very vague, let us explain.
1, byval-by value, that is to say, we pass to the function is a simple numerical past, the following code to help us understand:
The code is as follows |
Copy Code |
Sub Run () Dim I as Integer i = 1 Add I MsgBox I End Sub Sub Add (ByVal i as Integer) i = i + 3 End Sub |
The code above, the I value shown in the final dialog is still 1, because the compiler, or the VBA parser, creates a copy of the I pass to the calculation in the add process.
2, byref-by address delivery, pointers in languages such as C, C + +, or objectpascal, that pass a global memory address to a function (process), and when the function modifies the parameters you pass in the operation, the value is extended to facilitate understanding, Let's take a look at the following code:
The code is as follows |
Copy Code |
Sub Run () Dim I as Integer i = 1 Add I MsgBox I End Sub Sub Add (ByRef i as Integer) i = i + 3 End Sub |
This code has only one difference from the previous code, that is, the transfer of the parameter I in the Add process was modified by ByVal to ByRef, but the result of the operation would be completely different, the MsgBox dialog box, and finally the result would be 4.
Through the above two codes, do we have a better understanding of the two parameters of ByVal and ByRef?
Attention matters
Worthy of our children's shoes note that the default parameter pass is ByRef vb/vba, which means that byref can be omitted, which is not the same as other languages.