I am studying/learning the bahavior of ByVal and ByRef when it comed to working with a call object. So I created this class PersonModel
Private Type TPerson
firstName As String
lastName As String
End Type
Private this As TPerson
Public Property Get firstName() As String
firstName = this.firstName
End Property
Public Property Let firstName(ByVal strNewValue As String)
this.firstName = strNewValue
End Property
Public Property Get lastName() As String
lastName = this.lastName
End Property
Public Property Let lastName(ByVal strNewValue As String)
this.lastName = strNewValue
End Property
Public Property Get fullName() As String
fullName = this.firstName & " " & this.lastName
End Property
And I made a standard module trying to see how the value of an object be affected if it's passed as ByVal or ByRef in s subroutine. Here's the code in standard module
Private passedPerson As PersonModel
Public Sub StructureType()
Dim Object1 As PersonModel
Dim Object2 As PersonModel
Set Object1 = New PersonModel
With Object1
.firstName = "Max"
.lastName = "Weber"
Debug.Print .fullName 'gives Max Weber
End With
Set Object2 = Object1 'Object2 references Object1
Debug.Print Object2.fullName 'gives Max Weber
passByVal Object1
' First Call
Debug.Print passedPerson.fullName 'gives Max Weber
With Object2
.firstName = "Karl"
.lastName = "Marx"
Debug.Print .fullName 'gives Karl Marx
End With
'Second Call
Debug.Print passedPerson.fullName 'gives Karl Marx
End Sub
Private Sub passByVal(ByVal person As PersonModel)
Set passedPerson = New PersonModel
Set passedPerson = person
End Sub
I was just expecting that in the second call part of the code Debug.Print passedPerson.fullName
will give me an unchanged value of "Max Weber". But instead, it's giving the new value "Karl Marx". Even if I change the code of the procedure passByVal to:
Private Sub passByVal(ByVal person As PersonModel)
Dim newPerson As PersonModel
Set newPerson = New PersonModel
Set newPerson = person
Set passedPerson = newPerson
End Sub
Second call part of the code Debug.Print passedPerson.fullName
is still giving "Karl Marx". Regardless of changing ByVal
to ByRef
, it's still giving the same result.
I have two questions:
1. Is this how it should really work?
2. What am I doing wrong if my aim is to keep the value of the variable passedPerson
to "Max Weber"?