Chapter 10. Variables, Data Types, and Constants

In the next few chapters, we will discuss the basics of the VBA programming language, which underlies all of the Microsoft Office programming environments. During our discussion, we will consider many short coding examples. I hope that you will take the time to key in some of these examples and experiment with them.

Comments

We have already discussed the fact that comments are important. Any text that follows an apostrophe is considered a comment and is ignored by Access. For example, the first line in the following code is a comment, as is everything following the apostrophe on the third line:

' Declare a recordset variable
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("Names")   ' Get recordset for Names

When debugging code, it is often useful to comment out lines of code temporarily so they will not execute. The lines can subsequently be uncommented to restore them to active duty. The CommentBlock and UncommentBlock buttons, which can be found on the Edit toolbar, will place or remove comment marks from each currently selected line of code and are very useful for commenting out several lines of code in one step. (Unfortunately, there are no keyboard shortcuts for these commands, but they can be added to a menu and given menu accelerator keys.)

Line Continuation

The very nature of Access VBA syntax often leads to long lines of code, which can be difficult to read, especially if we need to scroll horizontally to see the entire line. For this reason, Microsoft recently introduced a line-continuation character into VBA. This character is the underscore, which must be preceded by a space and cannot be followed by any other characters (including comments). For example, the following code:

Set rs = CurrentDb.OpenRecordset("Names",  _
	dbOpenForwardOnly)

is treated as one line by Access.

It is important to note that a line-continuation character cannot be inserted in the middle of a literal string constant, which is enclosed in quotation marks.

Constants

The VBA language has two types of constants. A literal constant (also called a constant or literal ) is a specific value, such as a number, date, or text string, that does not change and is used exactly as written. Note that string constants are enclosed in double quotation marks, as in "Donna Smith", and date constants are enclosed between number signs, as in #1/1/96#.

For instance, the following code stores a date in the variable called dt:

Dim dt As Date
dt = #1/2/97#

A symbolic constant (also sometimes referred to simply as a constant) is a name for a literal constant. To define or declare a symbolic constant in a program, we use the Const keyword, as in:

Const InvoicePath = "d:Invoices"

In this case, Access will replace every instance of InvoicePath in our code with the string "d:Invoices". Thus, InvoicePath is a constant, since it never changes value, but it is not a literal constant, since it is not used as written.

The virtue of using symbolic constants is that, if we decide later to change "d:Invoices" to "d:OldInvoices", we only need to change the definition of InvoicePath to:

Const InvoicePath = "d:OldInvoices"

rather than searching through the entire program for every occurrence of the phrase "d:Invoices".

Note that it is generally good programming practice to declare any symbolic constants at the beginning of the procedure in which they are used (or in the Declarations section of a code module). This improves readability and makes housekeeping simpler.

In addition to the symbolic constants that you can define using the Const statement, VBA has a large number of built-in symbolic constants (about 700), whose names begin with the lowercase letters vb . Access VBA adds several hundred additional symbolic constants that begin with the letters ac .

Among the most commonly used VBA constants are vbCrLf, which is equivalent to a carriage return followed by a line feed, and vbTab, which is equivalent to the tab character.

Enums

Microsoft has introduced a structure into VBA to categorize the plethora of symbolic constants. This structure is called an enum , which is short for enumeration. For instance, the built-in enum for the constant values that can be returned when the user dismisses a message box (by clicking on a button) is:

Enum VbMsgBoxResult
     vbOK = 1
     vbCancel = 2
     vbAbort = 3
     vbRetry = 4
     vbIgnore = 5
     vbYes = 6
     vbNo = 7
End Enum

When the user hits the OK button on a dialog box (assuming it has one), VBA returns the value vbOK. Certainly, it is a lot easier to remember that VBA will return the symbolic constant vbOK than to remember that it will return the constant 1. (We will discuss how to get and use this return value later.)

