Consulting

Results 1 to 4 of 4

Thread: Solved: Passing variables between suns and functions

  1. #1
    VBAX Tutor
    Joined
    Nov 2007
    Posts
    291
    Location

    Solved: Passing variables between suns and functions

    Hello,

    In some functions i.e. GetChartSettings some of the variables are things you pass to the function and some of the variables are "filled" by the function and thus can be read by the calling sub

    Is there a way I can replicate this with my VBA functions i.e. the function might have four variables, two which the calling sub need to pass and two which the function return and thus the calling sub can read

    Thanks in advance
    Phil

  2. #2
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    Your calling sub needs to pass all 4 arguments, but the ones you want changed have to be passed ByRef.

  3. #3
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,876
    Two ways that come to mind,
    1. pass variables which are Global variables and get the sub (and functions too, I think) to change these values.
    2.Pass the variables to a Sub, but you don't have to have values in all of them:[vba]Sub test2()
    a = 3
    b = "Hello"
    'c is not defined
    d = 2
    mangle a, b, c, d
    Debug.Print a, b, c, d
    End Sub
    Sub mangle(aa, bb, cc, dd)
    aa = aa * 3
    bb = bb & aa
    cc = "A New String"
    dd = dd * 100
    End Sub[/vba] I think byref is the default.
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from you.

  4. #4
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    ByRef is the default, but it's better to be explicit I feel. For example:
    Sub testfunc()
       Dim lIn As Long, dIn As Double, lOut As Long, dOut As Double
       Dim bReturn As Boolean
       ' set input arguments
       lIn = 4
       dIn = 3.2
       bReturn = TestFunction(lIn, dIn, lOut, dOut)
       ' check output arguments
       MsgBox "lOut: " & lOut & "; dOut : " & dOut
    End Sub
    Function TestFunction(ByVal lInput As Long, ByVal dInput As Double, _
                         ByRef lOutput As Long, ByRef dOutput As Double) As Boolean
       lOutput = lInput
       dOutput = dInput
       TestFunction = True
    End Function

Posting Permissions

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