Using functions in VBA
This article will demonstrate how to create and use functions when working with VBA.
Functions are used to return results that a subroutine cannot return. As programs grow longer and more complex, functions are a useful tool that makes it easier to organize code blocks, debug, and modify scripts.
Functions can be divided into two subsets:
non-object-type |
Functions that will return strings, integers, booleans, etc. |
object-type |
Functions will return objects like ranges, array lists, etc. |
grammar:
[Public | Private] [ Static ] Function name [ ( argumentlist ) ] [ As retType ]
[ statements ]
[ name = expression ]
[ Exit Function ]
End Function
definition:
Public |
Optional. Indicates that other programs in all modules can access this function. |
Private |
Optional. Indicates that the function can only be accessed by procedures in the current module. |
Static |
Optional. Indicates that program variables are preserved between function calls. |
name |
Required. Function name |
argumentlist |
Optional. A list of variables to pass after calling the function. |
retType |
Optional. The return type of the function |
statements |
The code block to execute |
expression |
Function return value |
非对象
Using Function Types in VBA
The following code block will use 非对象
the function type to calculate the area of a triangle given its base and height as its parameters.
Public Function GetTriangleArea(b, h) as Double
Dim area as Double
area= (b*h)/2
GetTriangleArea= area
End Function
Sub TestFunction()
Debug.print("The area of the triangle is " & GetTriangleArea(10,8) & " square meters.")
End Sub
Output:
The area of the triangle is 40 square meters.
object
Using Function Types in VBA
The following code block will demonstrate how to use object
the function type to calculate the sum of all numbers between two numbers.
Public Function GetCollection(numStr, numEnd) As Object
'Declaring variable for the counter
Dim i As Integer
'Creating a new Arraylist named coll
Dim coll As Object
Set coll = CreateObject("System.Collections.ArrayList")
'Add all number from numStr to numEnd to the arraylist named coll using a for loop
For i = numStr To numEnd
coll.Add (i)
Next i
'Returning the arraylist named coll to the subroutine
Set GetCollection = coll
End Function
Sub testFunction()
'Declaring collForSum as an Object
'collForSum object will be the placeholder object where the coll arraylist will be in placed
Dim collForSum As Object
'Setting up a counter named j
Dim j As Integer
'Sum variable will hold the running sum of the elements in collForSum
Dim sum As Double
'Calling the GetCollection Function to fill collForSUm Object
Set collForSum = GetCollection(10, 20)
'For loop to iterate on all element of collForSum arraylist
For j = 0 To collForSum.Count - 1
'Add all the elements inside the collForSum arraylist.
sum = sum + collForSum(j)
Next j
Debug.Print ("The total sum is " & sum & ".")
End Sub
Output:
The total sum is 165.
Use Exit Function
the command to force a return to the subroutine
Returning a value to a subroutine or function does not necessarily mean that the code execution in the current function will stop. We need to explicitly state to stop the code execution on a function. The command to be used is 退出功能
.
Calling the function without Exit Function
a command may return an error value.
Public Function PositiveOrNegative(num) as String
If num >= 0 Then
PositiveOrNegative = "Positive"
End If
PositiveOrNegative = "Negative"
End Function
Sub TestFunction()
Debug.Print (PositiveOrNegative(5))
End Sub
TestFunction
Output:
Negative
Even if TestFunction
the input is 5
, the output is also Negative
, because code execution PositiveOrNegative = "Positive"
does not stop when it reaches the code line.
We need to use Exit Function
the command to solve this problem.
Public Function PositiveOrNegative(num) as String
If num >= 0 Then
PositiveOrNegative = "Positive"
'Exit Function will force the code execution in the current function to stop and return the current value of PositiveOrNegative
Exit Function
End If
PositiveOrNegative = "Negative"
End Function
Sub TestFunction()
Debug.Print (PositiveOrNegative(5))
End Sub
Output:
Positive
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Remove duplicates in VBA
Publish Date:2025/04/16 Views:105 Category:Vba
-
We will explain how to remove duplicates in VBA by example. Remove duplicates in VBA When working with an Excel worksheet that contains a lot of data, it is likely that this data contains some duplicates. Any duplicates must be removed to a
Rounding in VBA
Publish Date:2025/04/16 Views:163 Category:Vba
-
Round() We will introduce the and functions in VBA through examples RoundUp() . Round() Using the or RoundUp() function in VBA When working with Excel worksheets containing numbers and calculations, we get results that are fractions. Someti
Adding a new row in VBA
Publish Date:2025/04/16 Views:195 Category:Vba
-
We will show you how to continue the code on the next line in VBA by example. We will also show you how to go to the next line in a message box using different methods in VBA. Adding a new row in VBA There are two different situations in pr
Sum function in VBA
Publish Date:2025/04/16 Views:126 Category:Vba
-
We will show you how to use sum in VBA. Sum function in VBA Sum is the most commonly used function in excel. This function is very useful as we can use sum to get the total from the financial table. We will learn how to use the sum function
Exit Sub in VBA
Publish Date:2025/04/16 Views:192 Category:Vba
-
We will look at different ways to exit a sub in VBA through examples. Using the Exit Sub Statement in VBA While using Sub in VBA, we may want to exit it or prevent it from executing further if an error occurs or the user provides wrong inpu
Calling a Sub in VBA
Publish Date:2025/04/16 Views:191 Category:Vba
-
We will show you how to call a sub within another sub through examples in VBA. Calling a Sub in VBA When dealing with multiple subroutines, we may encounter situations where we need to call multiple subroutines for the same function. Some f
Check if a string contains a substring in VBA
Publish Date:2025/04/16 Views:189 Category:Vba
-
This article demonstrates the use of Instr() the , , InstrRev() and Like functions to check whether a main string contains a substring. Use Instr() the function to check if the main string contains a substring Instr() Function syntax: InStr
Convert a string to a number in VBA
Publish Date:2025/04/16 Views:189 Category:Vba
-
This article will discuss how to convert a string to a number in VBA Excel. There is a step-by-step guide and many examples for us to understand. Convert a string to a number in VBA In VBA code, numbers saved as text must be converted to re
Concatenating strings in VBA
Publish Date:2025/04/16 Views:113 Category:Vba
-
We will cover how to concatenate strings in VBA and explain how to use Excel and operators. Concatenating strings in VBA We can concatenate multiple strings into a singular string in VBA and use the operator to separate the values of