I am trying to pass a variable from one function to another function.
My first thought is to use the ByRef declaration which I hear will pass arguments by reference in Visual Basic. I am unclear, however, on how to use it. Right now I have the following code.
Function number(x As Double) As Double
Dim z As Double
z = 10.5
number = x
End Function
Function triple(ByRef z As Double) As Double
z = z * 3
triple = z
End Function
Lets say A1=2.5
. If I say B1=number(A1)
then the answer is 2.5 which I expected it to be. I then say B2=triple(B1)
but then the answer is 7.5 instead of 31.5. I am not sure why it's taking the value of A1
instead of taking the value of the variable z
from the function number
.
Here's a screenshot of the worksheet
Thanks in advance.
The z inside the number function is gone by the time the function returns. The triple function just tipples the number passed, 2.5 times 3 which is what you are seeing. The tipple function has no idea of z. One way to share variables is to declare them outside of the functions. Dim z as double outside the function. But then if you pass z as the value of b1 which is 2.5 then you will get the same 7.5 just call triple, don't pass the value of b1
Dim z As Double