Вы находитесь на странице: 1из 5

VBA Foundations, Part 5

A Tutorial in VBA for BeginnersThe Fifth in a Twelve Part Series


Richard L. Binning / rbinning@attbi.com
In the last issue, we defined the meaning of Good Code, reviewed some common coding guidelines, explored the anatomy of a macro, discovered some editor enhancements like Microsofts IntelliSense and
Command Completion utilities, and created our first useful macro. Lets begin this issue by explaining some
of the concepts mentioned in previous issues such as constants, variables, objects, and conditional or control
structures.

What is a Variable?
A variable is a meaningful name that takes the place of other data that might change during the course of
your project or macro. Variables temporarily store values while a macro is running. A variable has a name
(the word you use when you wish to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store). You might compare variables to storage containers that you
are familiar with. If you wanted to carry groceries home from the store, you might ask for a paper bag.
What else might a typical paper bag contain? A paper bag with your lunch inside might be carried to work,
or that same paper bag might be used to hold a bottle of vitamins on the way home from the drugstore, or
may hold a candle sitting in sand on some cold night in December (luminaire). Do you care what the bag
contains? No, you simply use it to hold something you wish to take out of it later. Similarly, you might use
a bucket to hold something. What might that same bucket hold on different occasions? It might hold fried
chicken at a picnic, or sand used in making a sand castle at the beach, or soapy water used for washing the
windows of your house or car. What is important about these containers is not the specific items they carry
but the fact that they can carry different types of items. Through experience you will learn which type of
container is most suitable for the task at hand. In a similar fashion, VBA provides containers (variable)
which can be used to hold whatever you desire, simply use the correct container for the task at hand.
Visual Basic for Applications also has a carryall type of variable for use when you are not sure what type of
items you wish to use it for. This variable is called a variant and can be used to hold words, multiple words,
numbers, objects, etc. This wide ranging functionality comes at a price. The Variant data type utilizes the
most memory, this ensures that it is capable of storing virtually any thing you might ask of it. While this
may be tempting to use, especially for beginners, you will be much better served by thinking about what
type of data you are storing and declaring your variable appropriately. For example, a suitcase may carry
your groceries home from the store everybit as well as it carries books home from the library, but just because it can hold many types of items doesnt mean that you should or would want to use it for every occasion. Although that suitcase is the correct container to hold all the clothes necessary for a week long trip, it
may not be best suited for carrying your lunch to work.

What is a Data Type?


A data type is simply the category describing the type of item residing inside your variable. For instance,
your lunch in that paper bag might be a food type, while your vitamins, although edible, are not really food
but some other type of similar product. The data type of a variable determines how those values are stored
in the computer's memory. When you declare a variable, you can also supply a data type for it. Some examples of data types include String, Integer, and Long. Data types also apply to other things besides variables.
When you assign a value to a property, that value has a data type; arguments to functions also have data
types. In fact, just about anything in VBA that involves data also involves data types. Variables can also
contain objects. Examples of object types, or classes, include Object, UserForm1, and TextBox1.
There are many types of Variables for different conditions, the following chart will list some of the more
common variables, their data type, and their approximate memory usage:
(Continued on page 2)

PaperSpace

Join AUGI free at www.augi.com

July 2002

VBA Foundations, Part 5


A Tutorial in VBA for BeginnersThe Fifth in a Twelve Part Series
Richard L. Binning / rbinning@attbi.com

Declaring a variable tells the macro about it in advance. Since this represents good coding practice we will
always strive to declare variables in advance of their use. Another aspect of variables is defined as the scope
of the variable. Scope can be defined as the area of the project where that variable can hold a value. For instance, if you declare a variable to be private inside of a sub routine then you cant place a value inside that
variable anywhere but within that sub routine. Variables can have the following scope:

You typically declare a variable with the Dim statement, supplying a name for the variable: (if you make
your variable public then you can declare it by replacing Dim with the word Public)
Dim variablename [As type]
In all of your projects, use global variables only when there is no other way to share data between forms.
When global variables must be used, it is good programming practice to declare them all in a single module,
grouped by function. Benefits from declaring variables in advance include: saving programming time by
reducing the number of bugs caused by typos and minimizing the amount of memory that is used during execution of your macro. Remember that we discussed using the Option Explicit statement in all your forms,
modules, classes, etc.
How are Constants used?
A constant is a meaningful name that takes the place of a number or string that does not change. Although a
constant resembles a variable, you can't modify a constant or assign a new value to it as you can when working with a variable. Often you'll find that your code contains values that reappear over and over without
changing. Or you may find that the code depends on certain numbers that are difficult to remember numbers that, in and of themselves, have no obvious meaning. An example of a constant is the value of pi. You
can greatly improve the readability of your code and make it easier to maintain by using constants.
The syntax for declaring a constant is:
[Public|Private] Const constantname[As type] = expression

(Continued on page 3)

PaperSpace

Join AUGI free at www.augi.com

July 2002

VBA Foundations, Part 5


A Tutorial in VBA for BeginnersThe Fifth in a Twelve Part Series
Richard L. Binning / rbinning@attbi.com
What are Control structures?
Control structures allow you to control the flow of your program's execution. In the past, programs had to be
written by putting each executable line in the order that it would be invoked. If you wanted to do the same
command many times, then you simply wrote that command multiple times. In VBA, as in other high level
languages, you can create control structures which allow you to repeat statements without rewriting them
over and over. While some very simple programs can be written in this top-down left-to-right manner, most
of the power and utility of any programming language comes from its ability to change execution order with
conditional control structures and loops.
There are two basic types of Control Structures; Decision or Branching Structures and Looping structures.

