+ Reply to Thread
Results 1 to 3 of 3

Passing Variables out of Subroutines

  1. #1
    Registered User
    Join Date

    Question Passing Variables out of Subroutines

    Is is possible to pass variables out of a subroutine? I know how to pass them in, but I'm not sure how to get them out. Thanks!

  2. #2
    Forum Moderator Leith Ross's Avatar
    Join Date
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Hello Cmcconnehey,

    I am not sure what you're asking. VBA has both a Sub procedure and a Subroutine construct called by the keyword GoSub. My assumption is you are referring to Sub procedures. A variable would be passed to another Sub or Function by including the variable in the call to it, provided of course it takes arguments. The other way would be to declare a variable as Public in the declarations section of a Standard Module. This way any routine can access the variable as well as change it. If I didn't answer your question, you should post an example of what you want to do.

    Leith Ross

  3. #3
    Forum Guru mikerickson's Avatar
    Join Date
    Davis CA
    MS-Off Ver
    Excel 2011
    You can pass a variable out of a sub either by using Module-wide or Public variables. Or the result can be passed through the arguments.

    Module wide variable are declared OUTSIDE the sub, as in this example. resultValue can be used by any routine in the module.
    Please Login or Register  to view this content.
    If the statment were
    Please Login or Register  to view this content.
    resultValue could be used by any routine in any module. Public variable are sometimes used to pass values to/from a Userform.

    The argument method passes the result as an argument of the sub.
    Please Login or Register  to view this content.
    Note that the returning value cannot be passed By Val, it must be passed By Ref.

    I use this technique when a "function" returns two values. The following routine takes the polar coordinates of a point and returns the rectangular coords.
    Please Login or Register  to view this content.
    finaly, you can return the output value in the same variable as the input value. Running testOne and testTwo shows the difference between ByVal and ByRef arguments. (It impressed me the first time I ran it.)
    Please Login or Register  to view this content.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1