Bjørn H. Sandvik
Bjørn H. Sandvik

Reputation: 543

Is there a global keyword similar to C's "Return" for returning values from a VBA function?

Not being entirely sure how to best articulate the title, I'll try to explain myself better here..

I do a lot of cutting and pasting of templated chunks of code that I repeat in most of my functions - typically, error handling and debugging facilities in general.

As returning values from functions is done by declaring MyFunction = "SomeValue", I figure there is little harm in asking if there is any way of generalizing away "MyFunction" (in this example)?

E.g.:

Function MyFunction() As String
    On Error GoTo ErrHandler

    ' <..do stuff here..>
    Exit Function

ErrHandler:
    MyFunction = "Something bad happened"

End Function

So if I were to copy this chunk as a template for all my future functions, I would love not having to replace every occurrence of the word MyFunction in the code.. So I wonder if there is some arbitrary keyword like Me to return the function's resultant value like you would use the Return function in C.

Hope that made sense!

Upvotes: 1

Views: 203

Answers (1)

paxdiablo
paxdiablo

Reputation: 882226

No, that's the way the language is specified. If you want to return a value from the X function, you "assign" the value to X:

Function MyFunction() As String
    MyFunction = "Hello"
End Function

And keep in mind, that doesn't actually finish execution of your function, if you want that, you need to explicitly exit the function as well:

Function MyFunction() As String
    If a = 1 Then
        MyFunction = "Hello"
        Exit Function
    End If
    MyFunction = "Bye"
End Function

Without the exit function line in the above code, the function will return Bye rather than Hello.

If you really want a new keyword to do the work of both those statements, you could petition Microsoft for a change, but I don't think much of your chances since there's already a perfectly good way of doing it :-) They're likely to just come back and tell you to use C++ or C# if you want those constructs.

Upvotes: 2

Related Questions