ByRef and ByVal in Function
we can pass arguments to a procedure or function by reference or by value. By default VBA passes arguments by reference.ByRef = in By Ref. we are not handing over a copy of the original variable but pointing to the original variable. if any change happen to the variable it will change the original value of the variable
ByVal = in ByVal. we are handing over a copy of the original variable . if any change happen to the variable it will not impact on the original value of the variable. orignal value will remain same.
Byref Example
|
Function change(ByRef x As Integer)
x = x * 3
change = x
End Function
Sub byref_demo()
Dim x As Integer
x = 5
Debug.Print "value from the change function " &
change(x)
Debug.Print "value from this sub procedure " & x
End Sub
|
you can see in this example we are giving value by reference, and at the end of the execution both value are returning same, that mean original value of x is changed from 5 to 15
ByVal Example
Function change(ByVal x As Integer)
x = x * 3
change = x
End Function
Sub byval_demo()
Dim x As Integer
x = 5
Debug.Print "value from the change function " & change(x)
Debug.Print "value from this sub procedure " & x
End Sub
|
you can see in this example we are giving value by value, and at the end of the execution both value are different, function is returning the value 15 and sub procedure is returning the original value of x which is 5, that mean original value of x is not changed when we pass the argument as byval
0 Comments