Visual Basic is one of the best programming languages that's quite simple to learn, yet, it's widely used in so many applications like within Microsoft Office programs. Besides, it makes learning other languages miles easier because of how many similarities there are. The most prominent similarity among all programming languages is the usage of functions. Check out our VBA vs Python review to decide which programming language is best suited for you.
Functions are pieces of code that you can reuse multiple times through the code, but you only need to write the function once.
Here's everything you need to know to be able to create and start using functions. And in addition, you can also choose a course here to get VBA certified.
Visual Basics Function Declaration
Throughout this section, I'll walk you through what you need to know to write your first function.
If you look at any Visual Basic function, it'll look like this: accessLevel Function functionName (argument1 as dataType, argument2 as dataType,...) As dataType.
Now, if that looks too confusing, let's break it down word for word.
Access Level Keyword
The main difference between public and private functions is which parts of the code have access to that function.
As you can guess, functions with the "public" keyword can be accessed throughout any part of the code — you can even access it from a different class! However, note that a public function is limited by its class, meaning that it's only public to the code inside that class if it's defined in a private class.
On the other hand, functions with the "private" keyword can only be accessed within the same module, class, or structure.
There are also other access types like protected, friend, protected friend, and private protected and each of them has its own uses, but that's beyond our scope for now.
You have freedom when it comes to choosing your function's name, but try to keep it as clear and to the point as possible so that it's easier for you to debug the code later on. First of all, you need to write the word "Function" before the name as follows: Function functionName.
However, there are some naming rules that you need to follow. For example, the first character of the name must be a character; you can't use special characters like periods, hashes, and dollar signs, to name a few. Also, the name has to be shorter than or equal to 255 characters.
Keep in mind that all Visual Basic names are case-sensitive.
I recommend checking Microsoft's documentation to get the full image.
The parameters or arguments are values that you can pass to perform the function. They're usually written like "name As dataType". Also, you can pass as many arguments as you'd like.
The best way to explain data types is through an example, so let's take a look at this simple function that returns the summation of two variables:
Private Function addition( x As Integer, y As Integer) As Integer
addition = x + y
Looking at the last "As Integer" in the function here, this means that the function will return an integer value, which is the variable called addition. Of course, you have to change that data type according to what your function does.
As you've seen in the previous example, you must add a statement "End Function" or "Exit Function" so that the program knows the function is done. Also, it should return control and a value to the calling code.
Calling a Visual Basic Function
Well, now you have your function ready, right? Here's how you can call it from another part of the code.
value = functionName(argument1, argument2,...)
In order to understand that piece of code, we need some more context, so take a look at this code:
Private Function addition(byVal x As Integer, byVal y As Integer, byVal z As Integer) As Integer
addition = x + y + z
Dim result, x, y, result As Integer
x = 2
y = 5
z = 1
result = addition(x, y, z)
If you run this code, the function will return the result of the addition, which is 8 in this example, into the variable declared as follows: Dim result As Integer.
Now, there are two ways for passing parameters in Visual Basic: by value and by reference. Here's what you need to know.
Passing Arguments by Value (byVal)
To understand what "byVal" in Visual Basic means, let's take a look at another code example:
Private Function additionPlusOne(byVal x As Integer, byVal y As Integer, byVal z As Integer) As Integer
x = 6
additionPlusOne = x + y +z
Dim x, y, z, result As Integer
x = 5
y = 1
z = 2
result = additionPlusOne(x, y, z)
As you can see, x, y, and z are all parameters that are passed to the function by value, which is specified using the "byVal" in the function's declaration statement. Passing variables by values means that the original values aren't changed.
This function returns the value 9 and saves it in the variables called result, correct? Now, if you check the x after the control was returned from the function, you'll notice that x is still 5 and not changed to 6. That's exactly what byVal does. The values of the passed parameters only change locally in the function itself; the original values are still saved and unchanged when the function is complete.
Please note that byVal is the default way of parameter passing, meaning if you don't write either byRef or byVal in the function declaration, it's assumed that you're passing by value.
Passing Arguments by Reference (byRef)
So, how things would change in Visual Basic if we were passing by reference? Let's take the same example but with a slightly different function statement:
Private Function additionPlusOne(byRef x As Integer, byRef y As Integer, byRef z As Integer) As Integer
x = 6
addition = x + y +z
and the Sub Main() is still the exact same.
Here, x, y, and z are passed by reference using byRef, which means that x changed in the calling code after the function has ended; the new value of x is 6, which is declared in the function body.
While this method isn't very protective because it changes original data, sometimes it's needed to pass values by reference. That's because you might want to change the values of multiple elements, and passing a copy then returning the results into the original variables might be too expensive.
This is especially true if you're passing a long string or a large array; passing a pointer is a lot cheaper than passing the entire string or array as parameters.
Functions vs Subroutines in Visual Basic
In Visual Basic, functions are quite different from subroutines in the sense that functions return a value while sub-procedures just don't.
A subroutine (or sub-procedure) simply does a few operations and returns the control to the calling code back without any value. Also, a subroutine needs a sub-end statement, which is "End Sub" to declare that the sub-procedure is done.
Subroutines also have access level keywords like functions, so you can use "Private Sub" and "Public Sub" as you see fit. Additionally, the main procedure has to be a subroutine that's declared as follows:
MsgBox("This is the Main procedure.")
MsgBox("It has to be declared using Sub Main().")
How Functions Return a Value in Visual Basic
A function in Visual Basic has to return a value, and that can be done in two different ways, which we'll discuss right now.
Without a "Return" Statement
First, let's look at this simple program code:
Private Function addOne(byVal x As Double) As Double
addOne= x + 1
Dim x, result As Double
x = 5
result = addOne(x)
This is a program that we've seen before, but let me tell you how it works. It returns the variable that has the same name as the function, which is "addOne" in this case, so the function will return the value 6, which is 5+1 when it finds an "End Function" or "Exit Function" statements.
With a "Return" Statement
The other method of returning variables is using "Return." Here's an example:
Private Function addOne(byVal x As Double) As Single
Dim FunctionResult As Single
FunctionResult = x + 1
Dim x, result As Single
x = 5
result = addOne(x)
As you can see, this method uses the Return Statement to specify which variable you want to return to the calling code. In other words, you specify the return value. So, it doesn't only return control, but it also returns the value that follows the "Return" statement, which is FunctionResult, in this case.
Now that you're at this point of the article, you should know everything there is to get you started with using functions in Visual Basic. Functions can be incredibly useful and time-saving if they're used correctly, so make sure you understand every part! If anything is still unclear, just go back and reread that section until you master it. Also, make sure you try everything you've learned yourself. What are you waiting for? Get to coding!