What are function procedures?
After discussing aboutĀ Sub ProceduresĀ and how to call them, this VBA Excel tutorial series will invite you to learn and understand how to create a function procedure or function procedure in VBA Excel.
Definition of Function Procedure
In the discussion of Macro VBA Excel, Procedure is a block of program code that contains certain command lines between the opening statement line and the closing statement of the procedure. You can read more details in the following series:Ā Excel VBA Module and ProcedureĀ .
A function procedureĀ in VBA Excel is one type of procedure that is marked with an opening statement āĀ FunctionĀ ā and ends with a āĀ End FunctionĀ ā statement.
In the process of working, theĀ function procedureĀ is actually the same as theĀ Sub ProcedureĀ that we discussed earlier. The main difference between these two types of procedures is thatĀ Function ProceduresĀ can generate a return value from their work processes that are stored in the procedure name.
The way a function procedure works is very similar to the default excel functions such as theĀ SUMĀ function ,Ā AVERAGEĀ function ,Ā MINāMAXĀ function and so on, where we can enter certain arguments into a procedure function, then the function performs calculations and then returns a result of that calculation.
Function procedures declared with the Public keyword can be used as excel formulas in an excel cell just like Excelās built-in functions. For this reason, function procedures are also known as Custom Functions and User Defined Functions (UDF) .
And for the same reason, in this blog I prefer to refer to the default worksheet function as a function and not an excel formula.
How to Create a Function Procedure
Perhaps you are asking how to make your own function or formula in excel?
If the default functions or the built-in functions that excel provides are not sufficient, you can create an excel function yourself. The trick is to create a custom function or user defined function (UDF) by creating a public function through VBA Excel.
The syntax or how to create a function procedure in a VBA module is as follows:
[Private|Public|Friend][Static] Function Function_Name ([List_Argument]) As [Return_Data_Type]
[Instructions/Program Code]
[Exit Function]
[Instructions/Program Code]
[Function_Name = Return_Value]
End Function
Each element that is in square brackets ā[ā¦]ā in the syntax of the function procedure above is optional , meaning that it can be used and can be ignored or not used.
A simple example of a function procedure is as follows:
Function areaSquare(length As Integer) As Long
Ā Ā Ā Ā Dim wide As Long
Ā Ā Ā Ā area = length * length
Ā Ā Ā Ā areaSquare = area
End Function
Element [Private|Public|Friend][Static]
Because it has been explained in several previous series, this element will not be discussed again. To learn what it means, please read the previous VBA Excel macro series materials.
Element āFunctionā
You must use this āĀ FunctionĀ ā text or element if you intend to create a Function procedure .
This element distinguishes the preparation of function procedures from other types of procedures.
Element āProcedure_Nameā
This section shows theĀ name of the procedure functionĀ that you created and that you should use. This function name will be used to call or be used on the worksheet. So name the function procedure that you created as wisely as possible. Ideally, please follow the example of how Office Excel names the default functions that are already available.
As explained in the discussion about VBA procedures, the name of this function also follows the following rules:
- The first character must be a letter of the alphabet (AZ, az).
- Subsequent characters can be letters, numbers or certain punctuation characters (not all punctuation marks can be used).
- You canāt use periods (.) and spaces ( ) and you canāt use the following characters: #, $,%, &, @, ^, * and !.
- There is no difference between uppercase and lowercase letters.
- The maximum number of characters that can be used is 255.
Element [List_Argument]
This section shows a list or list of variables that represent the arguments used in the function procedure when it is called or used.
About List Arguments This function will be discussed separately at the bottom later.
Wow, why not just now? I like it donk ekekekekeā¦.
Element āAs [Return_Data_Type]ā
This element is filled withĀ the VBA data typeĀ starting with the keyword āAsā as when declaring a variable.
This section shows the type of data that will be generated by the function we are creating. Writing for example: As Integer, As Long, As String, and so forth.
What types or types of data can be used? Please read the following series:Ā Data Types in Excel VBA
Element [Instructions/Program Code]
Instructions / Program Codes are lines of command code that will be carried out by the Function procedure when it is executed or called.
The content of course adjusts to your needs or desires, which in essence is a certain calculation process by the related procedure when it is called.
Element [Exit Function]
Ideally a line of code will end when it reaches ā End Function ā. However, under certain conditions you can exit the function procedure by using the āĀ Exit FunctionĀ ā command .
The line of code ā Exit Function ā is a command to exit the related Function Procedure. ā Exit Function ā indicates that the function procedure must be terminated and not continued to the next program lines.
Element āFunction_Name = Return_Valueā
It has been explained above that a function procedure can produce a return value ( Return Value ) from its work process.
So how do we tell this return value to a function procedure?
To tell a function procedure what value to return, the trick is to assign that value to the function name.
Writing the line of code is to write the name of the function followed by equals (=) and the value you want to generate or return.
Consider again the following example function procedure:
Function areaSquare(length As Integer) As Long
Ā Ā Ā Ā 'Wide variable declaration
Ā Ā Ā Ā Dim wide As Long
Ā
Ā Ā Ā Ā 'Calculates the area of a square according to the given length argument
Ā Ā Ā Ā area = length * length
Ā Ā Ā Ā 'Assign return value to function areaSquare
Ā Ā Ā Ā areaSquare = area
End Function
In the example above the line of code ā areaSquare = area ā tells the areaSquare function that the value it should return is the value of the area variable that is obtained by multiplying the length * length argument .
So in this case the function name also works as a variable.
Usually the line of code that tells the value to be returned by this kind of function is written at the end of the function before ā End Function ā or ā Exit Function ā.
As an additional note that you can also summarize the area of āāthe Square function above as follows
Function areaSquare(length As Integer) As Long
Ā Ā Ā Ā 'Calculating area at once Assign return value to function areaSquare
Ā Ā Ā Ā areaSquare = length * length
End Function
Make sure that when passing this return value to a function, the value given is the final value of a calculation process which may be quite lengthy.
āEnd Functionā Element
This section marks the end of a Function Procedure.
When you press Enter to finish writing the opening declaration when creating a new procedure, usually the closing statement of this function procedure will be automatically created in VBE (Visual Basic Editor) .
Arguments in Function Procedures
Iām sure you are very familiar with the term argument in an excel function.
In general, this argument is more often used in function procedures, although basically you can use this argument list inĀ Sub (Subroutine) type proceduresĀ that we discussed in the previous series.
The argument list is written between brackets (ā¦) after the procedure name. The way of writing is similar toĀ variable declaration in Excel VBA MacrosĀ , but without including the scope.
Writing arguments begins with the name of the argument followed by the data type and can also be accompanied by other keywords such as ByVal or ByRef and Optional statements, while the variable declaration does not exist.
If there is more than one argument, they are separated by a comma (,).
Consider the following example of a function procedure with the nameĀ DISCOUNTĀ :
Function DISCOUNT (Amount of As Long, price of As Currency, Optional percent As Double = 0.01)
Ā
Ā Ā Ā Ā DISCOUNT = quantity * price * percent
Ā
End Function
The function procedure with the name DISCOUNT above uses 3 arguments, each of which is: amount , price and percent .
Argument Procedure
When a procedure is accompanied by arguments, then to call the procedure must also provide input values āāfor the arguments. For example, to use the DISCOUNT function above on a cell as an excel formula you can write the following formula to use it:
= DISCOUNT(5;10000,0,1)
The value of the number 5 is the amount , 10000 is the price and 0.1 which is equal to 10% is for the percent argument .
Optional Keywords
As in Excelās built-in functions, you can also create arguments asĀ optional argumentsĀ that donāt have to be filled when called. To set an optional argument add the keyword ā Optional ā before the argument name.
You can also set this optional argument by default when the calling procedure does not include it. In the DISCOUNT function example above, the optional argument is percent with a default value of 0.01 (1%).
Optional percent As Double = 0.01
This default value of 0.01 will be ignored if when calling the DISCOUNT function you include the percent value as in the previous example. If not filled then this default value will be used.
In an excel cell you can call the DISCOUNT function like this:
= DISCOUNT(5;10000)
The excel formula above will produce the number 500 which is obtained from the calculation of 5 * 10000 and multiplied by 0.01 or 1% as the default percent value because you did not include the percent value when calling the DISCOUNT function.
To create an optional argument, start writing the argument with the keyword ā Optional ā followed by the name of the argument and if needed, set the default value by writing equal to (=) followed by the default value you want to set.
ByVal and ByRef Key keywords
In the preparation of procedure arguments, either function or sub types, you can also includeĀ ByValĀ orĀ ByRefĀ keywords .
ByRefĀ keyword is the default keyword, so in the preparation of theĀ DISKONĀ function arguments above you can also write it like this:
Function DISCOUNT(ByRef amount As Long, ByRef price As Currency, Optional ByRef percent As Double = 0.01)
Ā
Ā Ā Ā Ā DISCOUNT = quantity * price * percent
Ā
End Function
What is the meaning of using ByRef and ByVal keywords?
The ByValĀ andĀ ByRef keywordsĀ basically indicate how an argument value supplied by the caller will be used by the called procedure. Is the value of the argument passed taken its value ( Value ) or treated as a reference ( Reference ).
- Keyword ByRefĀ : Passes the memory location of a given value as an argument. The argument will be filled with the data form directly, therefore the value of the variable can be changed in the sub procedure or function.
- ByVal keywordĀ : The argument will be filled with a copy of the data value only, in other words ByVal sends a given value into an argument and then the argument copies that value to be used. The argument procedure will only change the copy of the value and the original value will not change at all
Iām at a loss for words to explain about this ByRef and ByVal. For more details, we just practice.
Please create the following sub procedures and functions in a Standard module:
Option Explicit
Ā
Function VOLUMECUBE(ByRef length As Long) As Long
Ā Ā Ā Ā length = length ^ 3
Ā Ā Ā Ā VOLUMECUBE = length
End Function
Ā
Sub testVolume()
Ā Ā Ā Dim lengthĀ As Long
Ā Ā Ā Ā length = 10
Ā
Ā Ā Ā Ā 'Call the VOLUMECUBE function and display the result value in a MesSage Box
Ā Ā Ā Ā MsgBox "Cube Volume = " & VOLUMECUBE(length)
Ā
Ā Ā Ā Ā 'Display variable length value in a Message Box
Ā Ā Ā Ā MsgBox "Variable Length = " & length
End Sub
If you have tried running the testVolume procedure. The result is the following 2 message boxes:
Pay attention to the number value that appears in the 2 message boxes. The first message box is the result of theĀ VOLUMECUBE functionĀ , while the second is the value of theĀ variable lengthĀ .
Next, changeĀ the ByRef keyword withĀ ByValĀ in the long argument, then run the testVolume procedure again. The result is the following 2 message boxes:
Notice the difference in the 2nd message box in the two exercises above.
When passing an argument by reference (ByRef), we are referring to the original value. The length value is changed in the function ( length = length ^ 3 ). Then this long variable is called again via the 2nd message box(Long MsgBox). As a result, the second MsgBox returns the value 1000.
When passing an argument by value (ByVal), we pass a copy of the value to the function (VOLUMECUBE(10)). The original length value does not change. As a result, the second MsgBox returns a value of 10 (the original value).
In the next series we will learn about how to use or call function procedures, but before that, please share this guide so that more people can benefit from it.
Are you getting confused? If you come across this page by accident I suggest reading some of the previous Excel VBA macro guide series so you will get a more complete understanding context.