Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Functions returning info 3

Status
Not open for further replies.

MrChopper

Programmer
Aug 11, 2004
20
US
Hi all-

Dumb question, but how would one retrieve info from a function call? If I had a function to add 2 numbers, how could I call that function, passing the two numbers, and return the result?
 



Hi,
Code:
...
  msgbox YourFunction(arg1, arg2)
...


Skip,
[sub]
[glasses] [red][/red]
[tongue][/sub]
 
Function AddMyNumbers(Number1 As Integer, Number2 As Integer) As Integer
AddMyNumbers = Number1 + Number2
End Function

Sub CallingProcedure()
Dim intAnswer as Integer

intAnswer = AddMyNumbers(3,5)

End Sub
 
Bah! Thanks guys, I knew it was something simple like that! :p
 
Another trick, if you need to return more than one value.
Code:
Sub ReturnTwoValues(ByRef Value1 as String, ByRef Value2 as String)
Value1 = "Monday"
Value2 = "Friday"
End Sub

Sub CallingProc()
Dim StartDOW as String, EndDOW as String
ReturnTwoValues StartDOW, EndDOW
End Sub
This is a "back door" workaround to the problem that a Function can only return one value. As such, it should be rigorously documented if used.

A few points: ByRef is the default (as opposed to ByVal) so is actually superfluous. ByRef arguments are actually pointers to the variable that is passed in. Therefore, any changes to the argument are actually made directly to the passed in variable. So, in the piece of code above, StartDOW will equal "Monday" and EndDOW will equal "Friday" once ReturnTwoValues is called.

Next, we're using a sub instead of a function. Since we're bypassing the more formal "front door" approach to returning values, we might as well bypass it altogether to avoid any confusion.

Again, I use this rarely, and document clearly what I'm up to when I do it.

HTH

Bob
 
>Since we're bypassing the more formal "front door" approach

In which case, rather than becoming a sub with no return value, we might like to adopt the approach taken by mnay of the API functions which is to return the values we are interested in in the passed parameters, and use the return value of the function to indicate sucess or some sort of failure.
 
<and use the return value of the function to indicate sucess or some sort of failure

Well, yes, that's very true. We'll call that an improvement. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top