tags:

views:

114

answers:

2

I don't normally use VB, and even less vba for excel, but I'm writing a function inside a macro and seem to not understand even the basics of creating a function

For example

Public Function test() As Integer
    return 1
End Function

This gives a compile error.

This is profoundly stupid, but how do I make a function return an integer in vba?

+2  A: 

You need to set the name of your function to the value like this:

Public Function test() As Integer
    test=1
End Function
Dan
+3  A: 

VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:

test = 1

(Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.)

froadie
Why the downvote...?
froadie
Actually you answered the question more clearly with extra information (which could potentialy lead to another question from new to VBA guy). Keep up the good work
Adarsha
Sorry, It seemed like you just answered the same thing as my answer, which I had first, but just adding the fact that it doesn't break out of the function. It is a nice addition, I just thought it'd be more appropriate as a comment. I'm not sure what the proper etiquette is, I guess it was a bit rude to downvote for just that, because it is a good answer, but it won't let me undo it.
Dan
@Dan - I wasn't aware that you had posted the same answer, it wasn't there when I posted mine. We must have posted it around the same time. If I had seen your answer before posting mine I would've definitely just added it as a comment
froadie