Home > Software engineering >  Returning several variables from a Sub or Function and passing them to a different Sub
Returning several variables from a Sub or Function and passing them to a different Sub

Time:06-07

I have roughly laid out the following code in VBA:

Sub Main()
Sheets("SheetA").Range("A1") = Test(250) 

I want this to be Param_A from Test(25)

Sheets("SheetA").Range("B1") = Test(250)

I want this to be Param_B from Test(250)

End Sub

Sub Test(speed)
Param_A = 1 * speed
Param_B = 2 * speed
End Sub

I want Test() to return Param_A and Param_B such that I can pass those to Main(). Param_A and Param_B will vary depending on what speed I input into Test()

I feel like this should be such a simple task, yet I cannot get my head around how VBA approaches this. I have read that I can use either a Sub or Function, yet neither seem to work here....

Please can someone help?

Thank you!

CodePudding user response:

Return the values by reference:

Sub Test( _
    Byval speed As Double, _
    ByRef Param_A As Double, _
    ByRef Param_B As Double)

    Param_A = 1 * speed
    Param_B = 2 * speed

End Sub

Then:

Sub Main()

    Dim Param_A As Double
    Dim Param_B As Double

    speed = 250
    Test speed, Param_A, Param_B

    Sheets("SheetA").Range("A1") = Param_A
    Sheets("SheetA").Range("B1") = Param_B

End Sub
  •  Tags:  
  • vba
  • Related