Full Version: return a value from a function
UtterAccess Discussion Forums > Microsoft® Office > Microsoft Excel
ryjyd
I know this is simple, but when I search for it, the answer will not come. Note this example:
CODE
sub somecode()
othernumber = 1
somenumber = changesomenumber(othernumber)
cells(1,1) = somenumber 'the number is 2
end sub
'
'
sub changesomenumber(changethis)
thisone = changethis + 1
'''''this is the part where I send thisone back
end sub


I get stuck at the part where I send the variable "thisone" back to the function "somecode()". How do I return the value of "thisone"? What is the code needed? Do I need to send something else back? Many thanks for the help given
ALaRiva
A Sub cannot return a value, only Functions can return values.

Try this:
CODE
Function changesomenumber(changethis As Integer)
changesomenumber = changethis + 1
end sub


You need to make sure and declare all datatypes for variables and arguments that you pass into the functions.

HTH, Thanks.
ryjyd
When you say declare all datatypes, I assume you mean "(changethis As Integer)". In my code, the first procedure should have a line of code stating: "Dim othernumber As Integer" before it's used. And finally, the act of using the function name as the name of a variable inside the function will send that value back to the procedure when I called that function... Do I have all of this right?
ALaRiva
Yes, that's what I meant about the declarations, however, even though you declared the datatype for the variable othernumber, you still need to declare the datatype for the argument that will be passed into the function. That's why I did the changethis As Integer.

Yes, just use the function name as if it was a variable to send the value back.

For Example
CODE
Function Test()

Test = "Some Value"

End Function


You may also want to declare what type of return you will get from the function, so it would be like this:
CODE
Function Test() As String
Test = "Some String"
End Function


HTH, Thanks.
ryjyd
Wonderful... Thanks so much for your help. You have a great weekend.
ALaRiva
You're Welcome . . . frown.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.