The VBA Model


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.

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.

Procedures

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.

Sub Procedures

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.”

Functions

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.




Access VBA Programming
Microsoft Access VBA Programming for the Absolute Beginner
ISBN: 1598633937
EAN: 2147483647
Year: 2006
Pages: 214
Authors: Michael Vine

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net