VBA also defines some symbolic constants that are used to set the types of buttons that will appear on a message box. These are contained in the following enum (which includes some additional constants not shown):

Enum VbMsgBoxStyle
     vbOKOnly = 0
     vbOKCancel = 1
     vbAbortRetryIgnore = 2
     vbYesNoCancel = 3
     vbYesNo = 4
     vbRetryCancel = 5
End Enum

To illustrate, consider the following code:

If MsgBox("Proceed?", vbOKCancel) = vbOK Then
   ' place code to execute when user hits OK button
Else
 ' place code to execute when user hits any other button
End If

In the first line, the code MsgBox("Proceed?", vbOKCancel) causes Access to display a message box with an OK button and a Cancel button and the message “Proceed?”, as shown in Figure 10-1.

Example message box
Figure 10-1. Example message box

If the user clicks the OK button, Access returns the constant value vbOK; otherwise, it returns the value vbCancel. Thus, the If statement in the first line distinguishes between the two responses. (We will discuss the If statement in detail in Chapter 13. Here we are interested in the role of symbolic constants.)

In case you are not yet convinced of the value of symbolic constants, consider the following enum for color constants:

Enum ColorConstants
     vbBlack = 0
     vbBlue = 16711680
     vbMagenta = 16711935
     vbCyan = 16776960
     vbWhite = 16777215
     vbRed = 255
     vbGreen = 65280
     vbYellow = 65535
End Enum

Which would you rather type:

ATextBox.ForeColor = vbBlue

or:

ATextBox.ForeColor = 16711680

Need I say more?

Variables and Data Types

A variable can be thought of as a memory location that can hold values of a specific type. The value in a variable may change during the life of the program—hence the name variable.

In VBA, each variable has a specific data type , which indicates which type of data it may hold. For instance, a variable that holds text strings has a String data type and is called a string variable. A variable that holds integers (whole numbers) has an Integer data type and is called an integer variable. For reference, Table 10-1 shows the complete set of VBA data types, along with the amount of memory that they consume and their range of values. We will discuss a few of the more commonly used data types in a moment.

Table 10-1. VBA data types

Type

Size in memory

Range of values

Byte

1 byte

0 to 255

Boolean

2 bytes

True or False

Integer

2 bytes

-32,768 to 32,767

Long (long integer)

4 bytes

-2,147,483,648 to 2,147,483,647

Single (single-precision real)

4 bytes

Approximately -3.4E38 to 3.4E38

Double (double-precision real)

8 bytes

Approximately -1.8E308 to 4.9E324

Currency (scaled integer)

8 bytes

Approximately -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Date

8 bytes

1/1/100 to 12/31/9999

Object

4 bytes

Any Object reference

String

Variable length: 10 bytes + string length; Fixed length: string length

Variable length: <= about 2 billion (65,400 for Win 3.1) Fixed length: up to 65,400

Variant

16 bytes for numbers

22 bytes + string length

Number: same as Double

String: same as String

User-defined

Varies

 

Variable Declaration

To declare a variable means to define its data type. Variables are declared with the Dim keyword (or with the keywords Private and Public, which we will discuss later in this chapter). Here are some examples:

Dim Name As String
Dim Holiday As Date
Dim Age As Integer
Dim Height As Single
Dim Money As Currency
Dim db as Database
Dim rs as Recordset

The general syntax of a variable declaration is:

Dim VariableName As DataType

If a particular variable is used without first being declared, or if it is declared without a data type mentioned, as in Dim Age, then VBA will treat the variable as having type Variant. As we can see from Table 10-1, this is generally a waste of memory, since variants require more memory than most other types of variables.

For instance, an integer variable requires 2 bytes, whereas a variant that holds the same integer requires 16 bytes, which is a waste of 14 bytes. It is common to have hundreds or even thousands of variables in a complex program, and so the memory waste could be significant. For this reason, it is a good idea to declare all variables.

