VBA - User Defined Functions
A function is a group of code that can be called n ' anywhere in your program. This eliminates the need to write the same code over and over again. This allows programmers to divide a large program into a number of small and manageable functions.
Besides the built-in functions, VBA also allows you to write user-defined functions. In this chapter, you will learn how to write your own functions in VBA.
A VBA function can have an optional return statement. This is necessary if you want to return a value from a function.
For example, you can pass two numbers into a function and then you can expect the function to return their multiplication in your calling program.
Note - A function can return several separate valueswith a comma as an array assigned to the name of the function itself.
Before using a function, we need to define that particular function. The most common way to define a function in VBA is to use the keyword Function followed by a unique function name and it may or may not carry a parameter list and a statement with End Function keyword, which indicates the end of the function. Here is the basic syntax.
Add a button and add the following function.
Function Functionname (parameter- list) instruction 1 instruction 2 instruction 3 ....... instruction n End Function
Add the following function that returns the zone. Note that a value / values can be returned with the name of the function itself.
FindArea Function (Length As Double, Optional Width As Variant) If IsMissing (Width) Then findArea = Length * Length Else findArea = Length * Width End If End Function
Calling a function
To call a function, call the function using the function name as shown below screenshot of the wing.
The output of the zone as shown below will be displayed to the user.