Passing objects ByRef or ByVal

confusion123

Active Member
Joined
Jul 27, 2014
Messages
400
In this article,

Passing Objects: ByRef / ByVal

it is claimed objects can ONLY be passed ByRef, (the second comment in the article) but the third comment states the following:

Code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) 

     'code

End Sub

so which is correct? Objects are passed ByRef or ByVal?

Thanks
 

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney
That's not strictly true in practice. When one is referring to an object, the byVal/byRef refers to the pointer of the object. To all intents and purposes this in effect means that objects are only passed byRef, there are situations however that this can catch you out. Consider:

Rich (BB code):
Sub test()
    
    Dim b As Collection
    Set b = New Collection
    
    If b Is Nothing Then
        Debug.Print "Object is Nothing"
    End If
    
    DeleteObjectVal b
    
    If b Is Nothing Then
        Debug.Print "Object is Nothing"
    End If
    
    DeleteObjectRef b
    
    If b Is Nothing Then
        Debug.Print "Object is Nothing"
    End If
    
End Sub

Sub DeleteObjectVal(ByVal obj As Object)
    Set obj = Nothing
End Sub

Sub DeleteObjectRef(ByRef obj As Object)
    Set obj = Nothing
End Sub
 
Last edited:
Upvote 0
Objects are always passed as a pointer to a memory location. If you pass an object ByVal, you pass a copy of the pointer, not a copy of the object. That means that you can still access all properties/methods of the object but you cannot change the original pointer to refer to a different object.
 
Upvote 0

Forum statistics

Threads
1,224,856
Messages
6,181,427
Members
453,040
Latest member
Santero

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top