Perhaps more importantly, much more overhead is involved in maintaining a Variant than its corresponding String or Integer, for example. This in turn means that using Variants typically results in worse performance than using an equivalent set of explicit data types.

We can place more than one declaration on a line to save space. For instance, the line:

Dim Age As Integer, Name As String, Money As Currency

declares three variables. Note, however, that a declaration such as:

Dim Age, Height, Weight As Integer

is legal, but Age and Height are declared as Variants, not Integers. In other words, we must specify the type for each variable explicitly.

It is also possible to tell VBA the type of the variable by appending a special character to the variable name. In particular, VBA allows the type-declaration suffixes shown in Table 10-2. (I personally dislike these suffixes, but they do save space.)

Table 10-2. Type-declaration suffixes

Suffix

Type

%

integer

&

long

!

single

#

double

@

currency

$

string

For instance, the line:

Dim Name$

declares a variable called Name$ of type String. We can then write:

Name$ = "Donna"

Finally, let us note that although Access allows variable and constant declarations to be placed anywhere within a procedure (before the item is used, that is), it is generally good programming practice to place all such declarations at the beginning of the procedure. This improves code readability and makes housekeeping much simpler.

The Importance of Explicit Variable Declaration

I have said that using the Variant data type generally wastes memory and often results in poorer performance, and that all variables are assumed to be variants unless you specify otherwise. There is an additional, even more important reason to declare all variables explicitly. This has to do with making typing errors, which we all do from time to time. In particular, if we accidentally misspell a variable name, VBA will think we mean to create a new variable!

Option Explicit

To avoid this problem, we need a way to make Access refuse to run a program if it contains any variables that we have not explicitly declared. This is done simply by placing the line:

Option Explicit

in the Declarations section of each code module. Since it is easy to forget to do this, VBA provides an option called Require Variable Declaration in its Options dialog box. When this option is selected, VBA automatically inserts the Option Explicit line for us. Therefore, I strongly recommend that you enable this option.

Now let us briefly discuss some of the data types in Table 10-1.

Numeric Data Types

The numeric data types include Integer, Long, Single, Double, and Currency. A long is also sometimes referred to as a long integer.

Boolean Data Type

A Boolean variable is a variable that takes on one of two values: True or False. This is a very useful data type that was only recently introduced into VBA. Prior to its introduction, VBA recognized 0 as False and any nonzero value as True, and you may still see this usage in older code.

String Data Type

A string is a sequence of characters. (An empty string has no characters, however.) A string may contain ordinary text characters (letters, digits, and punctuation), as well as special control characters such as vbCrLf (carriage return/line feed characters) or vbTab (tab character). As we have seen, a string constant is enclosed within quotation marks. An empty string is denoted by a pair of adjacent quotation marks, as in:

EmptyString = ""

There are two types of string variables in VBA: fixed-length and variable-length. A fixed-length string variable is declared as follows:

DimFixedStringVarName As String * StringLen

where StringLen specifies the number of characters reserved for the string. For instance, the following statement declares a fixed-length string of length 10 characters:

Dim sName As String * 10

Observe that the following code, which concatenates two strings:

Dim s As String * 10
s = "test"
Debug.Print s & "/"

produces the output:

test      /

This shows that the content of a fixed-length string is padded with spaces in order to reach the correct length.

A variable-length string variable is a variable that can hold strings of varying lengths (at different times, of course). Variable-length string variables are declared simply as:

DimVariableStringVarName as String

As an example, the code:

Dim s As String
s = "test"
Debug.Print s & "/"
s = "another test"
Debug.Print s & "/"

produces the output:

test/
another test/

Variable-length string variables are used much more often than fixed-length strings, although the latter have some very specific and important uses (which I will not go into in this book).

Date Data Type

Variables of the Date data type require 8 bytes of storage and are actually stored as decimal (floating-point) numbers that represent dates ranging from January 1, 100 to December 31, 9999 (no year 2000 problem here) and times from 0:00:00 to 23:59:59.

