Storing data in Variables and constants

All programming languages, including VBA, have a means of storing little chunks of information (data) in temporary cubbyholes called variables. Obviously, the contents of the cubbyhole can vary. For example, a variable named LastName might contain Smith, Jones, McDougal, or whatever. The VBA code can operate on whatever value happens to be in the variable at the moment.

Creating a variable is a two-step process:

1. Declare the variable's name and data type with a Dim statement.

2. Assign a value to the variable as needed.

The syntax usually involves two lines of code that follow this structure:

Dim name As type name = value where name is a name of your own choosing, type is one of the data types listed in Table 4-1, and value is the data you want to store in the variable.

When naming a variable, stick to using short names with no spaces or punctuation. Also make sure the name starts with a letter. You can use either letters or numbers as part of the name after the first character.

Here's an example of creating an Integer variable named x and storing the number 10 in that variable:

Here's an example of creating a string variable named LastName and putting the name Jones in it:

Dim LastName As String LastName = "Jones"

Note the use of the quotation marks around Jones. As in Access expressions, the quotation marks signify a literal text: That is, after the statement

LastName = "Jones" executes, the variable LastName contains (literally) the name Jones.

A constant is similar to a variable in that it's a name that refers to some value. However, after you assign a value to a variable, you can't change it. Hence, the value remains constant.

Lots of constants are built in to VBA, as you can see in many examples throughout this book. If you ever want to create your own constant, the syntax is

Const name As type = value where, once again, name is a name of your choosing, type is a data type from Table 4-1, and value is the data you want to store in the constant. For example, the following VBA statement creates a constant named pi that stores the number 3.14159265 as a double-precision number:

Const pi As Double = 3.14159265

0 0

Responses

  • reuben
    How to store your own variable type in a table in access 2007 vba?
    7 years ago

Post a comment