Create Your Own Functions in Excel VBA
Create Your Own Functions in Excel VBA
Functions are closely related to the Subs you learned about in a previous section, and are set up
in a similar way. The difference is that functions return a value (like the MsgBox function)
whereas Subs don't return a value - they just get on and execute the code. You use a function
when you want a chunk of code to return some sort of answer for you.
You start with the word Function. After a space, you need to come up with a name for your
function. Like Sub names, this should be something relevant to what the function does.
After the name of your function, you need a pair of round brackets. Just like Subs, the round
brackets are used for any arguments you want to pass over to your function.
One of the big differences between setting up a Sub and setting up a Function is the return type at
the end. This is exactly the same as setting up a variable type. So you can have As String, or As
Boolean, or As Integer - any of the types you can use with ordinary variables can also be used
with functions. If you miss off the As Type at the end then the function will be As Variant.
The function name you come up with is like a variable: whatever answer you want your function
to produce will be stored in the function name.
function_name = value