ByVal or ByRef - Classes
The Class data type is a reference data type.
When you declare a variable with a Class data type it can be passed in using either ByRef or ByVal.
In VBA all reference data types are passed by reference although there is a subtle difference.
Although it is a Reference data type there is a subtle difference between passing ByRef vs ByVal 'myClassModule class module
'myClassModule
Private mstrPropertyName As String
Property Get Property_Name() As String
Property_Name = mstrPropertyName
End Property
Property Let Property_Name(rData As String)
mstrPropertyName = rData
End Property
ByRef
Passing a class into a subroutine using ByRef allows the original class to the changed.
Public Sub Passing_Classes1()
Dim myClass As myClassModule
Set myClass = New myClassModule
myClass.Property_Name = "before"
Debug.Print myClass.Property_Name
Call ByReference(myClass)
Debug.Print myClass.Property_Name
End Sub
Public Function ByReference(ByRef theClass As myClassModule)
'this is the original
'the class has been passed by reference so this change is made to the original class
theClass.Property_Name = "after"
'the class has been passed by reference so this changes the original
'the new class reference will be passed back
'we can see this because the second Debug.Print displays "<blank>"
Set theClass = New myClassModule
End Function
ByVal
Passing a class into a subroutine using ByVal allows the original class to the changed.
Public Sub Passing_Classes2()
Dim myClass As myClassModule
Set myClass = New myClassModule
myClass.Property_Name = "before"
Debug.Print myClass.Property_Name
Call ByValue(myClass)
Debug.Print myClass.Property_Name
End Sub
Public Function ByValue(ByVal theClass As myClassModule)
'the class has been passed by value so this change is made to the original class
theClass.Property_Name = "after"
'the class has been passed by value so this changes just the local copy
'any changes made to the class reference (ie new assignment) is contained within the subroutine
'we can see this because the second Debug.Print display "after"
Set theClass = New myClassModule
End Function
What is the difference between ByVal and ByRef in the context of Class data types ?
There is a difference between declaring a variable with a Variant data type as opposed to a Class data type.
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext