ByVal or ByRef - User Defined Types

When you declare a variable with a User Defined Type it can only be passed in using ByRef.
A user defined type is a value data type.
When you declare a variable with a User Defined data type it can only be passed in using ByRef.


ByRef

Passing a User Defined Type into a subroutine using ByRef allows the original variable to be changed.

Type udtType 
   Field1 As String
End Type

Public Sub Passing_UserDefinedTypes1()
   Dim myUserDefinedType As udtType
   myUserDefinedType.Field1 = "before"
   Debug.Print myUserDefinedType.Field1 'before
   
   Call ByReference(myUserDefinedType)
   Debug.Print myUserDefinedType.Field1 'after
End Sub

Public Sub ByReference(ByRef theUserDefinedType As udtType)
'this changes the original
   theUserDefinedType.Field1 = theUserDefinedType.Field1 & "more"
   
'this changes the original
   theUserDefinedType.Field1 = "after"
End Sub

ByVal

Passing a User Defined Type into a subroutine using ByVal is not possible
If you try and declare a user defined type parameter that is passed ByVal you will get a compile error.

Public Sub ByValue(ByVal theUserDefinedType As udtType) 
End Sub
microsoft excel docs

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext