PDA

View Full Version : Solved: Passing variables between suns and functions



philfer
10-21-2009, 06:01 AM
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

Aflatoon
10-21-2009, 06:10 AM
Your calling sub needs to pass all 4 arguments, but the ones you want changed have to be passed ByRef.

p45cal
10-21-2009, 06:22 AM
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: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 I think byref is the default.

Aflatoon
10-21-2009, 06:24 AM
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