PDA

View Full Version : Passing Objects: ByRef / ByVal



Dr.K
06-26-2008, 08:38 AM
Ok, I understand passing variables ByVal and ByRef, but does it really work the same way for passing Objects?

I've gotten errors by trying pass Objects either way, so now I don't declare either type when passing Objects. Actually, the whole thing is so confusing that when I need to pass Objects, I usually just make them module-level Private variables.

How would a ByVal Object even work?
-It just makes a completely seperate copy of the Object?
-Is the Object properly destroyed at the end of the procedure?
(or do I have to Set it equal to Nothing before the Sub ends)

-What about Object relationships? Do they come too?
Example: I pass an Outlook Mail Object to a sub, can I work my way back up the Object tree to the Outlook Application? Or is the copy some kind of wierd orphan Object?

mikerickson
06-26-2008, 12:09 PM
Objects can only be passed ByRef.

Consider a sheet. There is a sheet, it is a unique object.
A variable (aSheet) can be assigned to that object.
Let that variable be passed to a function, where it has the variable name oneSheet.

If aSheet were to be passed ByVal, changes to oneSheet would not be reflected in aSheet. But aSheet and oneSheet are both the same object.

To pass an object ByVal, one would have to create a new instance of that object.

(Similarly, Let assigns variables ByVal, but Set assignes them ByRef.)

JimmyTheHand
06-27-2008, 05:26 AM
Objects can only be passed ByRef.

What you said makes sense, yet I found it isn't always true. See workbook/worksheet events. Are they just special exceptions? Or how can it be explained.
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'code
End Sub
This makes me a little bit confused, considering that you can change everything about Target, as if it was a ByRef-passed object.

Jimmy