Decision (Branching) Structures


VBA procedures can test conditions and then, depending on the results of that test, perform different operations. The decision structures that VBA supports include:
If...Then
The simplest of Branching structures, the If Then structure can test a simple condition such as color
of entity, or value of something. This is used in the following manner:
If some expression Then
DO SOMETHING HERE
End if
If...Then...Else
A more complex version of the If Then structure, provides the ability to do one thing if the expression is true otherwise do something else. Note: This doesnt mean that the second condition is true, just that
the first condition is not true so this is the only other possibility. This is used in the following manner:
If some expression Then
DO SOMETHING HERE
Else
DO SOME OTHER THING HERE
End if
Select Case
The most complex of the branching structures, it provides the ability to define many different conditions and include a default condition if none of the conditions is found to be true. This is used in the following manner:
Select Case some value
Case First Value
DO SOMETHING HERE
Case Second Value
DO SOMETHING HERE
th
Case n Value
DO SOMETHING HERE
Case Else (Note: This is optional)
DO DEFAULT THING HERE
End Select
(Continued on page 4)

PaperSpace

Join AUGI free at www.augi.com

July 2002

VBA Foundations, Part 5


A Tutorial in VBA for BeginnersThe Fifth in a Twelve Part Series
Richard L. Binning / rbinning@attbi.com
Looping Structures
Loop structures allow you to execute one or more lines of code repetitively without re-typing that code repetitively. These repetitive loops can be as long or as short as required and can change based on variables
contained in the code itself. The loop structures that Visual Basic supports include:
Do...Loop
A Do loop executes a block of statements an indefinite number of times. There are several variations of the
Do...Loop statement, but each type checks a numeric value before it continues the next loop.( Note: The
statements never execute if condition is initially False. ) As with If...Then, the condition must be a value or
expression that evaluates to False (zero) or to True (nonzero). This is used in the following manner:
Do While condition to be checked
DO SOMETHING HERE
Loop
For...Next
A For Next loop is the workhorse method for looping a known number of loops. It is frequently used for user
defined collections and intrinsic VBA collections alike. Again there are a couple variations of the For Next
Loop. We will show examples of both types since they are used so frequently. This is used in the following
manner:
For counter = start To end [Step stepvalue]
DO SOMETHING HERE
Exit For
Next counter
This type can be used to loop through all the values contained in an array or for all values contained in a
user defined custom type of object (more on this later). The start is the minimum value for the loop, the
counter is typically a variable which is incremented (by the stepvalue) until it reaches the end or maximum
value. The Exit For command is used when the correct value is obtained since it is the only way to continue
past the end of the loop without finishing the looping. (Note: You can also count backwards by reversing the
start and end values and making your stepvalue equal some negative integer.)
For Each...Next
A For Each Next loop is the workhorse method for using built in collections in AutoCADs object model. It
is frequently used when the count of the collection is unknown. A For Each...Next loop is similar to a
For...Next loop, but it repeats a group of statements for each element in a collection of objects or in an array
instead of repeating the statements a specified number of times. This is used in the following manner:
For Each Collection Item In Collection
DO SOMETHING HERE
Exit For
Next Collection Item
This type can also be used to loop through all the values contained in an array or for all values contained in
a user defined custom type of object (more on this later). The Exit For command is used when the correct
value is obtained since it is the only way to continue past the end of the loop without finishing the looping.
(Note: You usually have to simply declare the collection item but declare and populate the collection object.)
(Continued on page 5)

PaperSpace

Join AUGI free at www.augi.com

July 2002

VBA Foundations, Part 5


A Tutorial in VBA for BeginnersThe Fifth in a Twelve Part Series
Richard L. Binning / rbinning@attbi.com
Take Advantage of Collections
The ability to define and use collections of objects is a powerful feature of both VBA and AutoCAD. While
collections can be very useful, for the best performance you should use them correctly: Collections allow
you to iterate through them using an integer For...Next loop by incrementing the counter. However, the For
Each...Next construct is easier to read and maintain and in most cases is much faster. Although the For
Each...Next iteration is a built in method of the collection, it is implemented by the author of the collection
itself so the actual speed may vary. When you have a group of objects of the same type, you can usually
choose to manage them in a collection or an array. From a speed standpoint, which approach you choose
depends on how you plan to access the objects. If you can associate a unique key with each object, then a
collection is the fastest choice provided that the number of objects in the collection is greater than 100. Using a key to retrieve an object from a collection is almost always faster than iterating through an array sequentially. However, if you do not have unique keys and therefore will always have to iterate through the
array, then it is the better choice. For small numbers of objects (Less than 100), arrays consume less memory
and can usually be searched more quickly.
Now lets revisit our code from the last article. Take a look at the graphic shown. Utilizing the new definitions we have learned in this article I have taken the liberty of adding some notes in burgundy to the existing
graphic.

In the next issue we will make this routine more intelligent, more efficient, add some error checking, and
Explore and utilize some of the built in functions made available to us by AutoCAD, and VBA.

PaperSpace

Join AUGI free at www.augi.com

July 2002

Вам также может понравиться