As discussed earlier, literal dates are enclosed within number signs, but when assigning a date to a date variable, we can also use valid dates in string format. For example, the following are all valid date/time assignments:

Dim dt As Date
dt = #1/2/98#
dt = "January 12, 2001"
dt = #1/1/95#
dt = #12:50:00 PM#
dt = #1/13/76 12:50:00 PM#

VBA has a large number of functions that can manipulate dates and times. If you need to manipulate dates or times in your programs, you should probably spend some time with the Access VBA help file. (Start by looking under “Date Data Type.”)

Variant Data Type

The Variant data type provides a catch-all data type that is capable of holding data of any other type except fixed-length string data and user-defined types. I have already noted the virtues and vices of the Variant data type and discussed why variants should generally be avoided.

Access Object Data Types

Access VBA/DAO has a number of additional data types that fall under the general category of Object data type. Here is a sampling:

Some Access objects
Form
Module
Report
Control
Section
Some DAO objects
Workspace
Database
Recordset
Field
Error
User

Thus, we can declare variables such as:

Dim fm As Form
Dim ws As Workspace
Dim db As Database
Dim rs As Recordset
Dim fld As Field

I devote much of this book to studying the objects in the DAO object model, for it is through these objects that we can manipulate Access databases programmatically. (I will briefly describe the Access object model as well, but not go into its details, for its primary use is to manipulate Access forms and reports, not actual data. In fact, the Access object model does not even have a Table object!)

The generic As Object declaration

It is also possible to declare any Access object using the generic-object data type Object, as in the following example:

Dim rs As Object

While you may see this declaration from time to time, it is much less efficient than a specific object declaration, such as:

Dim rs As Recordset

This is because Access cannot tell what type of object the variable rs refers to until the program is running, so it must use some execution time to make this determination. This is referred to as late binding and can make programs run significantly more slowly.

The Set statement

Declaring object variables is done in the same way as declaring nonobject variables. For instance, here are two variable declarations:

Dim int As Integer    ' nonobject (standard) variable declaration
Dim db As Database    ' object variable declaration

On the other hand, when it comes to assigning a value to variables, the syntax differs for object and nonobject variables. In particular, we must use the Set keyword when assigning a value to an object variable. For example, the following line assigns the current Access database to the variable db :

Set db = CurrentDb

Arrays

An array variable is a collection of variables that use the same name, but are distinguished by an index value. For instance, to store 10 fields objects in variables, we could declare an array variable as follows:

Dim MyFields(1 To 10) As Field

The array variable is MyFields. It has size 10. The lower bound of the array is 1, and the upper bound is 10. Each of the variables:

MyFields(1), MyFields(2),..., MyFields(10)

are Field variables. Note that if we omit the first index in the declaration, as in:

Dim MyFields(10) As Field

then VBA will automatically set the first index to 0, so the size of the array will be 11.

The virtue of declaring array variables is clear, since it would be very unpleasant to have to declare 10 separate variables. In addition, as we will see, there are ways to work collectively with all of the elements in an array, using a few simple programming constructs. For instance, the following code sets all 10 Field types to Integer:

For i = 1 To 10
   MyFields(i).Type = dbInteger
Next i

The dimension of an array

The MyFields array defined in the previous example has dimension one. We can also define arrays of more than one dimension. For instance, the array:

Dim Stats(1 To 10, 1 To 100) As Integer

is a two-dimensional array whose first index ranges from 1 to 10 and whose second index ranges from 1 to 100. Thus, the array has size 10 x 100 = 1000.

Dynamic arrays

When an array is declared, as in:

Dim FileName(1 To 10) As String

the upper and lower bounds are both specified, and so the size of the array is fixed. However, there are many situations in which we do not know at declaration time how large an array we may need. For this reason, VBA provides dynamic arrays and the ReDim statement.

A dynamic array is declared with empty parentheses, as in:

Dim FileName(  ) as String

Dynamic arrays can be sized (or resized) using the ReDim statement, as in:

ReDim FileName(1 to 10)

This same array can later be resized again, as in:

ReDim FileName(1 to 100)

Note that resizing an array will destroy its contents unless we use the Preserve keyword, as in:

ReDim Preserve FileName(1 to 200)

However, when Preserve is used, we can only change the upper bound of the array (and only the last dimension in a multidimensional array).

The UBound function

The UBound function is used to return the current upper bound of an array. This is very useful in determining when an array needs redimensioning. To illustrate, suppose we want to collect an unknown number of filenames in an array named FileName. If the next file number is iNextFile, the following code checks to see if the upper bound is less than iNextFile and if so, it increases the upper bound of the array by 10, preserving its current contents, to make room for the next filename:

If UBound(FileName) < iNextFile Then 
   ReDim Preserve FileName(UBound(FileName) + 10)
End If

Note that redimensioning takes time, so it is wise to add some “working room” at the top to cut down on the number of times the array must be redimensioned. This is why we added 10 to the upper bound in this example, rather than just 1. (There is a tradeoff here between the extra time it takes to redimension and the extra space that may be wasted if we do not use the entire redimensioned array.)

Variable Naming Conventions

VBA programs can get very complicated, and we can use all the help we can get in trying to make them as readable as possible. In addition, as time goes on, the ideas behind the program begin to fade, and we must rely on the code itself to refresh our memory. This is why adding copious comments to a program is so important.

Another way to make programs more readable is to use a consistent naming convention for constants, variables, procedure names, and other items. In general, a name should have two properties. First, it should remind the reader of the purpose or function of the item. For instance, suppose we want to assign Field variables to some fields in an Access table. The code:

Dim fld1 As Field, fld2 as Field
Set fld1 = Fields("Sales")
Set fld2 = Fields("Transactions")

is perfectly legal, but 1,000 lines of code and 6 months later, will we remember which field is fld1 and which is fld2? Since we went to the trouble of naming the fields in a descriptive manner, we should do the same with the fld variables, as in:

Dim fldSales As Field, fldTrans as Field
Set fldSales = Fields("Sales")
Set fldTrans = Fields("Transactions")

Of course, there are exceptions to all rules, but in general, it is better to choose descriptive names for variables (as well as other items that require naming, such as constants, procedures, controls, forms, and code modules).

Second, a variable name should reflect something about the properties of the variable, such as its data type. Many programmers use a convention in which the first few characters of a variable’s name indicate the data type of the variable. This is sometimes referred to as a Hungarian naming convention, after the Hungarian programmer Charles Simonyi, who is credited with its invention.

Table 10-3 and Table 10-4 describe the naming convention that we will generally use for nonobject and object variables, respectively. Of course, you are free to make changes for your own personal use, but you should at least try to be reasonably consistent. These prefixes are intended to remind us of the data type, but it is not easy to do this perfectly using only a couple of characters, and the longer the prefix, the less likely it is that we will use it! (Note the c prefix for integers or longs. This is a commonly used prefix when the variable is intended to count something.)

Table 10-3. Naming convention for nonobject variables

Variable

Prefix

Boolean

bool, b, or f

Byte

b, byt, or bt

Currency

cur

Date

d or dte

Double

d or dbl

Integer

i, c, or int

Long

l, c, or lng

Single

s or sng

String

s or str

User-defined type

typ, u, or ut

Variant

v or var

Table 10-4. Naming convention for some object variables

Variable

Prefix

Database

db

Workspace

ws

Recordset

rs

TableDef

tdef

Field

fld

Index

idx

QueryDef

qdef

In addition to a data type, every variable has a scope and a lifetime. Some programmers advocate including a hint as to the scope of a variable in the prefix, using g for global and m for module level. For example, the variable giSize is a global variable of type Integer. I will discuss the scope and lifetime of a variable next (but I will not generally include scope prefixes in variable names).

