Passing Objects In
When you declare a variable with an Object data type it can assigned a value using the Set keyword.
Dim myObject As Object
Set myObject = ThisWorkbook
It is possible to pass an object into a subroutine or function
Call PassingIn(myObject)
Public Sub PassingIn(ByRef myObject As Object)
Debug.Print TypeName(myObject)
'Workbook
End Sub
Always By Reference
It doesn't matter if you pass in this variable using ByVal or ByRef, the object is always passed by reference.
This means that a reference pointer is passed in and not a copy of the actual object.
ByRef vs ByVal
There is a difference though between the following 2 lines
Public Sub PassingIn(ByRef myObject As Object)
Public Sub PassingIn(ByVal myObject As Object)
ByRef - Passes in the original reference pointer
ByVal - Passes in a copy of the reference pointer
The object will be modified in both cases
ByRef - Caller variable can be reassigned
ByVal - Caller variable cannot be reassigned
Example
Public Sub Testing()
Dim myObject As Object
Set myObject = Range("A1")
Call PassedByRef(myObject)
Debug.Print myObject.Address '$B$1 - changed
myObject.Value = 20
Set myObject = Range("A1")
Call PassedByRef(myObject)
Debug.Print myObject.Address '$A$1 - unchanged
myObject.Value = 20
End Sub
Public Sub PassedByRef(ByRef r As Range)
Set r = Range("B1")
End Sub
Public Sub PassedByVal(ByVal r As Range)
Set r = Range("C1")
End Sub
© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext