Example explain the ByVal in Vb/vba in a byref argument

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.