Variable Scope

Variables and constants have a scope, which indicates where in the program the variable or constant is recognized (or visible to the code). The scope of a variable or constant can be either procedure-level (also called local), module-level private, or module-level public. The rules may seem a bit involved at first, but they do make sense.

Procedure-level (local) variables

A local or procedure-level variable or constant is a variable or constant that is declared within a procedure, as is the case with the variable LocalVar and the constant LocalConstant in Figure 10-2. A local variable or constant is not visible outside of the procedure. Thus, for instance, if we try to run ProcedureB in Figure 10-2, we will get the error message, “Variable not defined,” and the name LocalVar will be highlighted.

Examples of variable scope
Figure 10-2. Examples of variable scope

One of the advantages of local variables is that we can use the same name in different procedures without conflict, since each variable is visible only in its own procedure.

Module-level variables

A module-level variable (or constant) is one that is declared in the declarations section of a code module. Module-level variables and constants come in two flavors: private and public.

Simply put, a module-level public variable (or constant) is available to all procedures in all of the modules in the project, not just the module in which it is declared, whereas a module-level private variable (or constant) is available only to the procedures in the module in which it was declared.

Public variables and constants are declared using the Public keyword, as in:

Public APubInt As Integer
Public Const APubConst = 7

Private variables and constants are declared using the Private keyword, as in:

Private APrivateInt As Integer
Private Const APrivateConst = 7

The Dim keyword, when used at the module level, has the same scope as Private, but is not as clear, so it should be avoided.

Public variables are also referred to as global variables , but this descriptive term is not de rigueur.

Variable Lifetime

Variables also have a lifetime. The difference between lifetime and scope is quite simple: lifetime refers to how long (or when) the variable is valid (that is, retains a value), whereas scope refers to where the variable is accessible or visible.

To illustrate the difference, consider the following procedure:

Sub ProcedureA(  )
   Dim LocalVar As Integer
   LocalVar = 0
   Call ProcedureB
   LocalVar = 1
End Sub

Note that LocalVar is a local variable. When the line:

Call ProcedureB

is executed, execution switches to ProcedureB. While the lines of ProcedureB are being executed, the variable LocalVar is out of scope, since it is local to ProcedureA. But it is still valid. In other words, the variable still exists and has a value, but it is simply not accessible to the code in ProcedureB. In fact, ProcedureB could also have a local variable named LocalVar, which would have nothing to do with the variable of the same name in ProcedureA.

Once ProcedureB has completed, execution continues in ProcedureA with the line:

LocalVar = 1

which is a valid instruction, since the variable LocalVar is back in scope.

Thus, the lifetime of the local variable LocalVar extends from the moment that ProcedureA is entered to the moment that it is terminated. This includes the period during which ProcedureB is executed as a result of the call to this procedure, even though during that period, LocalVar is out of scope.

Incidentally, you may notice that the Microsoft help files occasionally get the notions of scope and visibility mixed up a bit. The creators of the files seem to understand the difference, but they don’t always use the terms correctly.

Static variables

To repeat, a variable may go in and out of scope and yet remain valid during that time—that is, retain a value during that time. However, once the lifetime of a variable expires, the variable is destroyed, and its value is lost. It is the lifetime that determines the existence of a variable; its scope determines its visibility.

Thus, consider the following procedures:

Sub ProcedureA(  )
   Call ProcedureB
   Call ProcedureB
   Call ProcedureB
   Call ProcedureB
   Call ProcedureB
End Sub
Sub ProcedureB(  )
   Dim x As Integer
   x = 5
   . . . 
End Sub

When ProcedureA is executed, it simply calls ProcedureB five times. Each time ProcedureB is called, the local variable x is created anew and destroyed at the end of that call. Thus, x is created and destroyed five times.

Normally, this is just want we want. However, there are times when we would like the lifetime of a local variable to persist longer than the lifetime of the procedure in which it is declared. As an example, we may want a procedure to do something special the first time it is called, but not subsequent times.

