Consulting

Results 1 to 3 of 3

Thread: Passing Objects: ByRef / ByVal

  1. #1
    VBAX Contributor
    Joined
    Jun 2007
    Posts
    150
    Location

    Passing Objects: ByRef / ByVal

    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?

  2. #2
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    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.)

  3. #3
    Quote Originally Posted by mikerickson
    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.
    [vba]Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    'code
    End Sub[/vba]
    This makes me a little bit confused, considering that you can change everything about Target, as if it was a ByRef-passed object.

    Jimmy
    Last edited by JimmyTheHand; 06-27-2008 at 05:37 AM.
    -------------------------------------------------
    The more details you give, the easier it is to understand your question. Don't save the effort, tell us twice rather than not at all. The amount of info you give strongly influences the quality of answer, and also how fast you get it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •