ByVal or ByRef - Integers
When you declare a variable with an Integer data type it can be passed in using either ByVal or ByRef.
ByRef
Passing an Integer into a subroutine using ByRef allows the original variable to be changed.
Public Sub Passing_Integers1()
Dim myNumber As Integer
myNumber = 10
myNumber = myNumber + 10
myNumber = myNumber + 10
Debug.Print myNumber '30
Call ByReference(myNumber)
Debug.Print myNumber '0
End Sub
Public Sub ByReference(ByRef myNumber2 As Integer)
'this changes the original
myNumber2 = myNumber2 + 10
'this changes the original
myNumber2 = 0
End Sub
ByVal
Passing an Integer into a subroutine using ByVal prevents the original variable from being changed.
In this example we are going to create a new integer data type and then pass this integer into two subroutines.
The first subroutine will have the integer passed ByVal and the second one will be passed by ByRef.
Public Sub Passing_Integers2()
Dim myNumber As Integer
myNumber = 10
myNumber = myNumber + 10
myNumber = myNumber + 10
Debug.Print myNumber '30
Call ByValue(myNumber)
Debug.Print myNumber '30
End Sub
Public Sub ByValue(ByVal myNumber2 As Integer)
'this changes just the local copy
myNumber2 = myNumber2 + 10
'this changes just the local copy
myNumber2 = 0
End Sub
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext