Marc van der Peet
Marc van der Peet

Reputation: 1

Return a variable by a function and store it a new variable

I want to create two functions: one should "produce" a number and the other should perform a function with as parameter this number.

I got the following code

sub get_number()
  Dim x as Integer
  x = 3
  return x
end sub

But I cant get this to return a numeric value because it throws a compile error. Any thoughts on how I can get this function to return a x value and store it in a new variable (fe y()

Upvotes: 0

Views: 839

Answers (2)

Dave
Dave

Reputation: 4356

Sub can't return a value; use a Function:

Function get_number()
    Dim x as Integer
    x = 3
    get_number = x
End Function

myNumber = get_number()
MsgBox myNumber ' will return the 3

Or you can stick with the Sub and handle the return value with a parameter (which you'll have to define in the calling function or earlier)

Sub get_number(byRef myNumber) ' accepts myNumber as a parameter and returns its value
  Dim x as Integer
  x = 3
  myNumber = x
End Sub

Upvotes: 1

Rory
Rory

Reputation: 34035

You need to use a function, not a Sub, and assign the return value to the name of the function:

Function get_number()
  Dim x as Integer
  x = 3
  get_number = x
end Function

then use:

y = get_number

in your other code.

Upvotes: 1

Related Questions