A static variable is a local variable whose lifetime is the lifetime of the entire module, not just the procedure in which it was declared. In fact, a static variable retains its value as long as the document or template containing the code module is active (even if no code is running). Thus, a static variable has the scope of a local variable, but the lifetime of a module-level variable. C’est tout dire !

For instance, the procedure in Example 10-1 uses a static variable to execute some code only the first time the procedure is called, other code only after the first time, and still other code every time the procedure is run.

Example 10-1. Using a static variable
Sub StaticExample(  )

' Declare static Boolean variable
Static NotFirstTime As Boolean

' If first time, then run special code
If NotFirstTime = False Then

   ' Code here that runs only the first time procedure is called

   ' No longer the first time
   NotFirstTime = True

Else

   ' Not the first time
   ' Code here will run if not first time

End If

   ' Code here will always run (unless procedure is exited beforehand)

End Sub

The If statement checks to see if the value of NotFirstTime is False, as it will be the first time the procedure is called. During this first call, the line:

NotFirstTime = True

will execute, so that in subsequent calls to this procedure, the If condition:

If NotFirstTime = False

will be False, and the alternate code will execute.

Static variables are not used very often, but they can be quite useful at times.

It may have occurred to you that we could accomplish the same effect by using a module-level private variable to keep a record of whether the procedure has been called, instead of a static local variable. However, it is considered better programming style to use the most restrictive scope possible, which, in this case, is a local variable with an “extended” lifetime. This helps prevent accidental alteration of the variable in other portions of the code. (Remember that this code may be part of a much larger code module, with a lot of things going on. It is better to hide the NotFirstTime variable from this other code.)

Variable Initialization

When a procedure begins execution, all of its local variables are automatically initialized, that is, given initial values. In general, however, it is not good programming practice to rely on this initialization, since it makes the program less readable and somewhat more prone to logical errors. Thus, it is a good idea to initialize all local variables explicitly, as in the following example:

Sub Example(  )

Dim x As Integer
Dim s As String

x = 0       ' Initialize x to 0
s = ""      ' Initialize s to empty string

' more code here . . .

End Sub

Note, however, that static variables cannot be initialized, since that defeats their purpose! Thus, it is important to know the following rules that VBA uses for variable initialization (note also that they are intuitive):

  • Numeric variables (Integer, Long, Single, Double, and Currency) are initialized to zero.

  • A variable-length string is initialized to a zero-length (empty) string.

  • A fixed-length string is filled with the character represented by the ASCII character code 0, or Chr (0).

  • Variant variables are initialized to Empty.

  • Object variables are initialized to Nothing.

The Nothing keyword actually has several related uses in Access VBA. It is used to release an object variable, as in:

Set rs = Nothing

and to determine if an object variable references a valid object, as in:

If rs Is Nothing

It is also sometimes used as a return value for some functions, generally to indicate that some operation has failed. Finally, it is used to initialize object variables.

VBA Operators

VBA uses a handful of simple operators and relations, the most common of which are shown in Table 10-5.

Table 10-5. VBA operators and relations

Type

Name

Symbol

Arithmetic operators

Addition

+

 

Subtraction

-

 

Multiplication

*

 

Division

/

 

Division with Integer result

 

Exponentiation

^

 

Modulo

Mod

   

String operator

Concatenation

&

   

Logical operators

AND

AND

 

OR

OR

 

NOT

NOT

   

Comparison relations

Equal

=

 

Less than

<

 

Greater than

>

 

Less than or equal to

<=

 

Greater than or equal to

>=

 

Not equal to

<>

The Mod operator returns the remainder after division. For example:

8 Mod 3

returns 2, since the remainder after dividing 8 by 3 is 2.

To illustrate string concatenation, the expression:

"To be or " & "not to be"

is equivalent to:

"To be or not to be"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.147.252