Before you can start to program, you must understand the VBA model. In order to do that, you need to learn the hierarchy of structures. As you progress through the book, you will be drilling down to greater detail. However, we’ll start with an overview so you can get a better picture of how the pieces fit together. We begin with an overview of modules.
The module is the place where VBA code is written and stored. You can think of modules as drawers in a filing cabinet. You can keep related sections of code in separate modules, which facilitates the ability to organize your code efficiently.
Modules are divided into several types:
The form and report modules hold code associated with a particular report or form. As a matter of fact, if that form or report is moved to another database, the module holding the code usually moves with it.
The standard module holds code that has no association with a particular database object. Most of your coding will be in a standard module.
The code within the module is divided into blocks called procedures. Most procedures should only perform one specialized job. Procedures fall into two categories: sub procedures and functions.
A sub procedure just carries out a job without returning a value to whomever called it. Most procedures you write will fall into this category. An example of what a sub procedure looks like is as follows:
Sub Concat()
Dim strFirstname As String
Dim strLastName As String
Dim strFullName As String
strFirstname = "John"
strLastName = "Smith"
strFullName = strFirstname & " " & strLastName
Debug.Print strFullName
End Sub
Don’t worry about all the particulars of this sub procedure right now. The procedure opens with the line:
Sub Concat()
This defines the name of the sub procedure. Of course, you can call it whatever you want, but this is how a sub procedure opens.
The sub procedure ends with the line:
End Sub
All the code between these two lines is called the sub procedure implementation code.
Note |
Programmers commonly refer to the sub procedure as a “sub.” |
A function returns a value to whomever called it. We can recast the previous sub into a function as follows:
Function concat() As String Dim strFirstname As String Dim strLastName As String Dim strFullName As String strFirstname = "John" strLastName = "Smith" strFullName = strFirstname & " " & strLastName concat = strFullName End Function
Notice that this code opens with the line:
Function concat() As String
This states that the code is a function, and the value it will be returning is a string. The closing line is
End Function
Again, don’t be concerned about what is going on in between yet.