FUNCTIONS
Functions are basically the same as subroutines, except that they return some sort of value. The syntax for defining a function is as follows:
[attribute_list] [inheritance_mode] [accessibility]
Function function_name([parameters]) [As return_type]
[ Implements interface.function ]
[ statements ]
End function
This is almost the same as the syntax for defining a subroutine. See the section “Subroutines” earlier in this chapter for information about most of this declaration’s clauses.
One difference is that a function ends with the End Function statement rather than End Sub. Similarly, a function can exit before reaching its end by using Exit Function rather than Exit Sub.
The one nontrivial difference between subroutine and function declarations is the clause As return_type that comes after the function’s parameter list. This tells Visual Basic the type of value that the function returns.
The function can set its return value in one of two ways. First, it can set its own name equal to the value that it should return. The Factorial function shown in the following code calculates the factorial of a number. Written N!, the factorial of N is N * (N1) * (N2) . . .* 1. The function initializes its result variable to 1, and then loops over the values between 1 and the number parameter, multiplying these values to the result. It finishes by setting its name, Factorial, equal to the result value that it should return.
Private Function Factorial(number As Integer) As Double Dim ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access