Bill Kramer - John Gibb - Bill Kramer AutoCAD VBA Programming Tools and Techniques - Exploiting The Po
Bill Kramer - John Gibb - Bill Kramer AutoCAD VBA Programming Tools and Techniques - Exploiting The Po
Bill Kramer - John Gibb - Bill Kramer AutoCAD VBA Programming Tools and Techniques - Exploiting The Po
author:
publisher:
isbn10 | asin:
print isbn13:
ebook isbn13:
language:
subject
publication date:
lcc:
ddc:
subject:
Page i
Copyright © 1999 by John Gibb and Bill Kramer. All rights reserved. No part of this
book covered by copyrights hereon may be reproduced or copied in any manner
whatsoever without written permission, except in the case of brief quotations
embodied in articles and reviews. For information contact the publishers.
Distributed to the book trade in the U.S. and Canada by
Publishers Group West, 1700 Fourth Street, Berkeley, CA 94710
Cover Art: Robert Ward
Cover Design: The Visual Group
Interior Design and Composition: Brad Greene
Library of Congress Cataloging-in-Publication Data
Gibb, John W.
AutoCAD VBA programming: tools and techniques / by John Gibb and Bill Kramer.
p. cm
ISBN 0-87930-574-6 (alk.paper)
1. Computer graphics. 2. AutoCAD. 3. Microsoft Visual Basic for applications.
I. Kramer, Bill, 1958. II. Title
T385.G5217 1999
620'.0042'02855369dc21 99-43360
CIP
Printed in the United States of America
99 00 01 02 03 04 54321
Page iii
Dedication
Bill Kramer
I wish to dedicate this book to the memory of my friend John Keith and
my cousin Christopher Etheridge. Thanks to John for his humor and cre-
ative talent and Christopher for his youthful enthusiasm. Both left us
much too soon.
John Gibb
Page iv
Acknowledgments
I would like to thank my girlfriend Margaret, her sons Brian and
Bob and my mother for their unwavering support despite my
frequent lapses of memory during the writing of the book.
Sometimes focus is good for writing but hard on the ones you love.
Thanks for your patience.
I would also like to thank Application Developers, Andy Baron and
Mike Gunderloy for the use of their command line material as the
basis for the command line workaround material. A special thanks
to Bob Verdun and my colleagues at CFI for their patience during
the time it took to write this book.
2042015b45d2b5416108e486be44e8bc.gifJOHN GIBB
Preface
Search though you may, you won't find two more qualified people
to co-author a book on VBA and AutoCAD than Bill Kramer and
John Gibb. Both have written several books plumbing the depths of
programming as a science and an art. Both have explored
AutoCAD and AutoLISP since their inception and both are much
sought-after programmer-consultants by a wide range of science
and engineering firms.
When issue No. 1 of CADENCE was published in 1986, Bill
Kramer launched a column titled ''AutoLISP Concepts," that over
the years has transformed into his current "Programmer's Toolbox"
and that stands as the longest running column in CADENCE's 14-
year history. With the advent of VBA capabilities in AutoCAD
Release 14, Kramer expanded his "how to" programming tutorials
to include frequent explorations of the intricacies of Visual Basic
for Applications. John Gibb, too, has been a frequent contributor to
CADENCE and both have helped countless programmers boost
their knowledge of AutoCAD, AutoLISP and VBA through
courses at Autodesk University, among other venues.
A graduate of Ohio State University's College of Engineering
where he studied computer science and astronomy, Kramer first
"got into" computers with a DEC PDP-8 in 1975 teaching himself
assembler code. He programmed his first microcomputer, a Z-80-
based system with 32K RAM and two 160K disk drives, using
BASIC and assembler languages. In 1985
Page vi
he launched Kramer Consulting and began developing applications
for general CAD systems and AutoCAD in particular, including an
NC programming system called NC-AUTO-CODE that he has
supported ever since its first customer ship in 1986. Kramer has
taught AutoCAD as an adjunct professor at Franklin University for
several years and frequently offers sold-out classes in programming
through Autodesk University.
As an Autodesk certified instructor, John Gibb has himself spent a
fair amount of time sharing his vast programming knowledge with
students at the Moraine Valley Autodesk Training Center. With a
background in topology and utility mapping, space planning and
facilities management systems, he has devoted 12 of his 15 years as
a programmer to AutoCAD-related applications. An author of three
books and numerous journal articles related to AutoCAD, Gibb is
currently a senior applications developer with Computerized
Facility Integration.
Gibb and Kramer share a keen ability to comprehend the black art
of programming science and render it palatable. Both are noted for
their sense of humor. But you can tell them apart in a crowd. Bill is
the tall onea former basketball player and current eclipse chaser
who almost doesn't need a telescope to practice his craft. John's the
one with the pony tail.
As a team, Gibb and Kramer bring unparalleled programming
knowledge and experience to customizing AutoCAD with VBA.
Updated to include capabilities introduced with AutoCAD 2000,
this book is destined to become a de facto standard for AutoCAD
programmers. Although aimed at those with advanced-intermediate
and expert-level ability, there is much here as well for others who
are new to programming science who would like to use VBA to
maximize their AutoCAD productivity.
As authors, lecturers and consultants, Gibb and Kramer are best of
class. They are also decent human beings. Read this bookyou won't
be sorry you did. And when you attend the next Autodesk
University, take a class with them, or just stop them in the hallway
to chat. They'll love it and likely keep you just a bit longer than you
may have planned. But when you're done, you'll be all the richer
for it.
ARNIE WILLIAMS,
2042015b45d2b5416108e486be44e8bc.gifEDITOR IN CHIEF,
CADENCE MAGAZINE
Page vii
Table of Contents
Introduction xiii
Chapter 1 1
The AutoCAD VBA Environment
2042015b45d2b5416108e486be44e8bc. AutoCAD 1
gif Programming
Solutions
2042015b45d2b5416108e486be44e8bc. How AutoLISP 3
gif Differs from VBA
2042015b45d2b5416108e486be44e8bc. Object-Oriented 39
gif Programming
Introduction
2042015b45d2b5416108e486be44e8bc.gifWhat's an Object? 41
2042015b45d2b5416108e486be44e8bc. The Management 42
gif Features of Objects
2042015b45d2b5416108e486be44e8bc. Object Concept 43
gif Example
Chapter 4 59
The AutoCAD Object Model
2042015b45d2b5416108e486be44e8bc. Methods, Properties, 59
gif and Events
2042015b45d2b5416108e486be44e8bc.gifPreferences 94
2042015b45d2b5416108e486be44e8bc.gifExample Sequence 96
Chapter 5 102
Working with Entity Collection Objects
2042015b45d2b5416108e486be44e8bc.g The Collection 102
if Object
2042015b45d2b5416108e486be44e8bc. Selection Sets 103
gif Collection
2042015b45d2b5416108e486be44e8bc. Building a Collection 104
gif of Entity Objects
2042015b45d2b5416108e486be44e8bc. Accessing Selection 106
gif Set Members
Chapter 8 201
Managing Multiple Projects
Introduction
Why another book about VBA? John and I first started talking
about writing a book together some time ago. As programmers and
teachers of others how to program, we found that we had many
similar experiences. One of which is that you can never have
enough examples of how to do various things. Both of us used
books written by others as well as ourselves as sources for
examples in both writing new code as well as teaching others to
program. Another thing we felt that many books provided was a
variable perspective on how to get the job done. That is, different
ways to think about how to solve problems with programs and
obtain improved productivity.
And while we were discussing the merits of books and the logistics
of writing one together, an opportunity was presented by Miller
Freeman Inc to author one about VBA Visual Basic for
Applications. Both of us had extensive experience in BASIC and
programming in general thus we thought it would be fun to put one
together. We were right. It was fun and we both learned a lot from
each other along the way. And to increase the amount of pleasure,
we switched systems along the way. We started working with VBA
in AutoCAD Release 14 and ended up in AutoCAD 2000 by the
time we finished. The book is written for both versions however
there are features in the newer AutoCAD VBA that will not
Page xiv
work in the earlier one. We tried to point those out when we
reworked the chapters after getting the newer AutoCAD release.
Writing a book about a subject as broad as VBA means that we
jumped around a little here and there between chapters. We tried to
build on knowledge learned from earlier chapters as the book
progresses but at times it may seem like we shifted subjects in an
extreme manner. That was so we could fill in more of the
foundation of knowledge needed for the next step. The following
paragraphs demonstrate this fact as they briefly explain the
chapters in the book.
In chapter 1, we start with a basic introduction of what VBA is and
how it fits into AutoCAD. Because many readers of this book are
new to VBA, we wanted to get the terms defined that make up the
''VBA Talk". We also wanted to help clarify the differences
between VBA, AutoLISP, and Visual BASIC from Microsoft.
Chapter 2 jumps feet first into a simple project. This chapter was
intended for those readers who prefer to take a look around the
software first and then learn more about the details. The VBA
environment is explored in a hands-on fashion to provide a feel for
what it is like to write programs using this tool.
From our experiences in teaching VBA, both of us have learned
that it is important to understand what objects are all about and
how they relate to programming. Although simple in concept,
object-oriented-programming is a new notion to many just learning
VBA and other newer programming systems. In chapter 3 we
introduce objects and how the AutoCAD object database is
connected together. This chapter serves as a foundation for further
details into the objects VBA programmers manipulate.
Chapter 4 drills into the AutoCAD object looking at the way
everything is connected and introducing the main features found in
the model. In chapter 5 we take a detailed look at manipulating
collections of objects such as selection sets or groups of entities in
a drawing. Chapter 6 explores the tables found in the drawing such
as layers, line types, dictionaries, and so forth. These chapters
combine to provide a look at
Page xv
the entire AutoCAD VBA object system and how you work with it
from a general point view.
Many books about VBA finish after explaining the object model,
but since this book is focused towards AutoCAD application
developers we wanted to go further into some of the areas students
have wanted to see.
In chapter 7 there is a discussion about how to interface with other
automation servers such as Microsoft Excel. Examples are
provided that show how easy it is to interface with these other tools
in the computer system. We also look at extended data and how one
can use that feature of AutoCAD's customization to yield
tremendous benefits.
Project management for programming is important and chapter 8
provides information about how to work with more than one
project at a time to save time in the development effort. And while
on the subject of saving time, chapter 9 shows how to make use of
the tools provided in the Windows environment itself. Virtually all
of the time saving, operator friendly, aspects of Windows of that
you want to use are available through the Windows API library.
The only problem is that you have to find them and this chapter
shows you how to do just that.
A list of samples, examples, and useful utilities is found in chapter
10 where John provides a long list of routines from his personal
toolbox. John's earlier books on AutoLISP contained many of these
utilities and he translated them to VBA making them available with
this work.
In chapter 11 we took a more serious look at VB versus VBA.
They are not the same, but they share a lot of the same attributes.
For programmers looking to export their knowledge of VBA to VB
this chapter serves as a guiding light to what can be done. At the
same time, those programmers experienced with VB but wanting to
learn about VBA will find useful information in this chapter as
well. And as long as we are talking about experienced, we chose to
share some of our experiences in chapter 12 where we investigate
several possible pitfalls and provide tips we have learned along our
journey. That leads into chapter 13 with a discussion of
programming style to make your programs easier to read and work
with in the future.
Page xvi
In the last chapter we look at creating your own objects through
two examples. Most beginner VBA programmers do not venture
this far and that's why we saved it for the last chapter. If you are
serious about doing wonderful things with AutoCAD VBA, then
defining your own objects is a very powerful tool to use. And the
best way to explain it is to show two useful examples.
You should not think of this book as your only reference for VBA,
there is an extensive help library included in the system. This book
will help you understand that help library even better by having a
strong foundation of VBA know-how behind you. In addition, the
attached CD has more examples and even more information about
other aspects of the AutoCAD system such as plotting.
We hope you are able to learn about VBA and enjoy it as much as
we do through this book. The fun of getting the computer to do
something special that you programmed is tremendous. It is also
contagious as you learn new tricks and tidbits along the way. Keep
on programmin'!
Chapter One
The AutoCAD VBA Environment
Intended for programmers new to Visual BASIC for Applications
(VBA), this chapter explores how VBA relates to other
programming solutions inside AutoCAD. We will present a
comparison of VBA, Visual LISP, and AutoLISP for readers
familiar with the AutoLISP language and associated methods of
AutoCAD customization. We will also introduce the various
components of the VBA programming environment and give an
explanation of how to start VBA inside AutoCAD.
Figure 1.1
VBAIDE in AutoCAD
When started with a project already loaded, the IDE will present a
full-screen development environment containing multiple windows
as seen in figure 1.1. Select the one you want to work with by
picking it from the Windows pull-down menu or by selecting the
proper icon in the toolbar menus shown. When starting with no
existing VBA program in memory, the IDE presents a blank work
area with the project explorer and properties windows visible. Use
the menu Insert options to start the definition of a code module or
input form. The next chapter contains a tutorial walk-through to
create a simple program in VBA and can be used to learn the basics
behind programming in this environment.
What's in the IDE?
As we mentioned before, there are numerous windows in the IDE,
and at first they may not appear all that friendly. But it does not
take long
Page 15
before you will be comfortable navigating your way through
complex programs of your own design. The IDE was written by
programmers, for programmers, and as such it serves as a very
powerful tool in the development of applications. So let's look at
the various components in the IDE and get a general feeling as to
what they are for and how to use them.
Project Explorer: (Figure 1.2) This window presents a tree diagram
showing the modules and forms that are part of the current project.
The Project Explorer provides one method for getting around in
your program code. To get to a particular module, select it in the
hierarchy, then select the view code or form button. When you're
writing code, you won't use the Project Explorer too often, so it can
be hidden to make more space for the code window.
The Project Explorer becomes more and more useful as your
projects grow in complexity through the addition of more forms
and code sections. As the need comes up, you can restore it to the
screen for navigating about your project.
Figure 1.2
Project Explorer
User Form Windows: The dialog boxes of an application are
defined in user form windows. Generally you start development of
a new application by opening a new user form window and then
placing the controls for that window into the grid displayed. You
can quickly jump to the code window and the code specific to an
event by double clicking on a control while in the user form
window. Designing new forms is very easy, and it is tempting to
get ''creative" in how you present something. Chapter 13 has been
devoted to programming style, and we recommend that you adopt
standard styles for a variety of reasons.
Properties Window: (Figure 1.3) The details about whatever object
is currently highlighted will be shown in the Properties window.
Details
Page 16
include the name of the object, the color or display disposition of
controls and forms, captions, and numerous other features. You'll
use the Properties window the most when you are working on the
design of a form for user input. During coding it will seldom be
referenced, except to see what possible values a property might
take. Like the Project Explorer, it can be removed from view to
make more room for the code window.
Each object on a form has a variable number of properties, and the
list will change as you select the different controls. These represent
the control properties that can be set at design time when you are
creating the program for the first time. For some controls, there are
additional properties that can be added while the program is
running. When referencing a property in the help system, make
sure to note if it is run time changeable.
Figure 1.3
Properties window
Code Window: Program entry and review takes place in the code
windows: there is a code window for each user form that has code
associated with it. Entering code into a new program is aided in the
code window by the system. When you reference an object such as
a control in a form or an AutoCAD data entity, the editor will
prompt you through the various levels of the object to get to the
property or method you need. And as you debug your programs the
system will show you the code that caused a problem in the code
window related to the user form or module in which the problem
occurred.
The Object Browser: (Figure 1.4) Start the Object Browser window
by selecting the Object Browser button, by selecting it from the
View menu, or by pressing the function key 2. The Object Browser
is a tree structure display that shows all the objects known by the
VBA system. This is
Page 17
where you go ''shopping" for an object when you are not sure of the
name or when you are looking for a method (function) to perform a
particular task. The Object Browser links to the help system
through the function key 1 that facilitates the learning of the object
library. Although there are many objects in the library it does not
take too long to learn the important ones.
Figure 1.4
Object Browser
Chapter Two
VBA Application Jump-Start
In this chapter we are going to jump right into the VBA
programming environment and develop an application program.
The program is not advanced, but it does serve as a good example
of the power of VBA inside AutoCAD. It also gives programmers
who are learning the VBA system a chance to try out the features
in the programming environment by following the step-by-step
procedures.
Figure 2.1
Block Counter macro running
Figure 2.2
Toolbox controls
The toolbox contains the components that can make up a screen.
As you move your mouse over each and
Page 22
hesitate, a highlight box (tool tip) will appear telling you the name
of the object as in figure 2.3.
Figure 2.3
CommandButton selection
The dialog box in Figure 2.1 contains two controls (objects). The
button is a control, and so is the listbox.
Select the CommandButton option from the toolbox controls.
Locate a point on the grid to place the button as in Figure 2.4.
Figure 2.4
Placing CommandButton in grid
If you make a mistake or want to move the button on the grid, just
select it and drag it to a new location. You can also resize it and
change the corners as needed by your application. The control just
inserted will behave like most Windows objects do. You can
change its location and size with the pointing device only. Now
let's change the information inside the control object. That is, we
will change some of the properties of the CommandButton to suit
our needs. You cannot change these properties with a mouse alone,
so you will have to do some keyboard work.
Select the properties dialog box as in figure 2.5.
Pick the Caption property within the list shown. You may have to
scroll the list to get to the property you want.
Using the keyboard, type a new caption value''Return to
AutoCAD."
Figure 2.5
Properties dialog
Notice that as you type the command button will change as well.
The text you are typing will appear in the CommandButton in the
form design window. You can resize the CommandButton as
needed so that the text fits.
Page 23
The components of a dialog box are considered objects. We will
discuss objects in the next chapter, but an important thing to keep
in mind when programming them is that they contain properties.
Another term might be variables, but it really goes much beyond
that notion.
You can also select the View Object icon in VBA to bring the
forms editor to the front.
Page 25
It is time to give our form a name and a better title. We can do that
by changing the properties of the form object.
To view the properties, if they are not already visible on the screen,
select anywhere on the form (grid or title bar), then press the right
mouse button. The Properties window option is in the list. Select
on the formnot on the CommandButtonto make sure the properties
showing are for the UserForm as in figure 2.7.
In the Properties window, select the (name) property at the start of
the list.
Type in the name, ''BlockCount." This is now the name of the form
object.
Select the Caption property.
Type in the new caption, "Block Counter."
Figure 2.7
Properties for UserForm
Figure 2.8
Selecting a list box control
You can manipulate both control objects in the form using the
pointing device. By picking the object (with a single click), you
can
Page 26
move and resize the control into position. This is the most visual
feature of building a visual interface and can be a lot of fun as you
see what different controls look like together.
Checklist
At this point in our program design, we have the following defined:
1. A form named BlockCount
2. Two controls on the form, a button, and a list box.
3. The controls are named CommandButton1 and ListBox1. These
are the default names assigned when the objects were defined.
4. A function named CommandButton1_Click that is attached to
the BlockCount form.
Figure 2.8
Text editor banner
Global SS As AcadSelectionSet
Global BLKS As AcadBlocks
Global BLK As AcadBlock
Global Grps(0 To 1) As Integer
Global Dats(0 To 1) As Variant
Global Filter1, Filter2 As Variant
Page 28
This code sets up some variables that will be used in the program.
We are declaring these variables as global so we can re-use them in
various subroutines within our application. The variable ''SS" is
declared as a selection set object. We will use this object to locate
the block inserts inside the drawing. We will use BLKS as a pointer
to the blocks collection where the block table can be found. BLK is
a block object, which contains information such as the name of the
block, base point, and much more. Two arrays are defined, Grps
and Dats, to hold the filter information for building the selection
set. Because of the way variables are passed to AutoCAD from
VBA (and VB), variants are used for the filters. Filter1 and Filter2
are the variants used.
Note how VBA tries to help you along when you're typing in the
program code above. Although some may question the value of this
feature, when you are typing long AutoCAD names, it's a real time
saver. To select the highlighted item from the automatic pop-up list,
just press the Tab or Enter key. You can use the pointing device to
highlight the name desired.
We will discuss table collections, selection sets, filters, and other
details in much more detail in subsequent chapters. This example is
meant to give you a flavor of the programming environment.
Counting Blocks Macro
Now it is time to write the macro that starts the entire process. The
macro is to be titled BlockCounterthis is where we'll find some
more program code typing.
While still in the text editor, after typing the Filter1 and Filter2
variant declaration, type Sub BlockCounter ( ) and press the Enter
key.
The End Sub statement will automatically be added and the header
above the code should be changed to GeneralBlockCounter.
Now type in the code that appears in the following listing. Be
careful to get it right! Program code must be exact, as computers
do only what we tell them to do.
Page 29
Sub BlockCounter()
Grps(0) = 0: Dats(0) = ''INSERT"
Grps(1) = 2: Dats(1) = ""
On Error Resume Next
Set SS = ThisDrawing.SelectionSets.Add("SS")
If Err.Number <> 0 Then
Set SS = ThisDrawing.SelectionSets.Item("SS")
End If
SS.Clear
Set BLKS = ThisDrawing.Blocks
Dim J As Integer
J = BLKS.Count 1
For I = 2 To J
Set BLK = BLKS.Item(I)
Dats(1) = BLK.Name
Filter1 = Grps
Filter2 = Dats
SS.Select acSelectionSetAll, , , Filter1, Filter2
Out$ = BLK.Name & " " & Str$(SS.Count)
BlockCount.ListBox1.AddItem Out$
SS.Clear
Next I
While 1 = 1
BlockCount.Show
Wend
End Sub
The next step in the program is to define a selection set object. This
operation merely sets the room aside for a selection named "SS".
The variable name of the object (SS) matches the name of the
selection set for our own convenienceit is not a requirement of the
system. Since we don't know if that selection set has anything in it,
the next operation
Page 31
is to clear it just to make sure. The add( ) method will add a new
name to the selection sets collection if it does not already exist in
the list. If the name already exists, an error will result. By setting
the error recovery mode active in the program the error will not
cause the program to fail. Instead, the object is opened using the
item( ) method. The Clear method of the selection set object clears
out any entity object references that may have been in the selection
set.
Set BLKS = ThisDrawing.Blocks
J = BLKS.Count - 1
For I = 2 To J
The next step in the program is to start into a loop to look at all
blocks stored in the drawing. The block table is stored in what is
called the blocks collection, which is accessed through the current
drawing object. The first statement above obtains the blocks
collection object. ThisDrawing is the current drawing, and the dot
following it symbolizes a property or method. The property being
used is Blocks.
Notice how the BLKS variable now can be used to obtain
information about the blocks collection. In the second statement
above, the BLKS. Count reference obtains the count property. The
count is the number of block objects in the blocks collection.
We start a For loop to iterate through the collection. Access into the
collection is by index, meaning that it is zero-based. Index 0 gets
the first element, 1 gets the second, and so forth. The loop starts
with the third element in the blocks collection. The first two blocks
are Model Space and Paper Space, and these blocks are not inserted
into the drawingthey are the drawing. The For loop will iterate until
the number of blocks in the table minus one has been reached. The
minus-one portion of the loop control is for the index value of the
last element in the block table. To illustrate, if there are five blocks
in the table, including Model and Paper Space, the loop will iterate
three times (index values 2, 3, 4).
Set BLK = BLKS.Item(I)
Dats(1) = BLK.Name
Page 32
The BLKS object is the table or collection of block names. To get
the details on a particular block we can access this table by name or
by index number. The result of accessing the table is a block object
(BLK). The name of the block is a property of the block object, and
the program assigns it into the data array for the filter.
Filter1 = Grps
Filter2 = Dats
SS.Select acSelectionSetAll, , , Filter1, Filter2
The variants Filter1 and Filter2 are assigned to the arrays (Grps and
Dats). This must be done after any changes to the arrays, as the
variant linkage needs to be refreshed before they are used in the
parameter call to the selection set building functions.
SS.Select will build a selection set. In this case, it has been
instructed to look at all objects in the drawing and use the filters to
determine which ones are of interest. The filter used in our example
looks for ''INSERT" objects with a specific name.
Out$ = BLK.Name & " " & Str$(SS.Count)
BlockCount.ListBox1.AddItem Out$
We obtain the value to be added to the list box by taking the name
of the block and concatenating it to a string created from the size of
the selection set just created. The property name Count was used
for the selection set collection as well as the blocks collection. This
is a feature of object-oriented programming called polymorphism,
and it is used extensively in VBA object control inside AutoCAD.
The name of the list box is derived from the name of the object that
houses it. The form we created is called BlockCount. Inside that
form we created a list box object named ListBox1. To get to the list
box, we have to declare this hierarchy to VBA through the
mechanism demonstrated above. AddItem is a method (subroutine)
associated with list box objects. It will add a new string item to the
end of the list box.
List boxes in VBA are different from list boxes in other AutoCAD
programming systems using DCL. The list boxes of VBA retain the
data so
Page 33
that they can be retrieved directly from the list box itself. List
boxes and other controls serve as data containers for applications,
even when they are not on the screen as in this case. The
BlockCount form is still hidden, as far as the system is concerned,
while this section of code is running. We are simply loading up the
contents, and when we are ready, we will turn on the form for the
user to see.
SS.Clear
Next I
Before going on to the next block in the block table, the selection
set (SS) is cleared. The Select( ) method will add objects to the
selection set each time it is run. Existing objects in the selection set
remain while the new ones are added; hence it is important to
remember to clear the selection set with each iteration.
At the completion of the loop we are ready to start the dialog box
(form) to display the blocks and their respective counts. The list
box contents have been loaded, and all that remains is to set the
computer focus to the dialog box.
While 1 = 1
BlockCount.Show
Wend
This program module contains some code that is a little tricky for most
beginners. The module starts when the operator clicks on or selects one
of the list box members. Our goal is to display the block insertions for
that member by highlighting them.
LL$ = ListBox1.List(ListBox1.ListIndex)
This line of code extracts the highlighted selection from the list box.
ListBox1 is the name of the control (object) in the form. There are two
properties we are going to use from the list box. The first accessed is the
ListIndex, which is the integer index (base 0) into the list of the currently
selected item in the list. The second property of interest is the List
property that contains the list in the form of an array of strings. By
obtaining the list index first, then passing that to the list access property,
we obtain the value of the selected member in the list. The selected
member is stored as a string in variable LL$.
Page 36
While Mid$(LL$, Len(LL$), 1) <> " "
LL$ = Mid$(LL$, 1, Len(LL$) - 1)
Wend
While Mid$(LL$, Len(LL$), 1) = " "
LL$ = Mid$(LL$, 1, Len(LL$) - 1)
Wend
Our list box contents consist of the block name followed by a count
of the number of insertions found in the drawing. This section of
code removes the count and trailing spaces from the string (LL$).
Suppose we have a block named WIDGET and it has been inserted
twelve times in the drawing. The value in LL$ would be WIDGET
12.
Because block names can have embedded spaces in them, we must
start at the back of the string (LL$) and remove the numeric
characters, then the spaces. We cannot start at the front of the string
and work our way forward until we encounter a blank. The first
While loop in the code segment will iterate until a blank is found;
thus, it would remove the 12 from the example cited. The second
While loop then removes characters until a nonblank character is
encountered. The string manipulation going on inside the loops is
standard Visual BASIC string manipulation making use of the
Mid$ (middle or partial string) and Len (length of string) functions.
Dats(1) = LL$: Filter1 = Grps: Filter2 = Dats
SS.Clear
SS.Select acSelectionSetAll, , , Filter1, Filter2
This statement causes the form (dialog box) to be hidden. When the
current function finishes, control will be returned to the macro that
performed the Show function for the dialog box. If the Hide function
were not present, control would return to the dialog box system when
the function terminates. The use of Show and Hide is a slick way to
control dialog boxes in VBA. A calling program starts the dialog box
with a Show, and when the dialog box wants to return to the calling
program, one of the call back functions performs a Hide operation.
Note that in the Button1_Click (above) function the End statement
was used. This resulted in both the dialog box being hidden and the
program terminating. Control was not returned to the macro
containing the Show function call.
SS.HighLight True
LL$ = ThisDrawing.Utility.GetString(0, "Press Enter")
SS.HighLight False
The block inserts found for the particular block name are highlighted
with the Highlight method. This method contains a single parameter,
true or false. When true the objects are highlighted. When false the
highlight mode is turned off for the objects.
Between the two highlight statements, our program pauses for the
user. You can think of the utility object as a set of functions for
performing user input and output at the AutoCAD command level,
thereby providing access to the traditional interfaces for users.
Chapter Three
Understanding the AutoCAD Object-Oriented
Database
Object-oriented programming (OOP) is a buzzword in computer
programming circles. In this chapter we will discuss what it means
and how you use it in relation to AutoCAD customization. We will
devote the beginning sections of the chapter to objects and object-
oriented programming practices. Toward the end of the chapter we
will pay specific attention to how to use VBA to accomplish the
interface.
What's an Object?
Let's start by getting a handle on the term object and what it means
in relationship to computer program development. We also need to
get comfortable with some terms related to objects and object-
oriented programming.
So exactly what is an object? Technically speaking, an object is a
software container package that holds both properties (data) and
methods (functions). Objects are container packages in that the data
and functions all exist together. You cannot get at a piece of the
object without having the whole object available. How the
computer keeps track of everything is not that important at this
point. What is important to realize is that although this may seem
like a terrible burden, it is actually not too bad for modern
computers. And besides, these tools are meant to make the
programmer more efficient! One thing that experienced
programmers will notice immediately is that an object can be
referenced in whole with a single variable. When dealing with
complex objects, that can be very nice indeed.
An important feature of objects is that you can rely on them. By
having an entire object together in the system, it can keep track of
itself. What this means is that an object can have integrity. Integrity
in this case includes allowing only specific changes within a set of
rules as defined for the object. This way you don't end up with a
circle without a radius value or a line with only one data point.
When you create one of these graphical objects successfully, they
contain all the elements needed to be functional in the context of
AutoCAD. The integrity features of objects can impact the amount
of time it takes to program an application. An object will not let
you put bad data in or do something that it doesn't want to do.
Page 42
The concepts behind objects are not new in computer science. In
fact, they have been around for several decades, and several
variations on the concept can be found in most modern computer
systems such as the Apple Macintosh and Microsoft Windows.
Until recently the problem has been that computers need a lot of
memory to work with large object-based systems. Modern
computers sport more main memory than the disk drives of
machines a decade ago, so object-style programming has become
the norm. With the advent of CD distribution for larger media (no
more installing twenty-plus diskettes for a larger application),
objects have really become the popular way to develop advanced
programs.
The Management Features of Objects
Object programming is attractive to computer programmers and
managers because it re-uses working code. And should that piece
of code stop functioning for whatever reason, it can be modified to
work properly once again. This preserves past work in a better
fashion and allows newer applications to be built on solid
foundations.
Not too long ago it was discovered that entire applications had to
be rewritten as the technology evolved. Programs changed from
having no user input except from a card reader to being interactive.
Then they changed again from being sequentially interactive to
being event driven. This happened because computers got better
and faster. Thirty years ago it was a dream to have a video system
capable of what is found in a typical home computer on the market
today. The problem is that it costs a lot of money to have working
programs rewritten to take advantage of the improved technology.
And that is considering only the input aspect of the applicationit
does not incorporate the evolution of output devices and
processors.
From a management point of view, objects provide a nice way to
preserve your work through multiple generations of hardware.
Applications based on objects will be portable so long as the
objects are available. A rebuild of the application based on the
improved or modified object
Page 43
libraries is all that will be needed in many cases. The key to
identifying the items that would make good objects is
understanding what objects are all about.
Figure 3.1
Public transportation object
In Figure 3.1, all the objects share the features of the public
transportation object. That means you can buy a ticket, take a ride,
and so forth. In addition, the Propeller and Jet objects share similar
properties because they are both airplanes. That is, they both fly,
and it's required to get a special license to operate the airplane.
Having an operator license for a plane does not qualify one for
operation of a bullet train, however. Similar objects on the same
tree branch can often trade features, but you cannot trade features
across different branches.
There are many reasons why objects are attractive to the people
who use computers. Managers of large computer systems like them
because they allow for growth and migration to different
technology. The supplier of the objects has to update only the
system-related objects to upgrade the system. And they are of
interest to the users because they allow them to move to the same
new technology in a comfortable fashion, using language with
which they are already comfortable. The public transportation
object shows that object-level thinking allows for easy migration to
newer technologies and helps keep code up-to-date.
Because objects are models of real world ideas and concepts,
operators can use them at a further distance from the systems
aspects of the computer. They don't have to be computer scientists
to work with the
Page 46
computer in creative ways. Instead, using objects that model the
way a designer works allows the same designer the opportunity to
create new applications without being an expert computer
programmer. That is not to say that VBA objects can be used by
nonprogrammers to create advanced applications, but it does say
that the level of technical knowledge required of the programmer is
not that great.
Here is another quick example of an object and associated
functions. The PLOT command in AutoCAD outputs the drawing
to the output device. The output device can vary tremendously
from a pen plotter to an ink jet printer to some other technology. As
output devises have improved, the command has still been to
PLOT the drawing. Should you be a CAD operator who has
stepped through a time warp from ten years ago you will still know
how to PLOT a drawing in AutoCAD. You might be surprised at
how many things have improved in the meantime, but you would
also find those things you are familiar with from the older version
of the software.
Figure 3.2
AutoCAD object tree
the AutoCAD object tree. With a little practice, getting to what you
want in the object tree will be simple. Most of the time application
programs need to access the entities in Paper and Model Space, or
they need to get to the tables. When other tasks are required, the
object tree can be referenced to find the details involved. Because
of the way objects are addressed in VBA, it is best to have an
understanding of the object tree for whatever system you are
interfacing into. Other programming system interfaces (such as
Word and Excel) will have their own object model that will also be
tree-based. Once you have worked your way through any one of
them you will see how they are all very similar in structure.
Page 52
Collection Objects
Within the document object one finds a host of collection objects.
Collections are all of the tables used in an AutoCAD drawing.
Tables include information such as layers, blocks, dictionaries,
styles, extended data application names, and so forth. New items
are added to the collections (tables), and specific members selected
at this level in the object database. Once a specific member has
been selected, it can be manipulated or removed from the
collection.
From the document object, an object pointer is obtained to the
collection of interest. Given the object pointer of the collection, the
Count property will tell our application how many members are in
the collection, and the Item( ) method can be used to go to a
specific block by name or index number. There are several
examples of scanning and reading the AutoCAD drawing tables
that will appear in later chapters.
In the multiple document interface mode of AutoCAD, the various
documents that are open are stored in a collection accessed through
the application object. In VBA there is a faster way to get to the
current document object that we will see in the next chapter.
The Block Collection Object
Let's focus on one particular collection object, the block collection.
The block collection is where you will find the block definitions. A
block definition is a collection of entity objects that detail the
individual entities that comprise the block. To get to the entities in
a block, start at the document level and go to the collection level.
Next, select the specific block instance you are interested in
viewing, then use a loop to step through the objects in the
collection. New entity objects can be added by using the
appropriate Add method for the type of entity object involved. The
Add methods are found associated with the block object.
Page 54
To remove a block description from the collection of blocks, the
Delete method is used at the block level. You add new blocks with
the Add method at the block collections level. Sometimes this
confuses programmers who feel the delete function should be at the
collections level. The reason it is not located there is so that
AutoCAD can check the usage flags of the block definition before
attempting to purge it from the drawing.
There are two special entity collections that can be accessed from
either the block collection or directly from the document object.
These are Model Space and Paper Space. As new entity objects are
added to a drawing, they are added either to Model Space, Paper
Space, or to a block definition. Nothing is drawn on the screen until
it has been added to either Model or Paper Space. Entity objects
added to a block will not become visible until the block is inserted
into one of the two display spaces. Many of the example programs
found in this book demonstrate the techniques involved in adding
entities to drawings and block definitions. It can look a bit odd at
first, but once you get used to the object tree hierarchy, it is pretty
easy to get the job done.
Entity Objects
Last in the AutoCAD object tree are the entity objects. Entity
objects are the specific entities such as a line or an arc. Each entity
object houses the specific data and methods required when working
with the entity. The line object contains data for the start and
ending points, arcs contain center points, radius and angle values,
and so forth. You can modify these object properties through
methods that will check the input for validity before making any
assignments.
The entity objects contain several methods that do not change or
manipulate the properties of the object but are intended for use
with other entity objects. These methods provide very useful
computations such as determining the intersections between two
objects or performing system tasks such as making copies of the
current object. Because the polymorphism concept is at work in all
of these entity objects, the meth-
Page 55
ods all have the same name, making it easy to learn the complete
library with a little effort.
If you are familiar with the AutoLISP language and how it works
with entities, you will find the object methods of VBA to be much
better. As an example, instead of digging through entity lists
looking for extended data or a specific group code, you can use a
method to access or set the specific data. The method GetXdata is a
great example of this feature. With a single call, an array
containing all the Xdata for an object or just the specific Xdata
related to an application can be retrieved and stored into an array
for easy processing by a VBA program. Compare the two code
segments below that demonstrate accessing a line object and
changing the starting point to a value of 1, 1, 0.
In the AutoLISP version, given an entity name as a symbol EN, the
following expression will retrieve the starting point of a line.
(setq PT (cdr (assoc 10 (entget EN))))
While the above example looks simple enough, look at the opposite
situation, in which we want to update the starting point given a new
point in the symbol PT. Once again, the entity name is provided in
the symbol EN.
(setq EL (entget EN)
EL (subst (cons 10 PT) (assoc 10 EL) EL))
(entmod EL)
Figure 3.3
Object Browser
Page 57
bers of the class in the list box to the right. This is the fastest way
to view all the elements that a library has to offer.
The object browser makes use of various icons or glyphs to aid you
in identifying the components found in a library. Once you learn
these icons you can navigate the object browser faster as you begin
to look for a specific type of information. The glyphs that appear in
the object browser window are described below:
Figure 3.4
Class Symbol
Figure 3.4 is the symbol for class definition. A class is another term
for an object. Objects contain both methods and properties. Classes
appear in the left list box along with enumerated lists and modules.
When you look at the object browser, you will notice that all of the
classes and components defined for AutoCAD start with the letters
acad. For the most part, we are interested in classes (objects) when
programming VBA solutions. The classes are where we find the
individual objects that make up the entities our applications will
want to manipulate.
Figure 3.5
Module
Definition
Symbol
Figure 3.5 is the symbol for a module. A module is typically a
collection of constants that are global to a library. The names for
the constants can be used instead of the values to make your code
more readable. In other cases a module will be just a set of
subroutines that are not tied into an object but exist for general
usage. An example of a module group would be a series of
functions for converting strings and numbers. Modules of
subroutines tend to be general purpose in nature.
Figure 3.6
Enumerated
Object
Symbol
Figure 3.6 is the symbol for an enumerated object list of numbers.
Essentially, this is a list of whole numbers (integers) where each
entry is unique and has an associated name by which it may also be
referenced. Enumerated objects are often employed to define a
selection of options such as the style of the mouse cursor or options
for the display of a form.
Figure 3.7
Method
Symbol
Figure 3.7 is the symbol for a method within an object. Methods
are subroutines and functions. To use one you must include the
name of the object (unless it is impliedmore on that later) before
the method name and separated by a decimal point. You will notice
as you explore the various objects in the object browser that many
of the AutoCAD objects share the same name. This is
polymorphism at work!
Page 58
Figure 3.8
Data
Property
Symbol
Figure 3.8 is the symbol representing a data property. Properties are
the variable values associated with an object. For example, the start
and end points of a line are properties, as is the layer name.
Property values in a class (object) can be declared as public or
private. Only the public properties can be changed in an object
through programmatic control. Private properties do not show up in
the browser under normal circumstance. The only time you will see
private properties is when your program creates them for a custom
object of your own design.
Figure 3.9
Read Only
Property
Symbol
Figure 3.9 is the symbol representing a property that is read-only
and cannot be changed. These properties are for reference only and
contain data such as the area of an enclosed geometry object
(circle, ellipse, polyline, and so forth). Not all of the read-only
properties are marked in this manner, however, and this can lead to
occasional confusion. For example, the ObjectID property is read-
only, but is not marked with this glyph.
Figure 3.10
Event
Function
Symbol
Figure 3.10 is the symbol for an event function. Events are
functions called by AutoCAD when something of interest happens
inside the system that directly affects the object. Events use a
standardized naming system allowing AutoCAD to keep track of
those applications that need to be notified when something occurs.
Events are found at several levels inside the AutoCAD object
system and can be used by VBA applications to seamlessly
integrate into the AutoCAD environment.
The object browser represents a very powerful development tool
for programmers who are learning a new system. As you begin to
explore other environments such as the Microsoft Office
productivity suite or an updated AutoCAD library, the object
browser becomes a valuable tool to learn what is inside the library.
Page 59
Chapter Four
The AutoCAD Object Model
In this chapter we will introduce and explore the AutoCAD object
model as seen from the perspective of VBA. The object model is
structured to allow a program to navigate easily through the entity
objects and groupings of data. Starting at the topmost object level,
this chapter examines the AutoCAD object system, looking at the
important objectsincluding their methods and propertiesalong the
way. The purpose of this chapter is to introduce the complete
AutoCAD object hierarchy in terms of how VBA sees it.
Figure 4.1
Exploring the object tree
We are now going to explore the AutoCAD object tree (refer to
figure 4.1) in the following order. Starting with the application
object, we will quickly move down to the active document object.
The next step is into the utility object, where a library of very
useful functions can be found. Also within the document objects
are the collection objects. The collection objects contain all the
tables for the drawing, such as the layer and block tables. Chapter 5
explores collections in more detail: this chapter exposes only the
basic operations of collections. Within collections are the entity
objects, and they are explored next in the chain. After looking at
some specific entity objects to learn how they are structured, the
next step is back to the root of the tree and on to the preference
object. This object contains the drawing setup and controls
information for the edit session.
Getting to the Application Object
We will start off with a confusing notion as to accessing the
information. The application object, although closer to the root of
the AutoCAD object tree, is accessed through the document object.
You might think, when working with an object tree structure, that
you would start at the root of the tree. But that is not the case in
VBA, and the reason makes sense when you step back and think
about it for a minute. Because VBA applications run inside
AutoCAD, with an open drawing, there is always a current drawing
available. That drawing or document object is known as
ThisDrawing to the VBA system. ThisDrawing is a library symbol
in VBA.
Page 62
To get to the application object, access the application property of the
document object. This may seem repetitive because the words application
and object are used twice, but they refer to two different things that
happen to have the same name. One way to think about this is that the
application property is just a pointer to another area in memory. The
application object is what is stored in that area of memory. Remember that
objects are containers of both data and procedures. The data elements are
called properties when discussed in terms of objects.
ThisDrawing.Application 'the application object
Most of the properties associated with the application object relate to the
Windows operating system and how the application appears on the screen.
Although you can adjust some of these settings, we recommend that they
be used for reference purposes only. Many of the properties are read-only
to keep the system integrity level high.
Property What it does
ActiveDocumentPoints to the document object that is the current open drawing.
Also pointed at with the name ThisDrawing in the VBA
environment.
Caption Displays the caption above the primary window of AutoCAD.
This is a read-only property that you cannot change.
Documents Access to a collection of documents currently available for access
in the AutoCAD application. The currently active document will
be included in this list. Your application can open more than one
drawing at a time and obtain information in one for another by
traversing the documents collection.
(table continued on next page)
Page 64
(table continued from previous page)
Property What it does
FullName FullName returns the complete path and file name where ACAD.EXE
Name is located. Path returns only the path value and is used most often
Path when seeking other files that are located relative to the AutoCAD
program files. Name provides just the drawing name without the
directory information. These properties are useful when seeking the
AutoCAD main program for other directory-related activities.
Height Gives the height and width of the main application window in pixels.
Width
Left Gives the distance from the left or top edge of the display to the left
Top or top edge of the application window in pixels.
LocaleID Identifies the current AutoCAD application when talking with other
Windows applications.
MenuBar Links to the menu objects for pop-up menus and the menu bar. Pop-
MenuGroups up menus are part of the menu groups. In a typical application, menu
groups are first loaded and then the individual menu pop-up is
accessed for insertion into the menu bar.
Preferences Provides access to the various drawing setup and access preferences.
There are several levels of preferences in the application object that
access all of the same data that is found in the Preferences tabbed
menu.
VBE Provides access to the VBAIDE object and its data values. The most
common use of this property is to see if a project (VBA program) is
currently loaded in the VBAIDE.
Version Gives the current AutoCAD version as a string. This is the same value
found in the ACADVER system variable of AutoCAD.
WindowStateControls whether or not the AutoCAD application object is visible on
the display. The settings of this property are acMin, acMax, and
acNorm, which stand for minimized, maximize, or normal.
Many of the properties just listed are object points or collections. The
application object is the root of the tree, so most of the connected data
elements are objects. You'll use the application object to get to other
objects inside the system that are of specific interest to a program.
Page 65
The other properties are used to communicate to other programs
inside Windows, including the operating system. These values are
accessed if you need to interface with another program that is
outside of the AutoCAD, such as a word processor or spreadsheet
software system.
The following is a VBA program example that shows how to
traverse the object tree to get at one of the Preferences settings. In
this case, we want to see if the screen menu is being displayed. If
so, we will send a quick message to the user asking why it is on.
(Using this property, you can turn the screen menu on and off,
although that would not be recommended except in cases where it
was absolutely required. The MenuBar and MenuGroups objects
provide a much better way of dynamically manipulating menus for
the operator's selection.)
Dim prefs As AcadPreferences
Set prefs = ThisDrawing.Application.Preferences
If prefs.Display.DisplayScreenMenu then
MsgBox ''Why do you have screen menus on?"
End if
Note that most program samples provided in this book are for VBA. If you want to
take advantage of the interface through ActiveX only with VB, the appropriate
object assignments must be made to link with the active document and application.
In the code segment above, the first step is to establish a link to the
AutoCAD documents collection. Variable DWGS is defined as an
instance of the documents collection and then set to the actual
value. This process of defining an object and setting it will be
repeated for the majority of linkages you will be building in VBA.
Given the documents collection object, the Item method is
employed to obtain the document. The name of the document is
used as the index into the collection. In the next chapter we will
explore collections in more detail. The code contains an error trap
to test if the Item method was successful. If it is not, an error will
result, and if the error trap is not enabled, the program will crash.
After clearing the error buffer, the Item method is run and the result
placed in the DWG variable. DWG had been dimensioned earlier
as a document object. An IF test immediately follows to see if the
error handler ran into something undesirable. If so, the drawing
requested was not in the open documents list. Otherwise, the active
property of the document is checked to see if this is the
Page 69
active document. If not, the activate method is used to make the
current document.
The document object is explained in greater detail in the following
section. Let's get back to the document collection object and how we
would use it. In a commercial or extensively implemented application,
a program needs to operate in both single and multiple document
modes. In order to learn this we must check the AutoCAD application
preference settings.
The following code segment shows how to check for multiple
document mode, then how to open a drawing in multiple document
mode under VBA control.
Dim APS As AcadPreferences
Set APS = ThisDrawing.Application.Preferences
If APS.System.SingleDocumentMode = False Then
Dim DWG As AcadDocument
Set DWG = ThisDrawing.Application.ActiveDocument
ThisDrawing.Application.Documents.Open (Nam)
ThisDrawing.Application.ActiveDocument = DWG
End If
There are many more properties associated with the document object;
these are just a few of the more commonly used ones. The document level
contains the methods and properties that apply to the entire document as
well as the collection objects that contain the details of the drawing.
Page 74
There are two functions involved here: the Activate and Deactivate events.
When the window is activated, the Activate event will be called. At this
time, we will save the current value of Timer, a VBA function that returns
the number of seconds since midnight. We will also save the drawing name
for future reference in the program. The drawing name is saved in the
variable Dwg_Name. The full name of the drawing is obtained from full
name property of the current drawing object.
The second function in this example is the Deactivate event. This function
is called when the current drawing window is no longer
Page 78
current. This event will occur when the user selects a different
drawing in the AutoCAD MDI environment. (Note that when you
are working in the VBAIDE, leaving AutoCAD to return to the
editor seems to trigger this event too.)
As just seen, event-based programming can offer some powerful
tools in the development of AutoCAD utilities to fill in the holes
missing for your specific application. Event-based programs tend
to be small so that they don't get too much in the way. In fact, the
use of a message box in an event that occurs frequently can really
slow down an applicationmaking them perfect for programmers to
use when debugging advanced projects!
Although the functions just listed are very handy when you need them, the
majority of application developers moving from AutoLISP to VBA will
find the following functions to be essential in developing interactive
programs.
Page 80
Function What it does
GetAngle User input function: prompts the operator for the input of an
angle value. The result is a real number containing the angle
input in radians.
GetCorner User input function: prompts the operator the input of a point
relative to another point. The second point is meant to be the
opposite corner of a bounding box. This function is used to
accept user input when rectangular selection windows are
involved.
GetDistance User input function: prompts the operator for the input of a
distance value. The result is a real number.
GetEntity User input function: prompts the operator to select an entity
object on the screen. Two different variables that are supplied as
parameters to the function will return with the entity object and
point variant where it was selected. A third parameter is the
optional prompt.
GetInput Retrieves the actual value input when optional input is enabled
through the use of the InitializeUserInput method.
GetInteger User input function: prompts the operator for an integer value.
The result is an integer.
GetKeyword User input function: prompts the operator for input from a set of
possible values defined in the InitializeUserInput method.
GetOrientation User input function: accepts an angle and returns the value as a
real number containing radians. The difference between
GetAngle and GetOrientation is that the latter does not pay any
attention to the ANGBASE system variable setting in AutoCAD
while the former does.
GetPoint User input function: accepts a point and returns a variant array.
GetReal User input function: prompts the operator for input of a real
number value. The result is a real number.
GetString User input function: prompts the operator for input of a string.
The result is a string.
InitializeUserInputFunction: prepares the user input system enabling features such
as keyword options and the setting of input flags. Input flag
options include settings for not accepting negative numbers,
zero values, points outside the limits, no null input, and the
acceptance of strings for traditionally non-string input functions.
Prompt Outputs a string to the command line of AutoCAD.
Page 81
To use the utility functions you must first connect to the utility object. You'll do
this through the document object. For example, to request a real number from the
operator using GetReal( ) the following statement could be used.
Dim MyVal as Double
MyVal = ThisDrawing.Utility.GetReal(''Enter a real number: ")
When the code above is run, the prompt "Enter a real number:" appears at the
AutoCAD command line and the user is given the option to enter a numeric
value.
The required format to call this routine may seem a bit odd to AutoLISP
programmers who are used to simply running the (getreal) subr to achieve the
same results. The difference is in the language environment. VBA typically uses
forms or dialog boxes for user input and for reporting information to the user.
AutoCAD VBA goes a step further by allowing interfaces to take place at the
command line and on the graphics screen. Consequently, the function GetReal( )
is not a normal VBA command that would also be found in other
implementations of Visual Basic. GetReal( ) is something that is supported only
by AutoCAD. You'll add this to VBA by adding an object with supporting
methods. As such, the object tree must be defined to direct VBA where the
function is residing in the system.
The With statement can be used to reduce the amount of coding involved in the
utility object. The following example demonstrates the With statement in use
with the utility object for a series of user input.
With ThisDrawing.Utility
Dim myVal As Double
myVal = .GetReal("Enter a real number")
Dim MyStr As String
MyStr = .GetString(1, "Enter a string")
Dim MyInt As Integer
MyInt = .GetInteger("Enter an integer")
End With
Page 82
The With statement comes from Visual BASIC and is used to reduce
the amount of typing required when working with the same object over
and over again. In the example code above, the With statement
establishes a reference to the Utility object of the current drawing.
Thereafter, any methods called from the Utility object will have to
include only the dot (.) at the front to be associated with the object
already linked. This practice can save a lot of typing when dealing with
a series of accesses into the same object.
You'll choose the Utility object for input in VBA depending on the type
of input you are requesting from the user. Sometimes a dialog box is
best, and sometimes it is not. Generally, when you are looking for point
or entity object related input, the Utility object functions are better than
having the user type in the object or point related data. A good example
would be a function that requests the operator to select two objects and
then supply a numeric value. There is no reason to display a dialog box
for just the numeric value and the selection of the objects (via a
command button). Such an interface simply gets in the way of the user,
and a series of simple Utility function calls are all that is needed.
If your application has a dialog box showing when the utility object
function is referenced, the user will possibly be confused. The dialog
box should go away for the time that the graphical input is taking place.
Dialog box objects (forms) have a method called Hide that can be used
to turn off the dialog box. When Hide is executed, the dialog box will
no longer be visible on the screen until the Show method is used.
The following code segment demonstrates the basic principle of hiding
the input form and getting point input. After the point input, the dialog
box is restored. In this example, the dialog box form is named
MyInput-Form. The X and Y values from the point selected will be
placed in two text box controls named PtX and PtY.
MyInputForm.Hide
Dim Pnt As Variant
Pnt = ThisDrawing.Utility.Getpoint(,''Select a point")
MyInputForm.PtX.Value = Pnt(0)
Page 83
MyInputForm.PtY.Value = Pnt(1)
MyInputForm.Show
Collections of Objects
A collection is defined as an ordered set of data items that can be
referenced as a singular unit. From an AutoLISP programmer's
perspective, a collection is a lot like a list. There are several
collections used in the AutoCAD automation interface. Although
collections do not have to contain all the same data types for each
member, the AutoCAD collections tend to be made up of object
references. For example, the blocks collection contains only block
objects, and the text styles collection contains only text style
objects. Another way to think of a collection is that it is an array of
references to other data containers.
Something many programmers just learning VBA and AutoCAD
find confusing at first is that many of the collections and objects
have the same name. The only difference is that collections are the
plural version of the name. Thus, the Blocks collection contains
Block object references. In the multiple document interface (MDI)
of AutoCAD 2000, the documents that are open are stored in the
Documents collection. Each member of the document collection is
a Document object reference. The concept of collections in Visual
Basic is important to understand since the majority of the
AutoCAD object model consists of collections.
All of the table items in AutoCAD are stored as collections of
objects. This includes the blocks, layers, linetypes, views, view
ports, dimension styles, registered application names, text styles,
and dictionaries. When you want to programmatically add a new
member to a collection, use the collection object method Add to
add the object to the set. The Add method has a single parameter
that is the name of the object to add.
For example, the following code snippet will add a new layer
named MyLayer to the current drawing. When adding MyLayer, it
will set the color to blue and the linetypes to ''DASHED". The
linetypes must be loaded before this code will function properly. If
not, the linetypes change will cause an error.
Page 84
Dim MyLayer As AcadLayer
Set MyLayer = ThisDrawing.Layers.Add(''MyLayer")
MyLayer.Color = acBlue
MyLayer.Linetype = "DASHED"
Note the use of the constant acBlue to designate the color value. A
complete list of constants can be found in the <globals> class
inside the Object Browser. In most cases, you can figure out what
the name of the constant will be once you learn the basic method
behind the naming scheme. To illustrate, the remaining color codes
are acRed, acYellow, acCyan, and so forth.
The uses of most of the named constants found in the object
browser are pretty obvious. But if you are not sure, select the
member item: at the bottom of the object browser, the value of the
constant will be shown along with a quick description of how it is
intended to be used. Press the F1 key for even more information
about the constant and how to use it.
Returning to the collectionscollections are used in AutoCAD for
more than just tables of common information. They are also used
when working with groups of entity objects such as those found in
the block references, Model Space, Paper Space, selection sets, and
entity groups. The same basic strategies are employed in these
cases as well. Entity objects are added to the Model Space
collection or Paper Space collection or to a block definition
collection. When an application wants to access an entity, it can do
so through the collection methods as applied to any of the entity
collections.
The following tables are available for all collections in the
AutoCAD VBA environment. There are not as many methods and
properties associated with collection objects as there are with the
objects we've looked at thus far. The reason is that collection
objects are a general object used to house other objects that will
have more properties and methods as you drill deeper. Think of
collections as a list containing reference pointers to the individual
items that in turn contain all the details about themselves.
Page 85
MethodWhat it does
Add Adds a new member to the collection of choice. Remove a member using
either the Delete or RemoveItems methods defined in the object members.
Delete Deletes a member from the collection. This is available only in the view
ports collection. In all other AutoCAD collections, the delete function is
found in the data objects. That is, to delete a layer, you first access the
specific layer object, then the delete( ) method applied to that object. This
will remove it from the collection.
Item Retrieves a member given its index value, which can be a number or a
string.
Entity Objects
Each entity in the AutoCAD database is an object and has a set of
methods and properties that are specific to the control of that object. There
are many methods and properties that share the same name and
accomplish the same feats from one entity to the next (this is
polymorphism at
Page 86
work). There are additional methods and properties that are unique
to each object.
As with any object in VBA, gaining access to the methods and
properties of an entity object requires that a pointer be established
to that particular item. A pointer to an entity object can be obtained
in a number of fashions as seen in the following quick examples.
When an entity is created through the appropriate add method, the
result returned is an entity object pointer. The first code example
creates a line object from (1,1,0) to (5,1,0), saving the entity object
pointer in the variable (Obj).
Dim Obj As AcadLine
Dim P1(0 To 2) As Double
Dim P2(0 To 2) As Double
P1(0) = 1#: P1(1) = 1#: P1(2) = 0#
P2(0) = 5#: P1(1) = 1#: P1(2) = 0#
Set Obj = ThisDrawing.ModelSpace.AddLine(P1, P2)
'Variable (Obj) now contains line object.
In the example above the first step is to define the data elements.
There are three variables defined. Obj is defined as an AutoCAD
Line object. The variables P1 and P2 are defined as arrays of
double precision numbers. After placing the initial values into the
P1 and P2 arrays, the AddLine method is used to create a new line
object in model space. Afterward, the variable Obj can be used to
access the line object just added to the drawing database.
Moving on to another way of obtaining entity objects, a selection
set is a collection of entity objects. The same is true of block
definitions as well as Model Space and PaperSpace. This means
that an entity object can be obtained using the Item method and the
index or offset into the collection where the object of interest can
be found. The following code shows how to obtain an entity object
from the ModelSpace collection. The first member is at offset 0.
Page 87
Dim Obj As Object
Set Obj = ThisDrawing.ModelSpace.Item(0)
Another way to obtain an entity object is to have the user show it on the
screen. The following code segment requests that the user ''Pick an object"
from the drawing. Note that as user activity increases, so must the error-
checking in the program code. If the user does not pick an object and the error
handler is not enabled, the program will crash. By enabling the error handler
as shown below, your program can respond as required when user input does
not follow what was expected.
Dim Uobj As Object
Dim Pnt(0 To 2) As Double
On Error Resume Next
ThisDrawing.Utility.GetEntity Uobj, Pnt, "Pick an object: "
If Err.Number <> 0 Then
Err.Clear
MsgBox "Entity not selected."
Else
'Entity object now in variable (Uobj).
End If
Geometry methods associated with entities are very powerful tools for
application developers. These are the same routines used inside AutoCAD
to solve the basic problems of CAD manipulation.
Method What it does
GetBoundingBoxReturns two points describing a rectangular boundary around the
object that is parallel to the world coordinate system.
IntersectWith Determines the points where the current object intersects with
another object.
TransformBy Applies a transformation matrix to the object to combine rotation,
axis shift, and scaling operations.
Many of the methods have parameters associated with them that you can
quickly learn while typing them into the VBAIDE. As a properly
dimensioned object is filled in with the IDE, the parameters of the
methods are prompted for as needed. Even more information is available
via the online help too. Programming has never been so programmer
friendly!
Page 89
Property What it's for
Color Entity object color value as an integer.
EntityName Same as the class name of the object. This value contains a
descriptive type name used to identify what kind of object is in use.
The result is stored in a string and can be used when accessing
custom objects. For most AutoCAD objects, the EntityType property
should be referenced instead.
EntityType Integer code value indicating what type of AutoCAD object this
reference represents. The integer code values have named constants
that can be used in VBA. The entity name (in English) has the
characters a and c appended at the front. For example, the constant
for a circle entity can be referenced in the VBA code as acCircle.
Handle The entity handle that can be used to interface with external
databases. Each entity object is assigned a handle that remains
unique from one drawing session to the next making this string value
perfect for indexing from other databases back into AutoCAD.
Layer The layer name for the object.
Linetype The linetypes name for the object.
LinetypeScaleScale factor for the linetypes.
ObjectID Like the handle, but a long integer instead of a string. Used when
communicating with ARX applications.
Visible Controls the visibility of the entity object. Setting an object to visible
means that the layer controls whether the operator can see it or not.
When set to not visible, the object does not appear on the display.
Each of the entity objects will have some methods and properties that are
unique to that particular entity object. Working with lines and other
simpler objects in VBA is pretty easy once you get a feel for the naming
Page 91
Figure 4.3
LWPOLYLINE example output
systems used in the AutoCAD object library. Remember that
because of polymorphism, most of the names are the same, which
makes learning the system that much easier.
The lightweight polyline object in Figure 4.3 is a 2D polyline. A
polyline is a series of connected coordinates with optional bulge
factors. Bulge factors describe arcs. You calculate them by taking
the included angle of the arc (in radians), dividing it by 4 and then
computing the tangent value. The resulting tangent value is set to a
negative value if the arc direction is clockwise. The result is called
the bulge factor and is found in both lightweight and regular
polylines. Although this mechanism may seem complicated, it is
elegant in that only a single number is needed, in addition to the
two points to define an arc. An arc of any size (up to, but not
including a full circle) can be stored in this manner. When
accessing a polyline object and obtaining the bulge factor, the
included angle is found by computing the arc tangent of the
absolute value of the bulge factor and multiplying that result by 4.
If the bulge factor is negative, the arc's direction is clockwise. If
the bulge factor is nonnegative, the arc is counterclockwise.
The next program segment shows how to create a lightweight
polyline object and apply bulges to it. The code will generate the
triangular-like shape shown in Figure 4.3. In the listing, note the
use of the colon character (:) to allow more than one logical line of
code to appear on the same physical line in the source file. This
sort of programming style can improve readability of the source
code by shortening the number of lines to read. More about
programming styles for source code layout will be covered in
Chapter 13.
Page 92
Dim Obj As AcadLWPolyline
Dim P1(0 To 7) As Double
P1(0) = 1#: P1(1) = 1# 'Vertex 0
P1(2) = 1#: P1(3) = 5# 'Vertex 1
P1(4) = 4#: P1(5) = 1# 'Vertex 2
P1(6) = 2.5: P1(7) = 0.75 'Vertex 3
Set Obj = ThisDrawing.ModelSpace.AddLightWeightPolyline(P1)
Obj.Closed = True
'add 35 degree included angle at 2nd to last segment
Obj.SetBulge 2, 0.15
'add 45 degree included angle at closing segment
Obj.SetBulge 3, 0.2
When creating a polyline or lightweight polyline object, the initial points are
supplied in a single array. For a lightweight polyline, this array must be a
multiple of 2 in size. Each two real numbers represent an X,Y coordinate.
Regular polyline objects use an array with a size that is a multiple of 3, as the
Z ordinate value is also included in the points.
Complex objects such as polylines require more than just the Add method to
fill in the object with the remaining details. The Add method simply gets the
object started. Additional properties are then set and other methods run to
complete the details for the complex entity object. The entity will be
generated on the screen whenever the Update( ) method is run for the object
(or a parent to the object).
In the case of a new object (like the above code), the object will also
regenerate whenever the AutoCAD graphics screen gets the focus. This is
important to remember when you are writing code and wondering why the
graphics don't show up as they are created. When that sort of interaction is
required of an application, the focus needs to be forced back to AutoCAD
each time you want the graphics displayed. This will greatly slow down a
function that is creating many entity objects, so we don't recommend it in the
majority of cases.
Page 93
Preferences
Now let's shift back to the Application object at the root and go to the
Preferences object. The Preferences object deals with system settings
that
Page 95
are not saved in a drawing but may be specific to an individual user or edit
session. Applications will reference the preference settings to find things
out about the system, such as whether multiple document mode is enabled
or the screen menu is turned on. Other information in the preferences
section includes file search directories, locations for fonts and other
support files, and display controls for the cursor and screen colors. Any
changes made to the preferences by a program should be undone when the
application finishes or is un-installed from the system.
The information in the Preference object can be saved to disk in the form
of a profile file. Normally a profile is attached to a particular user's
preference setting. Profile files are used when the same user is logged on
to AutoCAD but a different setup is required due to the application or
preferences of another operator. They are also a handy way to save the
existing profile for restoration when an application is about to make
changes to the settings.
The Preferences object is divided into multiple objects. When you run the
Preferences command inside AutoCAD, a dialog box will appear. Each
object inside the Preferences object corresponds to a tab in the Preferences
dialog box inside AutoCAD.
Property What it is
Drafting All of the auto snap features and onscreen tracking tools.
Display All data associated with the display system, colors, fonts, cursor, and so
forth.
Files All data associated with files and directory paths used by AutoCAD.
OpenSaveAdd data associated with the Open and Save operations of drawing files.
Output Plot control options including the default plotting device selection.
Profiles Settings for save and load profiles to disk.
Selection Settings related to object selection such as grip box size and so forth.
System Systems-related settings, such as the single document mode indicator.
User User configuration settings for keyboard style, units defaults, and content
explorer settings.
Page 96
In the majority of cases the preferences are accessed only to determine if a particular
feature has been enabled in AutoCAD or not. Users of AutoCAD R14 VBA will find that
the preferences object is very different from what is described above. AutoCAD 2000
organized the Preferences information in a better fashion than R14, which simply
contained a large set of parameters, all of which were associated with the base.
Example Sequence
The tables presented in this chapter are extensive: there appears to be a lot to learn in
order to become productive with the VBA interface. The reality is that programming in
VBA is very simple and with a little practice, it is easy to recall the proper objects and
associated methods and properties.
Let's turn to a couple of simple examples to illustrate how the object functions operate for
AutoCAD. For those readers new to reading VBA code, a single quote mark (') is used to
note that the remainder of the line is a comment. The pound sign (#) following a number
signifies a real number or one that contains a decimal point. The pound is used for whole
numbers only, such as 1#, 2#, and 3#.
'Draw a line from the point (2, 3, 0) to the point (5, 2, 1).
'Use BASIC Dim statement to declare variables.
Dim P1(0 to 2) as Double 'Define array of double precision.
Dim P2(0 to 2) as Double 'Array of numbers for point 2.
Dim Obj as AcadLine 'Define line object variable.
P1(0) = 2# : P1(1) = 3#: P1(2) = 0# 'Set the value of point 1.
P2(0) = 5#: P2(1) = 2#: P2(2) = 1# 'Set the value of point 2.
The line created in the code above was on the current layer and with the current linetypes
assignments for style and scale. To change these
Page 97
values to something new, we need to use the line object reference.
The next code example takes the existing line object reference in
the variable Obj and changes the layer to ''A2A". The layer name is
a property that can be set directly with the name of the layer
desired. The layer should already exist in the drawing for proper
execution of this assignment.
Obj.Layer = "A2A"
The next few lines declare the variables used for the entity
selection function.
Dim Uobj as Object
Dim Pnt as Variant
Whenever file or user input and output are involved, the error
handling system of VBA should be enabled and given some
consideration. In this case we are going to ask the user to select an
object. If successful, the variable object Err will have a null or 0
value. If not successful, the variable object Err will have a non-zero
value.
It is recommended to perform error trapping using the Resume
Next option instead of the Goto option for the On Error statement.
The reason is that your error recovery will be easier to program,
and it will be easier to determine exactly where things are going
wrong. When the Goto option is used, you will need to set an
additional variable indicating where the jump originated.
Page 98
On Error Resume Next
With the error handler ready, the program is now ready to ask the user for
some input. The next statement accomplishes this using the utility object
method called GetEntity. For AutoLISP programmers, this is the same as the
(ENTSEL) function.
ThisDrawing.Utility.GetEntity Uobj, Pnt, "Pick an object:"
When the Resume Next option is used, program flow continues after the
statement that caused the error. The next statement after a potentially
offending command should deal with the basic error condition check.
If Err <> 0 then
Err.Clear
MsgBox ''You didn't pick an object!"
Else
Uobj.Layer = "NEWLAYER"
End If
In the previous example we used the layer property since it is common to all
entities. When you want to make changes to specific entity types only, you
need to check the type of object to make sure it matches what you are
changing. For example, the following code will continue working with the
Uobj entity object. It will test to see if it is an arc and if so, the radius will be
changed to a value of 1.5 units.
If (Uobj.EntityType = acArc) Then
Uobj.Radius = 1.5
Uobj.Update
End If
Next we ask the operator to select another entity. Note that the error object must be
reinstated since we have already passed one instance of using it for input. Each time a
program is going to perform input from the user, it is a good idea to include an error trap.
On Error Resume Next
ThisDrawing.Utility.GetEntity Vobj, Pnt2, ''Select another object: "
If Err <> 0 Then
Err.Clear
MsgBox "You didn't pick an object!"
Else
At this point in the program we have two valid AutoCAD entity objects. The intersection
method can now be used to find any and all intersections between the two. IntersectWith
returns a variant array of real numbers where every three numbers represent a point. The
point information is in X, Y, Z order, however, there is no delineation between the points
themselves. If two intersecting points were found, the array would return with them stored
as (X1, Y1, Z1, X2, Y2, Z2). If there are no intersections found, the variant array is set to
empty.
The program code first sets up a variant array, then calls the Intersection method. The
return array is then tested to see what its value is. If it is not empty, the program proceeds
to report the intersection points found.
Dim Pnts as Variant
Pnts = Vobj.IntersectWith(Uobj, acExtendNone)
If VarType(Pnts) <> vbEmpty then
Page 100
The VBA LBound and UBound functions provide the required
information as to how many values can be found in the array. These
values are used to define the limits to be used in a For-Next loop that
will go through each value in the list.
Note how the point values themselves are accessed from the array.
The X value is found at position (I) while the Y value is found at
(I+1) and Z at (I+2). In order to advance a whole point at a time in
the For-Next loop, the loop counter variable (I) is incremented by
two during each pass of the loop. It will automatically be
incremented by a value of 1 because of the For-Next loop.
Dim I as Integer
For I = LBound(Pnts) to UBound(Pnts)
S$ = Pnts(I) & ", " & Pnts(I+1) & ", " & Pnts(I+2)
MsgBox "Found intersection at " & S$
I = I + 2
Next I
If the resulting Pnts array was empty, the following code is executed.
The user is told via a message box that there are no intersections
between the two objects. The second End If statement closes the
earlier test to see if the second object was selected properly.
Else
MsgBox "No intersections found"
End If
End If
It does not take long to get used to working in the VBA environment.
In fact, with the programming tools native in the VBA IDE, you will
spend less time learning the objects than might be expected. This has
to do with the automatic typing feature that accompanies all objects
known to the system. With the easy access of the online help facility,
you can quickly find the object details in question. Perhaps the only
difficulty with the online help system is that the VBA files have
some information,
Page 101
and the AutoCAD help files have more. For example, if you are
searching the AutoCAD help files for ActiveX, you will find no
direct references to the Err object. That information is found in the
VBA specific help files.
Page 102
Chapter Five
Working with Entity Collection Objects
A collection object is a set of things all collected into one object. A
group of entity objects can be considered a collection as can a list
of text styles. This chapter explores the basic concepts behind
collections and how to work with them. We will give specific
attention to entity collections.
The Collection Object
A collection object provides a mechanism by which several items,
data or other objects, can be linked together and referenced as a
singular item. The easiest way to view a collection is to think of a
selection or pick set. A selection set results when you are picking
entity objects such as in the COPY or MOVE commands. A
selection set can have any number of entity objects in it, and these
objects can be of any typeranging from lines to block
insertionsreferencing even more objects. The collection of objects
can then be referenced as a single item. Say the AutoCAD operator
wants to both move and rotate a set of objects. For the first
command, he or she needs to select the objects to be manipulated
but in the second command, he or she can use the ''previous"
selection set. Obviously, this reduces the amount of work since the
operator can reference the entire collection of objects as a single
item.
Page 103
In Visual BASIC, a collection object is like an array or a list. The
main difference is that every element does not have to be of the
same data type. In some applications that involve collections, the
data type may be standardized for each object. This situation will
occur when interfacing to programs such as AutoCAD because
only through the standardization of the information is data
transferred without any problems. An example of this in AutoCAD
is the layer table that is treated as a collection of layer objects.
Generally, there are three methods associated with collections. The
methods provide the basic functions needed to add new items,
remove existing items, and access the items in the collection.
AutoCAD collections are not general-purpose collections but are
collection-like objects. You can think of them as being created
from the collection object, but with their own special traits. As a
result, special collections in AutoCAD such as selection sets tend
to have more methods specific to the type of collection in question.
Selection Sets Collection
In the AutoCAD drawing object model there is a collection called
the Selection Sets Collection. This collection is a storage place for
all of the selection sets in the drawing. When you want to create or
access a selection set, it will be from this collection. Selection sets
are referenced by name inside the collection. The name can be
anything that fits your application; we recommend that you use the
same naming structure as applied to the variable names to avoid
conflicts with existing collections. Selection sets collection
member names are strings.
As a drawing edit session is started, the selection sets collection
object is created and is ready for use. There can be any number of
selection set objects within the selection sets collection. Each
selection set object is a special type of collection in that it contains
none or many entity object references. So the hierarchy starts from
the current drawing object and then goes to the selection sets object
(figure 5.1). There can be multiple
Page 104
Figure 5.1
Selection Set Collection Hierarchy
selection sets defined as members of the selection sets object. Each
selection set can then have multiple entity objects as members.
In order to use a selection set in a program, it must first be created.
Adding a new member to the selection sets collection creates a new
selection set as in the following code segment.
Dim S1 as AcadSelectionSet
Set S1 = thisDrawing.SelectionSets.Add(''S1")
There are numerous methods in this set that create objects using only partial information.
The object's specific methods and properties are then used to set any of the remaining data
to the value needed by the application. The following code section demonstrates this simple
principle at work when you're creating text objects. The program will create a new text
object with a string value of ''This is a test", height of 0.2 units, rotation of 90 degrees, an
oblique angle of 22.5 degrees, and an insertion point at (5,10).
Dim MyObj as AcadText
Dim IP(0 to 2) as Double
IP(0) = 5#: IP(1) = 10#: IP(2) = 0.0
Set MyObj = ThisDrawing.ModelSpace.AddText("This is a test", IP, 0.2)
' Text object is created, and can now be updated to what we need
MyObj.Rotation = D2R(90#) 'D2R defined below..
MyObj.ObliqueAngle = D2R(22.5#) 'Angles must be in radians
' The text object now exists in the drawing as desired.
Page 117
' The function D2R does not exist in the VBA library,
' you must create it as follows.
Function D2R (D as Double) as Double
D2R = D * 3.141592653590 / 180#
End Function
For the more complex entities, your programs will have to update the
properties after the initial object has been created. Further examples
include bulge factors in polylines; Mtext, Text, and Attrib properties;
and partial ellipses. Use the online help when programming these
objects to find the name of the appropriate property or method.
Filtering the Selection Set
When selecting entity objects in an application, you may want to work
with just a specific subset of the entity objects in the drawing.
Selection sets are subsets of the entity objects in the drawing. When
building a selection set, you may want to select only certain types of
objects or objects that share specific property traits. An example
would be a program that counts how many bolt holes are in a design.
Such a program would search for just circles. You can use a filter
when you're building a selection set based on such criteria.
A filter is a set of properties that the entity objects need to match in
order to be included in the selection set. The properties can be specific
object types as well as ranges of valuessuch as selecting all circles
with radii between 1 and 2 drawing units.
In VBA, a filter is constructed as two arrays of variants. The two
arrays contain related information that consists of group codes and
data values. The first array contains group codes only. Group codes
are integer values that indicate the type of data being referenced. The
data itself resides in the other array. The index value links the two
arrays. The first value in the group codes array corresponds with the
first value in the data array.
Group codes that are used the most frequently in applications
programming are listed in the following table. There are lots more. A
com-
Page 118
plete list is documented in the DXF section of the AutoCAD reference
information. The group codes listed here are those most frequently used in
an application.
Group code Contents
0 2042015b45d2b5416108e486be44e8bc.gif Object type string such as LINE,
ARC, or CIRCLE
1 2042015b45d2b5416108e486be44e8bc.gif String value in Text, Mtext
2 2042015b45d2b5416108e486be44e8bc.gif Object name string needed only
for Block names and, Table names
8 2042015b45d2b5416108e486be44e8bc.gif Layer name string
10 2042015b45d2b5416108e486be44e8bc.gif Primary point
2042015b45d2b5416108e486be44e8bc. Secondary points for text
11 . . .
gif alignments, line endpoints, traces,
and so forth
40 2042015b45d2b5416108e486be44e8bc.gif Arc and circle radius
62 2042015b45d2b5416108e486be44e8bc.gif Color number (integer)
67 2042015b45d2b5416108e486be44e8bc.gif Model/paper space integer flag. A
value of 1 indicates the object is in
paper space.
-4 2042015b45d2b5416108e486be44e8bc.gif Grouping operator string or
relational test
The second array contains the data elements associated with the group
codes. The data elements will be of different data types that correspond to
the integer codes. A group code 40 will have an associated real number
while a group code 2 will have a string.
These two arrays must then be assigned to variant variables that are
passed to the selection set function. Beginning VBA programmers may
find that the variant passing system is somewhat awkward; however, it is
a common practice when sending information from BASIC to other
programming environments. The reason is that the variant data type is a
container holding a description of the data type and a pointer to where the
data is stored. Instead of sending a complete array through the parameter
list, a pointer is sent to its location in the computer. Another reason for
using variants is that inside the computer, arrays are stored differently in
the two languages. A variant data structure provides a link-
Page 119
age mechanism that tells the C++ component all about the array
and helps to set up the conversions required.
An example of using a filtered selection, the following code
segment builds a selection set from the entire drawing that will
contain only CIRCLE entity objects with a radius of 5 drawing
units.
Dim Ftyp(1) As Integer
Dim Fval(1) As Variant
Dim Filter1, Filter2 As Variant
Ftyp(0) = 0: Fval(0) = ''CIRCLE"
Ftyp(1) = 40: Fval(1) = 5#
Dim S1 As AcadSelectionSet.
Set S1 = ThisDrawing.SelectionSets.Add("S1")
Filter1 = Ftyp: Filter2 = Fval
S1.Select acSelectionSetAll, , , Filter1, Filter2
The arrays must be dimensioned to the proper size for the filters. If
you are using only two filter items, the array length should be
exactly 2, meaning that the dimension statement should call out a
dimension size that is 1 less than the number of elements that will
appear in the array. VBA arrays start indexing at a value of 0,
hence the need to subtract 1 from the dimensioned size. There are
two ways to dimension these arrays, and it is a matter of style as to
which you will use in your programming. You can specify the
lower and upper bounds of the array or simply specify the upper
bound and let the 0 value default. Both approaches work fine, but
we happen to find the version that declares the range to be more
readable. Programmers who work in multiple languages where
array declarations are not based on bound definitions will find the
range more readable as the other looks like an array that is defined
too small.
Dim AnArray(0 to 1) as Variant
The filter in the code above uses the (4) group code. When a
comparison test is used in the filter, it is applied to the values that
follow. In this case, the radius value is used for the relational test.
Numeric relational tests are as follows. These tests are typically
applied against real numbers found in the entity object properties.
They can also be applied for points.
Page 121
= Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= or Not equal to
/=
* Always-true returns true every time. Used
when testing point values.
When your program is testing point values, the point value tests are
combined with commas separating them. You can test the X, Y, Z
components of the point independently of each other. That means
that you can have the filter look for points that have an X
component greater than a value and have a Y component that is
less than another value. If the Z component is not supplied, it is
assumed to contain an always-true test associated with it.
The following example program tests for objects that are located in
the first quadrant (that is, they have X and Y values that are greater
than or equal to 0). This version tests the primary point value of all
objects in the drawing. The primary point value is group code 10.
The test to be used is written as ''>=,>=,*" which means that we
want X and Y values that are greater than the test value and that we
don't care what the Z value is.
Dim Pnt(0 to 2) As Double
Dim Ftyp(1) As Integer: Dim Fval(1) As Variant
Dim Filter1, Filter2 As Variant
Pnt(0) = 0#: Pnt(1) = 0#: Pnt(2) = 0#
Ftyp(0) = -4: Fval(0) = ">=,>=,*"
Ftyp(1) = 10: Fval(1) = Pnt
Filter1 = Ftyp: Filter2 = Fval
Dim S1 As AcadSelectionSet
Set S1 = ThisDrawing.SelectionSets.Add("S1")
S1.Select acSelectionSetAll, , , Filter1, Filter2
Page 122
In the code segment above, a point (Pnt) is defined as an array of double
precision numbers. Then that array is set into the variant array (Fval), which in
turn is set into the variant variable (Filter2) for passing into the Select function
that builds a new selection set. At first glance, this seems like a lot of extra
work to have to do in order to get what you want. That is one of the trade-offs
in object-oriented programming when you're working with more complex
objects; you can either have a lot of methods or you can have a lot of options
available in a smaller set of methods. The Select function is one of those that
have a lot of options. The empty parameters in the examples presented thus far
are there in case you want to send point constraints as required when using
window-based selections.
The following example looks for small arc objects (radius less than 1.0) in the
drawing. It uses a window-based selection method and supplies two points
along with a filter. The window is from (0, 0, 0) to (15, 15, 0). The point
arguments are supplied as arrays of numbers.
Dim Pnt1(0 to 2) As Double
Dim Pnt2(0 to 2) As Double
Dim Ftyp1(2) As Integer: Dim Fvar1(2) As Variant
Dim Filter1, Filter2 As Variant
Pnt1(0) = 0#: Pnt1(1) = 0#: Pnt1(2) = 0#
Pnt2(0) = 15#: Pnt2(1) = 15#: Pnt2(2) = 0#
Ftyp1(0) = 0: Fvar1(0) = ''ARC"
Ftyp1(1) = -4: Fvar1(1) = "<"
Ftyp1(2) = 40: Fvar1(2) = 1#
Filter1 = Ftyp1: Filter2 = Fvar1
Dim S1 As AcadSelectionSet
Set S1 = ThisDrawing.SelectionSets.Add("S1")
S1.Select acSelectionSetWindow, Pnt1, Pnt2, Filter1, Filter2
The value you're testing must be of a data type that makes sense for the test.
Numbers can be tested greater or less than relationships, but strings cannot.
After all, one string cannot be greater than another string
Page 123
in a form that makes sense for such a test. Wild cards can be used for
string testing in a filter instead.
String Tests in Filters
Wild cards are characters that symbolize a test. The most common wild
card used is the asterisk (*). We use an asterisk when we mean ''anything."
The other wild card characters used in testing strings are defined in the
table that follows.
* Anything
? Any single character
# Any single digit
@ Any single character
. Any non-alphanumeric character (such as a dash)
' Escape character, use the next character as is (as in '*to look for
asterisk)
[] Match any of the characters inside the brackets
[~]Match when the characters inside are not found
~ First character in search pattern means "NOT". This causes a match
when the pattern is not matched.
' Separate more than pattern such as in LYR*, LAYER* to look for a
match starting with either LYR or LAYER.
You do not need a relational test group code (-4) when you're doing string
pattern matches. As an example, the following code builds a selection set
of objects that are on any layer starting with the characters AA or AB. In
this example, the variables Filter1, Filter2, and S1 are already
dimensioned to the proper data types. They should match the previous
examples in this chapter for the same variable names.
Dim Ft(0) As Integer: Dim Fv(0) As Variant
Ft(0) = 8: Fv(0) = "AA*, AB*"
Filter1 = Ft: Filter2 = Fv
Dim S1 As AcadSelectionSet
Set S1 = ThisDrawing.SelectionSets.Add("S1")
S1.Select acSelectionSetAll, , , Filter1, Filter2
Page 124
The example just shown tests the entity objects for two different
layer name groups, those that start with AA and those that start
with AB. The two tests are combined into a single test separated by
the comma character. This forms an implicit OR test, which means
that a true result will come back if either or both of the tests turn
out true. When you consider an entire filter, each of the individual
matches are combined together in the form of an AND test. An
AND test is true only when all of the sub-tests are true. In some of
the previous examples we tested for multiple items such as circles
with a specific radius value. Because the AND test combines all the
parts of the filter, we do not get objects that match only one or two
of the tests. That means we cannot build a filter that would look for
both circle and arc objects since one or the other would cause the
selection to skip an entity. For example, if the object is an arc then
the circle test will fail.
You can accomplish testing by just laying out the testing sequence
in a logical manner. The first step is to attempt to state the test in
the terms supplied. Suppose our application was looking for either
CIRCLE entities with a radius greater than 0.25 but less than 0.75
as well as ARC entities on layer "PART" with a radius less than 1.
In this case, we would set up the filter list to contain an OR test
looking for either entity type; within each OR test there are
additional tests. For the circle, the radius must be between the
values specified, and for the arc it must be on a specific layer and
with a radius less than 1. The diagram that follows shows the tests
combined by boxes. There are two AND boxes and one OR box.
Now let's look at the code required to create this filter. The
Figure 5.2
Combined Logic in a Filter
Page 126
arrays are much longer than the ones shown thus far. When your program is using
filters containing logical combination tests, the number of elements in the array will
increase due to the (-4) group code additions.
Dim Ftyp14(14) As Integer
Dim Fvar14(14) As Variant
Ftyp14(0) = -4: Fvar14(0) = ''<OR" 'Start the overall OR test
Ftyp14(1) = -4: Fvar14(1) = "<AND" 'Start the AND test for ARC
Ftyp14(2) = 0: Fvar14(2) = "ARC"
Ftyp14(3) = 8: Fvar14(3) = "PART"
Ftyp14(4) = -4: Fvar14(4) = "<="
Ftyp14(5) = 40: Fvar14(5) = 1#
Ftyp14(6) = -4: Fvar14(6) = "AND>" 'End the AND test for ARC
Ftyp14(7) = -4: Fvar14(7) = "<AND" 'Start the AND test for CIRCLE
Ftyp14(8) = 0: Fvar14(8) = "CIRCLE"
Ftyp14(9) = -4: Fvar14(9) = ">="
Ftyp14(10) = 40: Fvar14(10) = 0.25
Ftyp14(11) = -4: Fvar14(11) = "<="
Ftyp14(12) = 40: Fvar14(12) = 0.75
Ftyp14(13) = -4: Fvar14(13) = "AND>" 'End the AND test for CIRCLE
Ftyp14(14) = -4: Fvar14(14) = "OR>" 'End the overall OR test
Virtually any selection criteria can be defined using the combination tests. Here are
some more examples presented in a tabular form for readability. The values would be
assigned as presented to the two arrays.
The first example shows a filter to test for objects that are not circles and arcs and that
are on layer "ABC". This filter uses the fact that there is an implicit AND by starting
with the layer test. The next part then informs the filter processing system that we are
NOT interested in circles OR arcs.
Page 127
Group code Value
8 2042015b45d2b5416108e486be44e8bc.gif ''ABC"
-4 2042015b45d2b5416108e486be44e8bc.gif "<NOT"
-4 2042015b45d2b5416108e486be44e8bc.gif "<OR"
0 2042015b45d2b5416108e486be44e8bc.gif "CIRCLE"
0 2042015b45d2b5416108e486be44e8bc.gif "ARC"
-4 2042015b45d2b5416108e486be44e8bc.gif "OR>
-4 2042015b45d2b5416108e486be44e8bc.gif "NOT>
As another example, here is a filter to test for text objects that are
not on either layer TITLE or BORDER. Text objects include the
Text, Attrib, and Mtext entity objects. An OR test is required to test
for each possible entity object. The portion of the filter that tests
whether or not the objects are not on a layer is accomplished with a
pair of (8) group codes containing the layer names preceded by the
tilde (~) character. When that character is present, the test is
reversed. Instead of being an equal test, it is a not-equal test. The
two individual tests are required and cannot be combined into a
single test with the command as in ~BORDER, ~TITLE since the
comma acts an OR combination which would always return true in
this case. After all, if an object is on layer BORDER, it is not on
layer TITLE, and the OR combination would result in a true result.
An AND combination is required, and that is why two separate (8)
group codes are involved.
Group code Value
-4 2042015b45d2b5416108e486be44e8bc.gif "<OR"
0 2042015b45d2b5416108e486be44e8bc.gif "TEXT"
0 2042015b45d2b5416108e486be44e8bc.gif "ATTRIB"
0 2042015b45d2b5416108e486be44e8bc.gif "MTEXT"
-4 2042015b45d2b5416108e486be44e8bc.gif "OR>
8 2042015b45d2b5416108e486be44e8bc.gif ~TITLE
8 2042015b45d2b5416108e486be44e8bc.gif ~BORDER
Page 128
Chapter Six
Drawing Tables
This chapter explores the tables in AutoCAD. AutoCAD tables
include layers, linetypes, blocks, dictionaries, views, view ports,
dimension styles, text styles, groups, registered applications,
layouts, and plot configurations. Tables are stored as collections of
specific objects and follow most of the standard methods of
collections with some notable exceptions. In this chapter we will
discuss how to manipulate tables in general, then we'll focus on
some of the specific table details. We finish the chapter with an in-
depth study of the blocks table and an explanation of how to
manipulate blocks in VBA.
There are more properties for the group object, but they are not of any real use to most
applications. The primary operations are adding and removing objects from the group. The
following code example creates a new group from a selection set of objects. The selection set
and group name are supplied as parameters to the function. The value returned from the
function is the new group object with the entities from the selection set as members. If the
group already exists, the selection set objects are added to any other entity objects that are
already in the group. If the group does not exist, it is created.
Function SS_2_Group(SS As AcadSelectionSet, Nm As String) As AcadGroup
Err.Clear
On Error Resume Next
Set SS_2_Group = ThisDrawing.Groups.Item(Nm)
If Err.Number <> 0 Then
Err.Clear
Set SS_2_Group = ThisDrawing.Groups.Add(Nm)
End If
Dim I, J As Integer
J = SS.Count - 1
ReDim Items(0 to J) As Object
For I = 0 To SS.Count - 1
Set Items(I) = SS.Item(I)
Next I
SS_2_Group.AppendItems (Items)
End Function
Note that the items are defined as generic objects, then assigned to the individual entity
objects in the selection set. The array is then passed to the AppendItems( ) method to add
these objects to the group.
Page 138
Note also the use of the Err object when you're accessing the group
collection. If the group name is not a member of the groups
collection, an error will result when attempting to locate it via the
Item( ) method. An error code that is non-zero means there was a
problem accessing the name in the collection, thus the program
proceeds into adding a new member to the collection. The result of
creating a new member is the same as accessing an existing
member with Item( ): an object reference is created to the group.
Perhaps the most confusing aspect of using groups is that the Item(
) method is used in two different places. It is used when accessing
the groups collection to obtain a group, and it is used again inside
the group to access the individual entity objects that are members
of the group.
The color number and linetype name must also be valid, or an error will result. In
the previous example the error system is used to trap this situation. Alternatives
would be to test the range or see if the linetype specified is in the linetype table
before making the assignment.
Page 142
Regardless, it should be obvious to the new VBA programmer by
now that the error handling system in VBA can be extremely useful
when manipulating AutoCAD objects. This can be crucial when
you're building a library of functions that you intend to use over
and over again in future projects.
PropertyWhat it is
Name UCS object name for referencing purposes. This is the same name used by
the Item( ) method in the collection to get to the UCS object.
Origin An array with three elements representing the origin of the UCS object in
the WCS. When obtained from the object, it is returned as a variant.
Xvector An array with three elements representing the direction in the WCS of the
UCS object's X-axis. Returned as a variant when accessed.
Yvector An array with three elements representing the direction in the WCS of the
UCS object's Y-axis. Returned as a variant when accessed.
UCS objects can be very useful when creating objects in 3D space. The
reason is that new objects are always drawn in the UCS and have an OCS
applied to them. When you're creating an object in the World Coordinate
System (WCS) that is to be placed relative to a UCS, you can use the
TransformBy( ) method to correct the entity object by applying an OCS.
The transformation method uses a transformation matrix which you can
create by defining a 4-by-4 array of double precision numbers or by
obtaining one from the GetUCSMatrix( ) method of the UCS object to be
used.
Page 147
The following code example shows how to apply the transformation matrix from a
UCS object. The example uses a coordinate system previously created and saved
with the name ''MY_UCS". A circle is defined in the WCS, then rotated relative to
the stored UCS. The center point of the circle is reset after the transformation so
that the selected point remains the center point of the object. The transformation
will most likely change the circle object center point value thus making this
operation a requirement.
' Current UCS is expected to the World Coordinate System (WCS)
Dim UCS_Mine As AcadUCS 'get UCS info from table
Set UCS_Mine = ThisDrawing.UserCoordinateSystems.Item("MY_UCS")
Dim p1 As Variant 'user input of a point
p1 = ThisDrawing.Utility.GetPoint(, "Center point")
Dim Obj As AcadCircle 'draw the circle, radius is one
Set Obj = ThisDrawing.ModelSpace.AddCircle(p1, 1#)
Dim TrnsMtx As Variant 'get the transformation matrix
TrnsMtx = UCS_Mine.GetUCSMatrix
Obj.TransformBy (TrnsMtx) 'apply transformation
Obj.Center = p1 'reset center point to original
Obj.Update 'regenerate the object on the screen
If you modify an existing UCS, you must update the document object after all
modifications are completed. To update the current UCS, simply set the active UCS
to be the UCS name once again. Any changes made to the UCS object will now be
applied.
Properties What it is
Center The location of the viewer's eye relative to the view port.
Direction A vector describing the direction from the center point to the
observer. The vector is a line from which the observer is looking
back toward the origin (0,0,0) of the view port.
GridOn Boolean indicating whether or not the grid is being displayed.
Height The height of the view port along the Y-axis.
LowerLeftCornerThe coordinates of the lower left corner of the view port.
Name Name of the view port.
The upper and lower corners of a view port are expressed in ratios. A
value of 1 indicates that it is at the maximum upper level, while a 0 value
is used to indicate the lowest possible level. Thus a corner at (0.5,1.0) is
halfway across the view port in the X-axis and at the top in the Y-axis.
You'll use these values to determine which window to use when you have
saved the view port using the VPORTS command in AutoCAD.
Only one view port is considered the active view port, and that one is
defined in the drawing property ActiveViewport. The active view port is
where drawing edits take place from the operator's perspective.
Programmers use the ActiveViewport property to cause changes made to
the view port properties to be reflected in the display. When you are
changing view port properties, nothing will change on the display until the
view port is established as the active view port. Even if the view port is
already the active view port in the drawing, it must be re-established as
such before any of the changes made will be visible.
Page 152
Using paper space view ports is not difficult. You create a new paper space view port
object through the AddPViewport( ) method found in the paper space object. A new
view port requires three parameters: the center point and the size of the view port along
both the X-axis and Y-axis. The following code creates a new paper space view port
centered at (7,9) that is 12 units wide and 16 units high.
'switch to paper space
ThisDrawing.ActiveSpace = acPaperSpace
Dim PT(0 To 2) As Double
PT(0) = 7#: PT(1) = 9#: PT(2) = 0#
Dim NVP As AcadPViewport 'create new paper space view port object
Set NVP = ThisDrawing.PaperSpace.AddPViewport(PT, 6#, 8#)
PT(0) = 1#: PT(1) = 1#: PT(2) = 1#
NVP.Direction = PT 'point is (1,1,1) for isometric view
NVP.Display True 'force display update
ThisDrawing.MSpace = True ' switch to model space
ThisDrawing.ActivePViewport = NVP 'set the active paper space port
ZoomAll
ThisDrawing.MSpace = False ' switch back to paper space
ZoomAll
Page 154
Most applications that use paper space also make use of view ports.
A couple of basic rules that must be followed when programming
view ports in paper space:
Changes can be applied to only view ports when they are not the
active paper space view port and have been turned off. What this
means is that you can make adjustments to the view port properties
only when first creating it or by setting another view port as active
while the changes are applied. The Display( ) method must be used
to turn the view port off if it is currently on.
The view port must be turned on via the Display( ) method before
it can be named as the active paper space view port for the
drawing.
The model space edit features cannot be activated for a view port
unless the display mode has been turned on via the Display( )
method for that view port.
The Blocks Collection
The block table for a drawing is stored in the blocks collection.
Each member of the blocks collection is a block object. Block
objects are collections of entity objects just like paper space and
model space. Block objects contain the same methods as found in
the model and paper space objects for adding new objects to the
block definition. The previous chapter lists the methods and
properties that exist for entity collections such as blocks, model
space, and paper space. A block is used in a drawing when
referenced by a BlockRef object.
Blocks save storage in a drawing and represent the easiest form of
programming available to the AutoCAD operator. Blocks are
sequences of entity objects that can be used over and over again.
Simple transformations can be applied to blocks such as scaling
and rotation, making them valuable tools for experienced
AutoCAD operators.
From a programmer's perspective, blocks are complex objects, but
that's only because there are multiple, variable steps involved in the
cre-
Page 155
ation of the blocks. They are really quite simple to create and manipulate in
a programming environment such as VBA.
Any number of entity objects can be added to a block definition. You can
also add to a block definition well after it has been defined. In fact, you can
edit the block programmatically to alter the contents at any time. All you
have to do is open the existing block object using the Item( ) method of the
blocks collection.
The following example opens an existing block for access by VBA. The
block object (stored in variable B1) is set with the result of the Item( )
access. Note the use of the Error object to trap the potential situation that
the block does not exist.
Dim B1 As AcadBlock
On Error Resume Next
Set B1 = ThisDrawing.Blocks.Item(''MYBLOCK")
If Err.Number <> 0 Then
'The block does not exist in the drawing
Else
'The block exists, B1 is a collection of entity objects
End If
In most applications involving blocks, the programs work with block references or insertions
into the drawing. The Name properties of the BlockRef objects (block reference) will return
the name of a particular instance of the block object. The name can then be used to get the
block
Page 159
definition from the blocks collection, and from there the block can be
accessed directly.
The following code example demonstrates how to access a block from a
selection on the screen. The operator is asked to pick an object using the
GetPoint( ) utility function. This function returns a variant that can be used
to define a selection set built using the SelectAtPoint( ) method. One item
of note in the code is that after declaring our selection set, we clear it just to
make sure no one else has used the same name. That includes us testing the
code.
Dim PP1, PP2 As Variant
Dim PP0 As Variant
PP0 = ThisDrawing.Utility.GetPoint(, ''Pick an object: ")
Dim S1 As AcadSelectionSet
On Error Resume Next
Set S1 = ThisDrawing.SelectionSets.Add("SS1")
If Err.Number <> 0 Then
Set S1 = ThisDrawing.SelectionSets.Item("SS1")
End If
S1.Clear
S1.SelectAtPoint (PP0) Dim E1 As Object
Set E1 = S1.Item(0)
If E1.EntityType = acBlockReference Then
MsgBox "Found a block reference! - " & E1.Name
Call Block_Extreme(E1.Name, PP1, PP2)
' . . .
The primitive example just shown tests the entity type property to see if it
matches a particular entities number. Specifically, the AutoCAD constant
acBlockReference was used to test for a block insert. This constant, along
with others, can be used when accessing entities under operator
Page 160
control to test exactly what was selected. It is up to your program to perform
adequate error checking when operator input is involved, as the operator will not
always input or select something you want.
AutoLISP programmers who are learning VBA must learn to think in terms of
what the objects can do for the application. There are different tools available for
solving some problems that in the past have taken a great deal of time.
The next example code section expands on the previous example by using the
selected entity object to build a selection set of objects that potentially intersect
with the block. Using the IntersectWith( ) method from the entity objects, the
application looks for intersection points, and when they are found, they are noted
as point objects. The PDMODE system variable can be changed to see the points
created with this example after it is run.
Dim PP0, IPs, PP1, PP2 As Variant
Dim S1 As AcadSelectionSet
Dim E1, E2, E1S(0) As Object
Dim IP(2) As Double
Dim I, J, K As Integer
'
PP0 = ThisDrawing.Utility.GetPoint(, ''Pick a block insert: ")
On Error Resume Next
Set S1 = ThisDrawing.SelectionSets.Add("SS1")
If Error.Number <> 0 Then
Set S1 = ThisDrawing.SelectionSets.Item("SS1")
End If
S1.Clear
S1.SelectAtPoint (PP0)
Set E1 = S1.Item(0)
'only work with block reference (insert) objects
If E1.EntityType = acBlockReference Then
Page 161
'Get limits of inserted block
E1.GetBoundingBox PP1, PP2
'Build selection set of objects crossing the bounding box
S1.Clear
S1.Select acSelectionSetCrossing, PP1, PP2
'Remove block reference from selection set
Set E1S(0) = E1
S1.RemoveItems E1S
'Loop through selection set
J = S1.Count - 1
For I = 0 To J
'Compute the intersection points
Set E2 = S1.Item(I)
IPs = E1.IntersectWith(E2, acExtendNone)
'Go through the intersections found
For K = LBound(IPs) To UBound(IPs)
IP(0) = IPs(K): IP(1) = IPs(K + 1): IP(2) = IPs(K + 2)
K = K + 2
'draw a point at the intersection location.
ThisDrawing.ModelSpace.AddPoint IP
Next K
Next I
Else
MsgBox ''You selected the wrong type of entity!"
End If
A block can contain any type of entity, including other block references. The only
thing a block definition cannot contain is a block reference back to itself, which
will cause a problem, as the block can never finish drawing itself. Most entity
objects behave as normal when inside a block, but there is one important
exception: attribute objects.
Page 162
The object(s) that are returned when you use the GetAttributes( ) method are
attribute references. Attribute references are different from attribute definitions. An
attribute definition contains the default value, prompt string, tag name, and all the
default generation parameters of the attribute text. An attribute reference, on the
other hand, contains an instance of the attribute with the text value, location, sizing,
and tag.
For the most part they are easy to keep straight. You will encounter attribute
definitions while sequentially scanning the drawing or a block. Attribute references,
on the other hand, are found associated only with a block reference.
If you make a request to get the attributes for a block that does not have any
attributes, the resulting value in the variant will be an array of length 0. Thus the
Ubound( ) function will return minus 1 (-1) when the array is empty, meaning that
there are no attributes to be found for that block reference.
The following subroutine demonstrates the basics of accessing attributes by reading
through model space and looking for any entity objects that are blocks. When a
block is found the GetAttributes( ) method is called to build the variant array (ATS).
The upper bound (Ubound) value is incremented to form a count of the number of
attributes (variable K). When a block is found that contains attribute references, it is
reported to the operator using a message box. The output string (S$) for the message
box is built from the various properties of the block reference and attribute
references. Specifically, it contains the block name followed by the count of the
number of attributes found. Also included in the output string are the tag names and
values of the attribute references associated with the block. This function will report
on each individual block it locates in model space.
Page 164
Sub ViewAttribs()
Dim E1 As Object
Dim ATS As Variant
Dim EA As AcadAttributeReference
Dim MS As AcadModelSpace
Set MS = ThisDrawing.ModelSpace
I = MS.Count - 1
For J = 0 To I
Set E1 = MS.Item(J)
If E1.EntityType = acBlockReference Then
ATS = E1.GetAttributes
K = UBound(ATS) + 1
If K > 0 Then
S$ = "Found block - " & E1.Name & _
" - with " & Str$(K) & " attributes { "
For L = 0 To K - 1
Set EA = ATS(L)
S$ = S$ + EA.TagString & "/" & EA.TextString & " "
Next L
S$ = S$ & "}"
MsgBox S$
End If
End If
Next J
End Sub
You create attribute definitions with the AddAttribute( ) method just like adding
other entities into the drawing database. You can use AddAttribute( )with
model space, paper space, or with a block definition object. Adding attributes to
model and paper space is not as common when working in VBA. When
creating new attribute definitions it will most likely be in a block reference.
Page 165
The parameters to the AddAttribute( ) method are the text height, attribute
generation mode, prompt string, insert point, tag string, and default value
string. The insert point is supplied as an array of three double precision
real numbers. The attribute generation mode is an integer code number
from the following table.
Mode What it means
AcAttributeModeInvisibleAttribute is invisible and cannot be seen by operator.
AcAttributeModeConstantAttribute value is constant and cannot be changed.
AcAttributeModeVerify Operator will be requested to verify entry of attribute
data.
AcAttributeModePreset Sets the value of the attribute to the default value
automatically on insert.
If the application requires that the attribute take on more than one mode,
simply add these constants together. Mixing some of the codes will not
make much sense (such as verify and constant modes); however, there are
many cases in which constant or preset attributes are expected to be
invisible, requiring a combination of mode settings.
Attribute definition and references contain many of the same properties.
The most important ones are listed in the table below; most of the others
match the basic text object in their usage and names. Like other entities,
there are methods for computing intersections and other edit
manipulations; however, you will not use them when manipulating
attribute references as often as the ones listed below.
Property What it is
Height Text height of the attribute.
InsertionPointThe point where the text starts.
Mode This is the integer mode value as described in the previous table. Use
these constants to preserve your code from one release of AutoCAD
to the next. This value is only in the attribute definition and does not
appear in the reference.
(table continued on next page)
Page 166
(table continued from previous page)
Property What it is
PromptStringThis is the prompt string the user sees when the attribute is being
referenced inside AutoCAD. This string is only in the attribute
definition and does not appear in the attribute reference.
TagString The tag for the attribute. The tag is used when referencing the
attribute in the attribute extract.
TextString In an attribute reference, this value is the text entered by the user (or
application). For an attribute definition, this string is the default value
of the attribute.
Working with attributes is quite easy inside of VBA. You can add and
manipulate them within block object definitions, and when you use them
in a drawing, you'll find them only when you're accessing the block
reference objects specifically. Compared with the techniques you use to
get at attributes inside of the AutoLISP environment, this is a vast
improvement.
Page 167
Chapter Seven
Working with Other Applications
The primary feature of VB is that it is capable of working with
other programs that support automation inside of Windows. Some
of the programs that support automation include the Microsoft
Office 97 programs Word, Excel, and Access. This chapter
demonstrates the basic strategies of interfacing AutoCAD VBA
with these tools. In particular, we will pay attention to interfacing
AutoCAD VBA with Microsoft Excel. This chapter is merely an
introduction to using automation tools with these other packages.
There are other books available that deal with the interfaces into
the packages in much more detail. This chapter continues with an
exploration of the techniques involved in building links between
AutoCAD and external data systems using extended data (Xdata).
We also cover the Dictionary and Xrecord objects in how they can
be used in relation with external interfaces.
Object Models
Every program that supports ActiveX automation has an object tree
that is similar to the AutoCAD object tree. The difference is that
the tree for the other application will be specific to that application
just as the AutoCAD object library is dedicated to AutoCAD.
Page 168
The object model in the other applications will follow the basic
strategy (figure 7.1) of having the application at the root. There
will be various properties, methods, and events associated with the
application that may interest you, but normally your first step is
into the documents. Inside the collection of documents will be the
one document the application wants to access.
Figure 7.1
Generic object tree
Each of the applications in Office 97 has specific names for each of
the levels just described. In Microsoft Excel, a single spreadsheet
document is a work sheet. Work sheets are contained inside of
workbooks. Thus, workbooks are at the documents object level,
and work sheets are at the document level. Inside the work sheets
are cells that are the individual data items.
When you're talking to a spreadsheet or some other automation
interface system you will have to navigate through the object tree
to get at what you want. This is not as difficult as it may sound: it
is just a matter of learning the various branches and what they can
do for you. The online help and object browser can be very helpful
in locating these items.
Before you can use the online browser to locate the items of
interest, you must first attach the object models you want to use.
You link to an object library through the references setting located
in the Tools pulldown menu of VBAIDE. Selecting the References
option in the Tools menu brings up a menu of the available object
references. You might be surprised at the selection available. It's
generally pretty obvious which reference library to use when it
comes to specific applications. For example, if you want to link in
with Microsoft Excel, page through the list to the Microsoft Excel
option, then pick it. The selected object library will now become
available to your application. If more than one option is available,
pick the most recent edition (highest release number).
To manipulate the objects from the other environments, you should
have a good idea of what you want to do and how. That is, if you
don't
Page 169
know how to use the Excel spreadsheet system, you will have
difficulty understanding all that you can do with the objects that are
available. It will be worth your while to spend time learning how to
manipulate the system in its native mode in order to gain an
appreciation of what the tool can do for an application. The objects
and manipulation tools available to ActiveX are generally quite
extensive, and your application programs can take advantage of
virtually every feature of the other software system.
For you to have access to these tools they must be installed on the
computer you are using. That is, you cannot possibly access the
object model of Excel without Excel first being installed. For
object models to work, the parent task or host must be available to
service the requests. The same is true of AutoCAD and any other
program of such sophistication. The term automation means just
that automation of the tasks on your computer so it does them more
quickly and efficiently.
Interface to Microsoft Excel
This section will show you how to interface to the Microsoft Excel
spreadsheet system of Office 97. Excel is a spreadsheet system, so
it is exceptional at manipulating tabular data. AutoCAD-based
applications can take advantage of Excel to build reports based on
information found in the drawing. At first it may seem like magic
to run a program from another program, but once you get used to
object-oriented programming of this nature it seems primitive to do
it any other way.
The Excel object tree starts at the Excel application (figure 7.2).
Given an object pointer to the application, you access the
workbook object to get to the worksheets level. From there you
select
Figure 7.2
Excel object tree
Page 170
an individual worksheet and a range manipulated inside of that
sheet. A range can be a single cell or multiple cells inside the sheet.
There are numerous methods, events, and properties associated
with each of these levels in the system that you can explore using
the online help and object browser systems. We will now turn our
attention to the details involved when interfacing Excel and
AutoCAD using VBA.
Interfacing Excel to AutoCAD can result in elegant solutions to
common problems found in the design and drafting field. Using the
strengths of each system you could construct a bill of materials
system that counts blocks or other tagged objects in a drawing by
building a spreadsheet detailing what was found. The spreadsheet
can then be further instructed to calculate the costs associated with
the values found. The next step would be to read the spreadsheet
contents back into the drawing to create a bill of material table
inside the drawing. A variation of the same idea would be the
construction of hole charts in a spreadsheet based on the locations
of circles found in the drawing. Once in the spreadsheet, locations
can be sorted and other data appended to the report to finish it
quickly. Even if you're not an advanced systems programmer, you
can enhance productivity by merging the power of a graphics
system such as AutoCAD and a data table manipulation tool such
as Excel.
Figure 7.3
Example 1XLSspread sheet contents
You will create the XLS file ahead of time using normal Excel
operations. The file name to use for our example is
''EXAMPLE1.XLS" and the sheet name will be "Sheet 1", the
default. You can use normal Excel operations to define this table in
the system if you want to try it yourself.
Link to Excel
The remainder of the programming takes place inside VBA in
AutoCAD. When you're starting a new project, the first step is to
link the Excel object library using the Tools-Resources menu
selection with the project. The specific library to select will vary
depending on what version of Excel you have installed. For
example, the name may appear as Microsoft Excel
Page 172
8.0 Object Library if you have Office 97 installed. Now our VBA
program will know how to talk with Excel. (Remember that you
must have Excel installed on your computer to access the library.)
Variable Declarations
After adding the linkage references for Excel, the next step is to
start coding the interface. After inserting a new module into the
project, we type in the following declarations.
Dim ExL As Object
Dim XLWorkBook as Object
Dim excelSheet As Object
VBA fills in the rest for us, adding in a new subroutine definition
to the module. The parentheses are added, as is the End Sub
statement. All we have to do is fill in the middle part. When you
type in the Sub statement with the name of a new function, the
code editor will contain the following after you press the Enter key.
Page 174
Sub Set_Up_Excel ()
End Sub
The following is what we filled in for the function. This function will start
Microsoft Excel with the ''EXAMPLE1.XLS" workbook (must be located in
the default Excel document directory) and "Sheet1" worksheet loaded and
ready to go. Each line of the code is explained in the text that follows. All
the code is presented together for those just scanning for examples.
Sub Set_Up_Excel()
On Error Resume Next
Set ExL = GetObject("", "Excel.Application")
ExL.Visible = True
If (Err.Number <> 0) Then
Err.Clear
MsgBox "You must have Excel loaded on your computer!"
Exit Sub
End If
Set XLWorkBook = Workbooks.Open("EXAMPLE1.XLS")
Sheets("Sheet1").Select
Set excelSheet = ExL.ActiveWorkbook.Sheets("Sheet1")
End Sub
The first part of the program will attach the Excel application object.
GetObject( ) is a VBA function that retrieves an application object given the
executable file name or the class name of the application. If Excel is running,
the class name "Excel.Application" will find a link and return the application
object for our program to use. If Excel is not running, the GetObject( )
function will start Excel. If Excel is not available on the computer, the
program will fail. That's why the error handler is turned on before the call to
GetObject( ). If the error handler was not enabled and Excel was not
available, the program would crash in an ugly manner.
Page 175
This way we can control the exit situation and issue a proper error
message that makes sense to the user.
By including the empty string as the first parameter to the
getObject( ) function, we are instructing VBA to run Excel if it is
not already running in the computer. Leaving the first parameter
blank will cause an error if an instance of Excel does not already
exist in the machine.
Another way to access the workbook object is through the create-
Object( ) function. This function behaves just like getObject( )
except that it will start the application. If your application knows it
will be starting Excel when it is going to run, then the
createObject( ) function is a better choice.
The next step is to open the workbook using the Open method of
the Workbooks object in Excel. You'll supply the complete file
name, with extension, to the Open function. No directory was
specified in the example routine. The file is assumed to be in the
Excel or system search path. If it's not in the search path, you'll
need to provide a complete path name. The extension XLS will not
be appended automatically, which means that your application can
use alternative extensions as a minimal form of data security. The
result of a successful open call is a workbook object.
Workbooks contain worksheets, so the next level into the object
tree takes our application to the specific sheet we wish to have
available. The example program selects ''Sheet1", the default sheet
name in a new workbook. The worksheet object is then assigned to
the variable excelSheet.
The result of running this function is that the workbook and
worksheet are opened and their respective object references are
stored in the variables defined in the declaration section.
To search the entire column labeled as A, you can specify the range
as ("A:A") instead of limiting the range search to rows 1 through
10 as in the code above. In Excel, this format is considered "A1"
notation. Most spreadsheet users are used to denoting areas or
ranges in the document with "A1" notation. "A1" notation uses
letters to represent the columns and numbers to represent the rows.
In this notation the value B5 would refer to the fifth entry in the
second column.
Page 178
When using the ''A1" notation, you can shortcut the code entry by
just specifying the desired range inside of square brackets as in
[A1:A10] instead of Range("A1:A10"). Note that the quotation
marks are not needed when defining the range using the shortcut
approach.
There are other ways to denote ranges of cells inside Excel from
VBA. An easy alternative is to use the Rows and Columns
properties of a worksheet. You can use these properties to define a
range based on an entire row or column. Using the column
property, you would rewrite the code as follows.
Set Fnd = excelSheet.Columns(1).Find("AA-3")
At the end of the loop, the variable R$ would either hold the value
from the second column of the row in which the "AA-3" match was
made or it will be an empty string.
So which style should your application use? Use whatever makes
sense for the application at hand. The Find( ) method will locate a
match inside of a range faster than a direct iteration loop; however,
it is limited to finding exact matches. If you need to test values to
see if they fit a particular range for a selection to be made, then the
direct iteration approach will
Page 179
probably work better for the application. An example is a program
that searches a database of available sizes and selects the one
nearest in size (but larger than) a theoretically calculated size. In
this case, there may not be an exact match, and some logic must be
applied to the spreadsheet data in order to make a selection.
For most applications, you apply a specified range and an exact
value (often called a key) for the search. In those cases, the ''A1"
notation style will work nicely in conjunction with a Find( ). The
range to search could be hard coded as in these examples, or it
could be supplied in the form of a range variable. And because
strings can also be stored inside a spreadsheet, there is nothing that
would stop an application from obtaining the range value to use
from some other cell in the spreadsheet.
When you're searching through a spreadsheet, the best solution for
any given application to use is the one that reads in a logical
manner. For example, if someone said to search the first column,
then the Columns( ) property seems to make the most sense. On the
other hand, if someone specified that the application should search
through a specific set of rows and columns, then the "A1" notation
works best. And if there is a need to perform calculations or
comparisons with the values, a direct iteration is the only way to
get the job done.
Another Example Interface to Microsoft Excel
Simple examples demonstrate how easily you can use Excel to
create reports from AutoCAD drawing information. This function
will create a hole chart from all the circles found in the drawing. A
hole chart is a table that lists holes found in the drawing along with
their X-Y location. The hole chart is typically used for drill
programming or for locating bolted attachments in an assembly.
This simple function set will create a chart with sequential hole
number, X, Y location of center point, and the radius of the hole.
The hole number will then be written back into the drawing at the
center point of the circle using the current default text height. This
example demon-
Page 180
strates just how simple it is to build a powerful reporting tool for
AutoCAD with Excel.
The application is broken down into small modules to make the
code easier to read. The first listing contains the global variable
declarations for the module. There are two variables that we will
declare as global (available to all functions and subroutines in the
module), and they are a link to the active Excel spreadsheet and an
AutoCAD selection set collection.
Dim excelSheet As Object
Dim SS As AcadSelectionSet
The Sort( ) method can be a tad confusing at a quick glance. From the
example above, it appears as though the sort would do only a single
cellcertainly not the desired operation. Actually, the value supplied is either a
range or the first cell of a region. In this case, we are sorting a region that is
designated as starting at "A1". The sort fields are defined by assigning the
parameter variables Key1, Key2, and so forth to the first sort fields in the
spreadsheet. For our example we are sorting by the X, then Y, then the radius
values. You can sort the fields in ascending (the default) order or in
descending order. To have a field, such as the Y values, sort in descending
order, use the Order2 parameter variable and set it to a value of
xlDescending. Order1 will change the sort order of the first key field, and
Order3 will change the order of the third set. There are up to three sort fields
that can be defined in the Sort( ) method.
Let's turn our attention to the first of the subroutines called from the main
function. The Get_Circles function will build a selection set collection of
circles found in the drawing.
Function Get_Circles() As AcadSelectionSet
Dim Cir1, Cir2 As Variant
Dim CirA(0 To 0) As Integer
Dim CirB(0 To 0) As Variant
CirA(0) = 0
CirB(0) = "CIRCLE"
Cir1 = CirA: Cir2 = CirB
On Error Resume Next
Set Get_Circles = ThisDrawing.SelectionSets.Add("HOLES")
Page 182
If Err.Number <> 0 Then
Err.Clear
Set Get_Circles = ThisDrawing.SelectionSets.Item(''HOLES")
End If
Get_Circles.Clear
Get_Circles.Select acSelectionSetAll, , , Cir1, Cir2
End Function
The value that will be returned from the Get_Circles function is a selection set
collection. The function is defined as being of the type selection set, and we can use
the name in our program as a variable to house the selection set collection while it
is being constructed. Get_Circles uses a filter to construct the selection set
collection. The filter is to look for circles only and can be expanded to include layer
names and other criteria as well.
Given the selection set collection, the next step is to write the values out to Excel in
the worksheet already started. At the beginning of this subroutine, the worksheet is
expected to be empty.
Sub Send_Holes_To_Excel()
Dim Ent As AcadCircle
CN = 1: CX = 2: CY = 3: CR = 4
R = 1
Dim PTV As Variant
For Each Ent In SS
excelSheet.Cells(R, CN).Value = Ent.Handle
PTV = Ent.Center
excelSheet.Cells(R, CX).Value = PTV(0)
excelSheet.Cells(R, CY).Value = PTV(1)
excelSheet.Cells(R, CR).Value = Ent.Radius
R = R + 1
Next Ent
End Sub
Page 183
This function loops through the selection set collection (stored in
global variable SS, which was set in the main program as the result
of calling Get_Circles). Each entity is assumed to be a circle object,
meaning that certain values are known to be available such as the
center point and radius. As this subroutine reads through the
selection set collection each entity is placed in the variable Ent for
processing. The first column of the spreadsheet is set to the entity
handle. Handles are the best way to link entity objects with external
data structures; we will be discussing them in more detail later in this
chapter. The second and third columns of the spreadsheet are then set
to the X and Y values of the circle center point. The fourth column is
set to the radius value found in the circle object.
The variable R holds the row number as the program adds each hole
location to the spreadsheet. After the user writes the hole location
and size information to the spreadsheet, the subroutine ends and
control is returned back to the main program.
The main program then sorts the spreadsheet as already discussed.
The sorted spreadsheet contains the data sequenced by X, Y, and
Radius values. The next subroutine will read the spreadsheet and
place hole numbers at each circle location. There are two operations
that will take place as this function iterates through the spreadsheet.
The first is to place the hole number in the drawing. The second is to
replace the handle entry in the spreadsheet with the sequential hole
number.
Sub Set_Hole_Numbers()
Dim PTV As Variant
Dim PTC(0 To 2) As Double
I = 1
TH = ThisDrawing.GetVariable(''TEXTSIZE")
While excelSheet.Cells(I, 1).Value <> ""
PTC(0) = excelSheet.Cells(I, 2).Value
PTC(1) = excelSheet.Cells(I, 3).Value
PTC(2) = 0#
ThisDrawing.ModelSpace.AddText Str$(I), PTC, TH
Page 184
I = I + 1
Wend
End Sub
The function begins by obtaining the current default text size for
the drawing. This value will be used when adding the text objects
for the hole number. A While loop is started that will iterate so long
as the cell in the first column of the current row number (in
variable I) has a non-blank entry. Handles are never blank, thus
when the program encounters a blank cell, it has hit the end of the
list. This version of the function doesn't do anything with the
handle other than test to see if one is there.
The X and Y values for the center of the circle are retrieved from
the spreadsheet and placed into an array of doubles. This array is
set into the variant variable PTV which is needed by the addCircle(
) function. You must use variants when sending and getting points
from objects. The reason has to do with the way the BASIC
language (as implemented in VBA) passes parameters internally
and the fact that array references are handled better using a variant
pointer.
The row number is incremented, and the loop continues until the
last hole has been read and the text placed in the drawing, at which
point the subroutine finishes.
This function set demonstrates the basics and performs a very
useful operation as well (should you need hole charts and a
numbering system for holes). VBA provides a powerful way to tie
various tools together so that each can be used in its own way to
make the application dream a reality.
Using Handles
The last example used handles but didn't really do anything with
them other than look for a blank handle indicating the end of the
list in the spreadsheet. Handles are strings that uniquely identify
each object in a drawing. AutoCAD assigns handles as the objects
are created and never reuses the same handle in the drawing. There
are tools in AutoCAD's
Page 185
programming systems for converting handles to entity objects. As such,
handles present a way that entity object references can be moved to an
external system such as a spreadsheet for later reference.
In VBA, a handle is converted to an entity object through the Handle-
ToObject( ) method. This method is associated with the document object and
can return values only when that document is the current document. That is,
you can get handles converted into objects only in the currently opened
drawing.
Using this conversion utility you can update the drawing based on the values
in the spreadsheet as in the following example, which looks at the same
spreadsheet. In this subroutine, the values in the spreadsheet are read one at a
time and the radius values checked against the original drawing objects. If
changed, the drawing object is updated and the layer changed to layer
''CHANGED". The layer is assumed to exist before the macro is run.
Sub update_radii()
Dim Excell As Object
Set Excell = GetObject(, "Excel.Application")
Set excelSheet = Excell.ActiveWorkbook.Sheets("Sheet32")
Dim Ent As AcadCircle
I = 1
While excelSheet.Cells(I, 1).Value <> ""
HN$ = excelSheet.Cells(I, 1).Value
Set Ent = ThisDrawing.HandleToObject(HN$)
If Ent.Radius <> excelSheet.Cells(I, 4) Then
Ent.Radius = excelSheet.Cells(I, 4)
Ent.Layer = "CHANGED"
End If
I = I + 1
Wend
End Sub
Page 186
You need to create a dictionary object only once; doing so a second time will
result in an error trigger. If a particular dictionary object already exists in the
drawing, you'll access it using the Item( ) method. The following code will
access the dictionary object named "My Dictionary" and if it is not found,
will create it.
Page 190
' Dictionary objects should be global
Dim Dict As AcadDictionary
'
On Error Resume Next
Set Dict = ThisDrawing.Dictionaries.Item ( ''My Dictionary")
If Err.Number <> 0 Then
Err.Clear
Set Dict = ThisDrawing.Dictionaries.Add("My Dictionary")
End If
The dictionary object can be used to reference the objects within the dictionary.
What you will find in a dictionary is entirely up to the application that
maintains the dictionary. In most cases, the dictionary will contain object
references. The objects in the dictionary are accessed just like a collection in
that you use names or the index number to obtain the reference.
For most applications the dictionary serves as a wonderful place to store
variable values and parametric data. A dictionary can also be used to store
tables of data reflecting standards in effect when the drawing was created. As a
result, the most common member of a custom dictionary is the Xrecord.
Because Xrecords can contain any data and make use of the same numbering
system as AutoCAD objects, they are very easy for most AutoCAD
programmers to use.
Xrecord Contents
An Xrecord contains variable data: one Xrecord does not have to look like the
next in the dictionary collection. The data for an Xrecord is supplied in two
arrays. The first array contains integer group codes that specify the kind of data
that will be found at the same offset in the second array. The second array is of
type variant, meaning that it can contain anything. When accessing or writing
an Xrecord, these two arrays are used. They must be the same size, and the data
contents are entirely up to the appli-
Page 191
cation. The only integer codes not permitted are 5 and 105, as these are reserved for AutoCAD
handles. New Xrecords will have handles added automatically when they are first created. All
of the remaining group codes are at the disposal of the application. That is, you can use group
code 40 over and over again for a sequence of real numbers, or you can use 40, 41, and so
forth. Whatever works best for the application.
To add an Xrecord object to a dictionary, first open the dictionary. We recommend that you
dimension objects such as dictionaries in global memory so that they may be accessed by all
modules in the application that need to get at them. With the dictionary already open, the next
step is to add the Xrecord object to it with the AddXRecord( ) method. The AddXrecord( )
method creates an Xrecord object that is attached to the dictionary collection. The Xrecord
data is then written to the object using the SetXRecordData method.
To learn how an Xrecord object is created, consider the following code. A new Xrecord object
is attached to an already open dictionary object referenced by the variable Dict as in the
previous code segment. The subroutine will store a real number, an integer, and a string,
which are all provided as parameters to the function. The key parameter is the key name that
will be used for accessing the Xrecord in the dictionary at some time in the future.
Sub WriteXrecord(Key As String, R As Double, I As Integer, S As String)
Dim Xtyp(2) As Integer
Dim Xvar(2) As Variant
Xtyp(0) = 40: Xvar(0) = R
Xtyp(1) = 60: Xvar(1) = I
Xtyp(2) = 1: Xvar(2) = S
Dim Xrec As AcadXRecord
Set Xrec = Dict.AddXRecord(Key)
Xrec.SetXRecordData Xtyp, Xvar
End Sub
Page 192
The function just provided might be used by an application that has three variables to be stored
for future referencing. This function could be part of a module that reacts to the begin-save
event. The first step would be to open the dictionary object by accessing an existing one or
creating a new one. Next you'll write the variables. That would end the begin-save event
reactor. You'll need to do additional programming for the drawing-open reactor, in which a
module would open the dictionary and read the three variables back into the application.
Reading Xrecords
To read an Xrecord you must first know the key name it was stored under. The only alternative
is to loop through the dictionary one item at a time and examine the contents of each. In either
case, the Item( ) method is used with the dictionary object to obtain the Xrecord object. From
there, you'll use the GetXRecordData( ) method to get at the group codes and data stored inside.
<XrecordObject>.GetXRecordData( ) uses two variant parameters. When the function returns,
these two will reference arrays of data. The first will contain an array of integer values, and the
second will be an array of variants.
The next code example will read the Xrecord created in the previous example given the key
name as a parameter. The values read from the Xrecord are put back into the parameter
variables to be used by the calling program. You'll use the function GetXRecordData( ) method
to return the Xrecord contents given the Xrecord object reference. To obtain the Xrecord object
reference, the Item( ) method is applied against the already open dictionary object Dict.
Sub ReadMyXrecord(Key As String, R As Double, I As Integer, S As String)
Dim Xtyp, XVar As Variant
Dim XR As AcadXRecord
Set XR = Dict.Item(Key)
XR.GetXRecordData Xtyp, XVar
Page 193
For J = LBound(Xtyp) To UBound(Xtyp)
If Xtyp(J) = 1 Then S = XVar(J)
If Xtyp(J) = 40 Then R = XVar(J)
If Xtyp(J) = 70 Then I = XVar(J)
Next J
End Sub
In this function, the values returned from the Xrecord read are processed
into variables that are passed back to the calling function. They could just
as easily been placed into global variable locations for the application or
returned as a result of a function instead. The key item to remember is that
Xrecords are under the control of the application program manipulating
them. They can contain any type of data desired and can be of any length.
Note that they are not protected from other programmers who understand
how to navigate the object system of AutoCAD, but they are well
protected from the normal AutoCAD user.
Extended Data
The other way to attach data that is non-graphical to a drawing is to use
extended data. You attach extended data directly to objects in the drawing
database; these can contain numbers, points, and strings. The only real
limit to keep in mind with extended data is that an object can have only
about 16 kilobytes of data attached to it. Now, that is a lot of data to attach
to an object in a drawing, and it would not be good to attach even half that
amount to objects throughout the database. Operators will most definitely
complain about the excessive disk space being consumed.
When setting up extended data, you'll use a group code system much like
the Xrecord objects with the exception that extended data group codes are
all numbered in the 1000 series. Extended data attachments must use these
group codes when attaching data to an entity object.
CodeExtended data type
1000 String.
1001 Application name.
1002 Control string for nested information. Open bracket for start of the nest, close
bracket for the end of it.
1003 Layer name. If the layer name is changed in the drawing, this field will be
updated to reflect that change.
1004 Binary data storage. Data cannot be accessed by AutoLISP and is used
primarily by ObjectARX applications.
(table continued on next page)
Page 195
(table continued from previous page)
Code Extended data type
1005 Handle to another object. Can be used to link one object to another.
1010 Point.
1040 Real number.
1041 Distance will be scaled with the parent object.
1042 Scale factor will be scaled with the parent object.
1070 Integer.
1071 Long integer.
Every object in the AutoCAD drawing database can have extended data
attached to it. But before you can use extended data, the application ID
must first be added to the registered applications collection. The Add( )
method is used to add the name of your application to the registered
applications collection object in the current drawing, as in the following
line of code.
ThisDrawing.RegisteredApplications.Add "MyApplication"
The SetXData method is used with the line object to add the
extended data arrays to the object. Group codes 1001 and 1040
were used to hold the registered application name and the real
number value for the CDATE system variable. If you need to store
an additional real number, the group code 1040 is used again. One
problem that can come up is if multiple applications are working
with the same extended data. In those cases, it is possible that the
order of the data elements could get confused. We highly
recommend that you keep extended data grouped in small data
packs if there is a requirement for multiple applications to be
messing with the data. Each of the data packs is assigned a
registered application name, making it easy to retrieve just the data
sought after.
This next section of code will locate the line with the "CREATED"
extended data and read the saved value for the CDATE system
variable. In order to accomplish the task, the function must first
locate the line. This is done with the selection set utility function.
The function Getdate( ) is presented in pieces, followed by a
description of each section of code.
Function Getdate()As Double
Dim SS As AcadSelectionSet
Page 198
On Error Resume Next
Set SS = ThisDrawing.SelectionSets.Add(''TEMP")
If Err.Number <> 0 Then
Set SS = ThisDrawing.SelectionSets.Item("TEMP")
Err.Clear
SS.Clear
End If
'function continues
You'll use the Select method from the selection set object to locate
the desired graphics. We are interested in finding a "LINE" object
that has extended data attached to it. The technique involved in
building the filter
Page 199
for extended data is somewhat different in VBA compared with
AutoLISP/Visual LISP. Instead of searching for a 3 group code, it
searches for the 1001 group code. The 1001 group code contains
the application name that will be exactly the same as the
application name supplied in the function that wrote the extended
data in the first place. For our application, that name is
''CREATED".
The filter list is built by first defining two arrays. The first array
contains the integer group codes for the data we are filtering. In
this example we are looking for a "LINE", thus group code 0 is
used. Entity names are always associated with group code 0. The
extended data application name is represented by the 1001 value.
In the second array, the values for these variables are set. The
second array is of the type Variant so that it can hold any type of
data: string, double, or integer.
Due to the way variants are stored in the VBA system, a second
assignment is made for the arrays to another pair of Variant
variables (vFT, vFV). All the input elements for the selection set
building function are ready, and Select( ) is called on to put entities
into the selection set SS. The acSelectSetAll is an AutoCAD
constant that tells the select method to search the entire drawing
database.
At the end of this section of code, the selection set variable SS now
contains a "LINE" object that has the extended data attached to it.
If the "LINE" object is not found in the drawing, the selection set
will be empty.
'function continues
If SS.Count > 0 Then
Dim Ent As AcadLine
Set Ent = SS.Item(0)
Ent.GetXData "CREATED", vFT, vFV
GetSavedDate = vFV(1)
Else
GetSavedDate = 0#
End If
End Function
Page 200
The selection set Count property tells us how many objects were
found matching the filter description we just used. If the Count is
greater than 0, then the Select( ) method was successful in locating
objects that fit our criteria.
We know that the object we want is a line, so we define an
AcadLine object. If the extended data had been attached to any
AutoCAD object, a better choice would have been to use the
AcadObject definition instead. However, due to the way VBA
works with libraries and objects, the general rule of thumb is that
when you know exactly what object type will be encountered, use
that definition. This will improve the performance of the
applications.
The application looks at the first line in the selection set with
Item(0). The GetXData( ) method is used with that entity object to
retrieve two variants that are arrays containing the extended data.
Since our application wrote only two pieces of data to the extended
data, the name of the application and the data value, we know for
certain that the value saved can be found in the second element.
Thus, use vFV(1) to get the saved value and place it in the return
value of the function.
If the selection set count was 0, the function didn't find any ''LINE"
objects with the extended data attached. At this point, the return
result of the function is set to 0.
A more advanced look at extended data manipulations is presented
in a later chapter. Extended data provides a powerful way to
associate non-graphical data to existing graphical objects. There
are other techniques that can be used as well, including Xrecords
with hard ownership relationships. However, these are more
difficult to manage under VBA, and most applications will find
extended data to suffice.
Page 201
Chapter Eight
Managing Multiple Projects
The macro system in VBA is excellent for creating small
applications that solve specific problems in AutoCAD. Using VBA
macros, you can greatly enhance the way AutoCAD works for a
particular discipline. In this chapter we are going to explore how to
keep track of the VBA macros and how to integrate them into
normal AutoCAD operations. We are also going to be looking at
the different ways to store VBA macros in AutoCAD drawings or
as projects.
Embedded Projects
An embedded project is one that is stored inside the AutoCAD
drawing. When the drawing is loaded, the operator will be given
the opportunity to enable the embedded project. A stern warning
about viruses is issued as the default in AutoCAD, so users may be
a bit shy about allowing the macros to be loaded. You can disable
the virus warning for future loads at the particular workstation, but
this will let any drawing that has attached macros enter the system
as well. The choice of using embedded projects is up to the
environment. It does increase the drawing size, but depending on
the application, that may not be by very much.
To embed a project in a drawing, load the drawing, then either
define or load the project. In the VBA Project Manager program
dialog, select the project, then select the Embed button. The project
is now embedded into the drawing and will be saved with the
drawing.
The next time the drawing is loaded, the project is immediately
available. The AcadDocument_Activate function will then be run.
You can use this function to load a dialog box (form.show)
immediately to ask the user a question or two. You can create a
time management system for each drawing using this simple
approach.
There can be only one project embedded in the drawing at a time,
however. That project can reference other projects stored on disk.
To have an embedded project reference a stored project, load both
into the VBAIDE. With the embedded project as the active project,
select the ToolsReferences pull-down menu option. Find the object
name of the other project in the list and select it. Save the project
and drawing. The next time the drawing is loaded, the embedded
project will be loaded automatically and the referenced project will
be loaded at the same time.
Projects on Disk
Projects that are not embedded are stored on disk as DVB files. A
DVB project file can be locked, thereby protecting it from changes
by the user. A project is stored on disk when the Save project is
used and the project
Page 206
is not considered embedded. A project contains all the modules,
forms, and object reference information needed to run the project
the next time it is loaded. If the project has public subroutines
defined, they are listed in the macros list.
To load a project, you can use the VBALOAD command. You can
also load VBA projects by entering the VBA Manager dialog box
(command VBAMAN). The VBARUN command will display a
dialog box for running the macros that are exposed in any of the
projects loaded.
In AutoCAD 2000 you can have more than one project loaded and
available at once. In AutoCAD Release 14's version of VBA, only
one project can be open and available at a time. Thus the entire
idea of referencing other projects is not something that can be
explored with AutoCAD Release 14: it requires AutoCAD 2000.
You can load the project manager without the dialog box. This is
how you place project load and start-up sequences into AutoCAD
menus and AutoLISP macros. When you put a dash character (-) in
front of the command, AutoCAD does not display the dialog box
but instead prompts for the parameters required.
To illustrate, the following code segment is from a menu macro
that will load the VBA project stored as MYPROJ.DVB, then start
a macro named MYMACRO that is a public subroutine in the
project. This menu macro can be added as a new toolbar entry or
can be part of a larger menu source file.
[Run my macro]^C^C^C^P-
VBALOAD MYPROJ.DVB VBARUN MYMACRO
When the DVB file does not exist in the search path for AutoCAD,
the entire path name must be provided to properly load it. If the
project is already loaded, the VBALOAD command will just exit,
and the VBARUN command can then run the macro.
You can supply this same sequence in an AutoLISP program
module to start a VBA macro. And you can employ the
COMMAND subr to send the command stream to AutoCAD to
launch the program.
(command "-VBALOAD" "MYPROJ.DVB" "-
VBARUN" "MYMACRO")
Page 207
Using the AutoLISP launch version, you can set up the ACAD.LSP
files to contain a function that will load and start the VBA
application. Note that in AutoCAD 2000 the usage of the
ACAD.LSP file has changed, and it may not load for every
drawing according to the AutoCAD system variable setting
ACADLSPASDOC. When this variable is true, the default,
ACAD.LSP, is loaded for each new drawing. When false,
ACAD.LSP will be loaded once at the beginning of the AutoCAD
session.
Both VBA program launch mechanisms can result in dialog box
interruptions. The first is the Macro Virus warning. A stern
warning is displayed in a dialog box stating that macros may
contain viruses and that the user can disable the macros to make
sure no viruses infect the system. Of course, this could result in the
VBA macro not running at all. When running from a menu or from
AutoLISP, that is not the desired result. Macro Virus warnings can
be turned off by toggling the ''Always ask before opening projects
with macros" to the off position (not checked). Future warnings
will not be issued until the feature is turned back on. Another
dialog error that will result from using the load and launch will
result when you're attempting to perform the same function a
second time in the same drawing. Since the macro set is already
loaded, an error message will result stating that the file is already
loaded. There is no way presently to test if a VBA project is loaded
from inside an AutoLISP routine or from a menu macro.
Thus the best way to load and launch VBA programs is using the
menu system of AutoCAD. Inside the menu you can explicitly
request the VBA application by name or force the load of the
supporting AutoLISP code that runs the project. Once the menu
macro has run the first time, it can be replaced with a simple macro
that just reruns the VBA program. The user makes a single pick of
the menu item and the program starts running. What could be
simpler?
Re-Using Code
As you develop applications with VBA, you will begin to build a
toolbox of useful utilities. We are getting you started with a host of
functions
Page 208
that will be introduced in Chapter 10. These utilities can be
imported into your current projects by saving the individual
modules as they are developed. Modules are saved as BAS files. To
build a BAS file from inside the VBAIDE, select the FilesExport
pull-down menu option. Modules are exported as ASCII text files
with a default extension of BAS.
The same is true with forms. They can be exported to FRM and
FRX files that contain the essential information related to the
dialog box and associated code. The FRM file is an ASCII header
file that points to the FRX file. The FRX file is a binary file that
contains the actual dialog box definition and its associated code
segments.
In a future project where the same program code or input form may
be used again, you can import the saved components using the
FilesImport pull-down menu option. Once you have imported the
entire module or form, you can keep those sections that are of
interest while you remove the remainder using the editors in
VBAIDE.
Sometimes it is better to have a copy of another text editor (such as
Notepad) running to load code modules (BAS files). You can copy
the needed code to the clipboard, then paste it back into the
VBAIDE in the module where the code will be used. This approach
works great when you are working with a large library (like that
provided with this book) and want to pull in fragments of the code
to save yourself the typing.
Running a Macro from Another Project
Another choice available to the VBA developer for re-using code
already developed is to load the project that contains the module
desired and run it. AutoCAD VBA provides the tools needed to
accomplish this task in AutoCAD 2000. There are three methods
associated with the application object that can be used to load, run,
and unload projects.
The LoadDVB method will load a project file (extension DVB). If
the project is already open, an error will result, so it is best to
invoke the error handler when using this method unless you know
for sure that the project is not loaded and that you will be
unloading it when you are
Page 209
done with it. LoadDVB has one parameter: the name of the project
file as a string. You should provide the complete path name and
extension DVB if the file is not in the current search directory.
When the load operation is completed, the project is now available
to the user as well as to your application.
After loading a project into the current application environment,
you can use the RunMacro method to run a public subroutine from
the project. You must define the subroutine as public since your
application will enjoy only the same rights into the project as a user
does. If the macro is not available for whatever reason, an error
will result.
The only parameter to the RunMacro method is the name of the
macro to run. When supplying a name for this function, the
complete macro location must be specified. That is, you need to
supply the module name plus the name of the subroutine.
RunMacro is associated with the application object that has just
opened the project file. If you have a macro and module of the
same name in your program set, they will not be run. The
difference is the way you call on a macro in your own program
versus in an external one, as we are discussing. When you call a
macro in your own program you supply the name directly, and
VBA finds the links right away. When you call a macro in a loaded
DVB project file, you supply the macro name as a string parameter.
The string is then used in a search of the project to locate the macro
intended. At that time the macro executes.
If you want to run macros from multiple DVB files, it is best to
close each one as soon as you are done with it. To close the project,
use the UnloadDVB method. Once again, you must supply the
name of the DVB project in order to ensure that the correct project
is closed.
The following simple example will load a DVB project called
CoolStuf that is saved in the \MyCoolStuff directory. Once the
project is loaded, the macro VeryNeat is run from the module
named Module1. Then the project is unloaded.
Dim ACADApp As AcadApplication
Set ACADApp = GetObject(, ''AutoCAD.Application")
Page 210
ACADApp.LoadDVB "C:\MyCoolStuff\CoolStuf.DVB"
ACADApp.RunMacro ''Module1.VeryNeat"
ACADApp.UnloadDVB "C:\MyCoolStuff\CoolStuf.DVB"
Chapter Nine
API Calls from VBA
Although VBA programs run inside of AutoCAD, they also run
inside of Windows, and there are times when an application needs
to perform tasks related to the operating system. This is where
VBA greatly exceeds the abilities of AutoLISP. You can talk to
Windows by calling functions that are available as objects and
utilities to your program.
What's an API?
API is an acronym for Application Programmer's Interface. The
Windows Application Programmer's Interface is a set of functions
built into Windows that allow you to access the system's registry
and INI files. Microsoft has included a robust set of information
about the system in the registry, and you can write more exotic
applications using this information. You can write sound generator
programs or programs that animate the desktop or draw on it.
Windows API is a whole world unto itself, and many a career has
been made learning and using it.
Page 215
AutoLISP programmers have not been able to access the Windows
registry and therefore have limited or no experience with this rich
environment. You can access any information stored in the registry
through the API calls. This includes ActiveX information about
other applications or even information about your printer or plotter.
It all depends on the vendor setting up the information in the
registry.
An example is AutoCAD and AutoCAD LT. AutoCAD is an
ActiveX client and server. It can make calls to other applications,
or it can receive calls from other applications. It has a switch that
can be used to tell it that it is being used as a server (/Automation).
When you use an API in a language such as VB to GetObject and
tell it you want the AutoCAD application, the function searches the
Windows registry to see if AutoCAD is registered as an ActiveX
application and uses the information, when found, to find
AutoCAD and attach it to the object. An application like AutoCAD
LT (the AutoCAD engine stripped down) is not directly
programmable from VB because the hook inside the registry is
missing and the switch has been turned off inside the application.
By now, you're probably saying to yourself, ''Great, but what's that
got to do with VBA?" Simple: VBA supports the API calls
necessary to access the system registry. You won't want to use it for
attaching and manipulating AutoCAD because you're already
inside AutoCAD, but you can still use it to access other
applications that are ActiveX compliant. You can also use it to
access INI files, directory information, file information, and printer
information. It's great for querying the system to find out how
much space you have left on a drive or how much memory is
available. The list goes on and on. This chapter looks at only a few
of the more common API calls you might regularly use. For more
extensive reading on Windows APIs, we suggest that you pick up
one of the many books on the subject. We recommend PC
Magazine's Visual Basic Programmer's Guide to the Win32 API by
Daniel Appleman (published by Ziff-Davis Press) for its coverage
of topics such as directory and file APIs and system information.
Page 216
Figure 9.1
API Viewer interface
Page 217
Load a text or database file into the program by using the File/Load
Text File menu item. Several are shipped with the program but the
one you will use most is the Win32api.txt file (or its database
equivalent should you use the Convert text to database menu item
to convert it into a Jet database). Once the file is loaded into the
program a list appears in the Available Items list box. You can
change from a list of Declarations to a list of Types or Constants by
using the pull-down list labeled API Type, as shown in Figure 9.2.
The Search button allows you to search for a specific item while
the Add button allows you to add the item to the Selected Items list
box. The Remove button allows you to remove an item from the
Selected Items list box, and the Copy button allows you to place
the items in the Selected Items list box into the clipboard for
pasting into your program's declaration area.
Figure 9.2
API Types pull-down menu
The problem with this program is that it expects you to already
know the declaration you are looking for. The search engine is
keyed on the declaration names. You can use the slide bar on the
list box window to scan all of the items, but that is very time
consuming, and not all declaration names are intuitive. That's why
we suggest that you purchase a book that explains what each
declaration can do, then use the program to go find them instead of
having to type them in by hand.
INI File Calls
INI files are simply ASCII text files in a set format that allows the
programmer access to information to be used by the program.
Opening, closing, reading, and writing in VBA is straightforward
even though the
Page 218
reading and writing functions have many options. Simple ASCII
text file manipulation does not require API calls. To experiment
with examples of this type of file manipulation, load the project
called FileIO.dvb provided on the accompanying CD and run the
macro IOEXAMPLE from the immediate window. Simple input
and output operations are provided as an example of ASCII file
manipulation without API calls.
Many AutoLISP programmers have had to create their own
routines for accessing INI files because the AutoLISP language
does not have access to the API calls. Routines that segregate the
sections, keys, and items into lists that allow the programmer to
process the item data are not part of that language. You can build
the same routines in VB and VBA, but you don't need to because
those languages have access to the API calls for accessing INI files.
There are two API calls that are used to retrieve and write item data
in an INI file. They are
GetPrivateProfileString; and
WritePrivateProfileString.
Both of these API calls return a long telling you how many
characters were placed in their string buffers. You can use this
information to authenticate that you have written the number of
characters back to the file when using the WritePrivateProfileString
API call and you must use it to trim unwanted and unused space in
the string buffer returned from the GetPrivateProfileString API
call.
How the PrivateProfileString APIs Work
It is important to understand how API calls work in general. Both
of these calls return information in the traditional way (passing
back a long data type that tells you how many characters were in
the buffer), but they also use the string buffer in their argument list
to hold returned information. In fact, it is the string buffer argument
that has the information you really want to process! The returned
long is just the character count of the actual data in the buffer. This
is typical of many
Page 219
API calls, so a more detailed analysis of the API declaration will help in understanding API calls in
general.
API Declaration Breakdown
Let's start with the GetPrivateProfileString API call declaration and break down what it is doing.
This is the function declaration that is placed in your declaration section. It is as follows on one line
of code:
Declare Function
GetPrivateProfileString
Lib ''kernel32" Alias
"GetPrivateProfileStringA"
(ByVal lpApplicationName
2042015b45d2b5416108e486be44e8bc. As String, ByVal 2042015b45d2b5416108e486be44e8bc.
gif lpKeyName As Any, gif
ByVal lpDefault As String,
ByVal lpReturnedString As
String, ByVal nSize As
Long, ByVal lpFileName
As String) As Long
This is lengthy and worthy of understanding. Here is each piece broken down as to what it does:
Declare tells VBA that you are starting the declaration (works like Dim, Public, or Private).
Function is the type of procedure. A function returns a value while a subroutine would simply
perform an action.
GetPrivateProfileString is the name of the function.
Lib "kernel32" is the name of the Windows library containing the function.
Alias "GetPrivateProfileStringA" defines which internal function name in the library you want
assigned to your function name. This is necessary because many API functions have different
internal definitions for 16- or 32-bit functions, and many times a version works with only ASCII or
Unicode. The A at the end of this alias means that it works on ASCII code.
ByVal lpApplicationName As String is the section header name as the data type string.
Page 220
ByVal lpKeyName As Any is the key name as either a string or a
Null value. The Any data type means that you are deferring the
data type to when you use the call. Then the VBA interpreter will
determine the data type of the data you pass in and act accordingly.
ByVal lpDefault As String is a default return value placed in the
result string buffer should the call fail to find any data.
ByVal lpReturnedString As String is the string buffer that is filled
with the data you are requesting.
ByVal nSize As Long is the specified length of the string buffer
that is returned.
ByVal lpFileName As String is the name of the INI file you wish to
access. Full path and extension are necessary.
As Long is the returned number of characters in the string buffer.
There are a few items here that are very important to consider when
you are declaring your API call:
1. It really doesn't matter what you name the arguments in the
declaration. Even Microsoft changes them in the examples from
version to version. Since you are using them in your program, you
can call them what you want. Only the alias name must remain the
same to ensure that you are getting the correct function from the
library.
2. The alias function name for the library specifies which library
function to use. If you forget the A at the end of the alias function
name, your function will not work properly with ASCII text files.
3. A data type of Any (used for the lpKeyName argument) allows
you to pass either a string to search for or a string having a value of
0 (vbNullString). A vbNullString being passed in tells the function
to return a list of all keys in the INI file, separated by a Null
character, in the string buffer. Just the keys are returned in this
situation, not their items. You can then spin through the string
buffer with your handy dandy parser function (see Chapter 10) and
check out each key in the
Page 221
file. This option is often used to gather a list of all keys in a file for
examination. It should be noted that some programmers prefer to
use two declarations, with different names, when they are dealing
with an argument that has the Any data type. The thought process
behind this is that it is clearer to have two slightly different
declarations to keep track of, each one declaring specifically the
data type to be used for the argument. Then they just use the proper
one for the job rather than trust to memory that the one argument
can be either data type.
4. The default string can be a zero-length string.
5. The returned string is a fixed-length string buffer that you must
set up before the call. The returned value always ends in a Null
string character [chr$(0)]. You must remove the Null string and any
trailing characters before processing the string, or functions such as
Len will report back erroneous information. For functions such as
the PrivateProfileString function that returns a long telling you how
many characters were put into the string buffer, the matter is
simple. Use the Left function to parse out your data from the
buffer. Other API functions don't report back how many characters
are in the buffer, and that can be a small problem. For those
situations you must find the length of the data, then parse it out.
This is not all that difficult; the function you need to do it is
supplied in Chapter 10: it is called StripTerminator.
6. The size argument must be large enough to hold all of the data.
If it is not, the data is truncated.
7. If no filename is supplied, the default value is returned in the
string buffer.
There are a few words of caution that we must share regarding the
use of these API calls. To show them we need to use a code
example as follows. This code shows a typical use of the API
function. The string variables strSection, strKey, strDefault, and
strIniFile and the global constant gintMAX_SIZE are assumed to
have been already defined.
Page 222
Dim strBuffer As String
Dim strResult As String
Dim lngPos As Long
strBuffer = Space$(gintMAX_SIZE)
lngPos = GetPrivateProfileString (strSection, strKey, strDefault, _
strBuffer, gintMAX_SIZE, strIniFile)
There are some subtle nuisances to the code shown in the above figure. First is the use of
separate declarations for the strBuffer and strResult strings.
Many experienced VBA programmers prefer to use the handy shortcut of declaring like
variables on the same line. A single-line declaration for the two variables follows.
Dim strBuffer, strResult As String
The code looks good and does not cause a compile (to pcode) or runtime error. But it
does not work! The reason is that the strBuffer variable must be a string, and the
declaration is actually setting it to a Variant type. This is because VBA assigns a default
data type of Variant when no data type is specified, and the shortcut shown in the above
code only assigns the string data type to the second (strResult) variable, not the first
variable listed. In most situations the shortcut works because VBA is very forgiving but
in this situation it does not work. To make sure that the data type you want for each
variable is assigned to each variable listed in a shortcut, you must declare the data type
for each variable as shown in the code below.
Dim strBuffer as String, strResult As String
Once the strBuffer variable is properly declared the string must be initialized to spaces.
The line of code strBuffer = Space$(gintMAX_SIZE) places the specified amount of
spaces defined in the global integer gintMAX_SIZE into the string. For clarity,
gintMAX_SIZE is defined elsewhere in our program module and has an integer value
specifying the size of the strings to be used.
Page 223
If the size is too small for the returning data, the API truncates the
returned data. We must also point out that you must initiate the
buffer before giving it to the API as an argument. Should you not
do so, the program will fail. When calling the API functions, VBA
is really calling into a library of modules that have different
specific requirements. In addition, they were written in different
computer languages that have alternative ways of representing
string variable data. The problem is that the API function called has
no way of knowing how long a string you declared for the
argument. You must define the length of the string so as not to
overwrite any other variables in your memory pool. Finding this
sort of error tracing and debugging can consume a lot of time.
Another important thing to remember about the resulting string
data is that it is terminated with the Null string character chr$(0).
The null string terminator is typically used in C/C++ programming,
which should give you some idea as to what languages are used to
create the API functions in the first place.
There is another technique for dealing with the string buffer's
return argument size:
1. Initialize the string buffer to just one character and call the API
function.
2. Examine the returned counter of the characters that should be in
the buffer.
3. Use the returned number to reinitialize the string buffer and call
the API again.
This involves some extra coding but it ensures that the returned
buffer is exactly the length you need, so you don't need to strip it of
trailing characters. The following code demonstrates the alternative
way of getting the data.
Dim strBuffer As String
Dim strResult As String
Dim intPos As Integer
strBuffer = Space$(1)
Page 224
intPos = GetPrivateProfileString(strSection, strKey, ''default",
strBuffer, gintMAX_SIZE, strIniFile)
If intPos > 1 then
strBuffer = Space$(intPos)
intPos = GetPrivateProfileString(strSection, strKey, "default",
strBuffer, gintMAX_SIZE, strIniFile)
End If
Registry Calls
Microsoft introduced the registry in Windows 95 and NT. It essentially
replaced INI files (although you can still find many system INI files
hanging around the Windows system directory for backward compatibility
issues). The registry is made up of three binary files that you access
through API calls. It is important to know how it works: It is set up along
the lines of the INI file. You can have an Application name (which
corresponds to the INI file name), a Section header (the same as in the INI
file), and a key and item (again the same as in an INI file). A program for
navigating the registry is supplied by Microsoft and called Regedit.exe. It
represents the registry as a hierarchy of folders stemming from 'My
Computer'. All application names, section headers, keys, and items are
located under the 'folder' VB and VBA Program Settings. The location of
the VB and VBA Program Settings folder differs depending upon the
operating system of the computer. They are as follows:
Windows 95
HKEY_CURRENT_USER\Software\VB and VBA Program Settings
HKEY_USERS\.Default\Software\VB and VBA Program Settings
Windows NT
HKEY_CURRENT_USER\Software\VB and VBA Program Settings
An NT box will also mirror the settings in your personal profile area of
the registry. Notice that the one common location on both systems is the
HKEY_CURRENT_USER area. You can use the Regedit program to
view your program's results when saving to the registry. Figure 9.3 shows
the
Page 226
register editor open to the VBA Book's General key.
The sample project (RegistryIO) supplied with this book creates,
reads, and removes the VBA Book registry entry shown above to
show you how the VBA registry functions work. We will cover
more on how it does that later in this chapter.
Figure 9.3
Windows 95 Program Settings location
Figure 9.4
Regedit dialog box
Page 227
Table 9.1: Registry root keys
Root Key Description
HKEY_CLASSES_ROOT Stores information about classes of files and objects,
associations between document types and
applications, and class identifiers used by OLE
objects.
HKEY_CURRENT_USER Contains current configuration information for the
current user.
HKEY_LOCAL_MACHINE Contains in-depth information about hardware and
software configuration on the system.
HKEY_USERS Contains software and system configuration
information that is unique to a particular user.
HKEY_CURRENT_CONFIGUsed to store general system configuration
information. Used by Windows 95.
HKEY_DYN_DATA Used to hold temporary data about current session.
Windows 95 only.
The program has an import and export feature. The export feature takes
whatever key you're on and stores it, along with its whole hierarchy all of
the way up to the root key, into an ASCII file with a .REG extension that
the import feature can use to recreate the registry on your system or any
other. Another feature is the edit menu. With it, you can add a new key or
section header and edit any existing keys.
While checking and working with the registry, you can refresh the view at
any time with the function key F5. This is handy for verifying when your
program deletes or adds items to the registry.
A final warning: Be careful in the registry. You can delete or change
information about your computer that will totally cripple it! You should be
safe if you stay in the VB and VBA Program Settings area under the root
key HKEY_CURRENT_USER.
You could move the whole thing under the Software folder by changing the line to:
Call SaveSetting("Software\VBA Book", "General", "My File", "test")
This is a very straightforward method and simple to use. You can have as many levels
deep as you like in the first argument. They will all hang under the VB and VBA
Program Settings folder in the registry, and section, key, and item will hang under them.
Reading the information is the reverse of saving it. You use the GetSetting function and
give it the exact same parameters, except it does not need the item argument. It returns
the item information in string format.
Removing the registry entry is just as simple with the DeleteSetting function. You can
remove data at any level just by supplying the name in the correct position of the
function call's argument list.
To remove a key:
DeleteSetting "VBA Book", "General", "My File"
The setting functions are all you really need to do most of the registry work you might
want. You can store a dialog box's position on screen for later use or program settings for
the next time the program runs. All of the things you did with INI files can be done with
the registry. For more exotic registry applications read up on the registry API functions
in the
Page 230
API viewer and relating books. They're easy to find because they
all have the Reg prefix. To see an example of the setting functions
in action, load the RegistryIO.dvb project file and run the
Regaccess form. The form, shown in Figure 9.6, is set up to default
to the application name, section, and key shown in the registry
examples earlier in the chapter.
You can use the Regedit program to examine the results for your
computer and experiment with keys and item data. Step through the
code one line at a time to get a feel for how the functions work.
Figure 9.6
Registry Access example form
System Calls
VBA has a robust set of functions for dealing with the system's
data on the hard drive, the date, and the time. You can find out
information about the functions, manipulate their files and
directories, and get the current time and date. What VBA doesn't
supply is functions for querying the system's environment for
information (other than time and date). API functions also have a
robust set of function calls for the hard drive, but it is easier for
most programmers to use the built-in VBA functions. Most
programmers don't bother with the API calls for files and
directories unless they have a feature that the VBA function
doesn'tor they just like using the API calls better. Table 9.2 shows a
comparison of the VBA functions with the API function calls.
Blank spaces mean that the function doesn't exist for that
environment.
Page 231
Table 9.2: VBA and API function call comparison
Function description VBA function name API function name
Directory information Dir GetCurrentDirectory
Remove a file Kill DeleteFile
Copy a file FileCopy CopyFile
Retrieve a file's length FileLen GetFileSize
Retrieve a file's date and time FileDateTime GetFileTime
Set a file's date and time SetFileTime
Retrieve a file's attribute settings GetAttr GetFileAttributes
Set a file's attribute settings SetAttr SetFileAttributes
System date Date GetSystemTime
Local time Time GetLocalTime
Computer's name GetComputerName
User's login name GetUserName
System time GetSystemTime
Window's temporary directory GetTempPath
Free hard drive space GetDiskFreeSpace
System environmental variable GetEnvironmentVariable
Format time and date data GetTimeFormat
As the above table shows, some of the system API calls that VBA doesn't
mimic are
retrieving the computer name;
retrieving the user's login name;
retrieving the true system time;
retrieving the Windows temporary directory;
retrieving a hard drive's free space;
retrieving a system environmental variable; and
formatting the time and date.
Page 232
We have supplied a sample project called WindowsOS.dvb to
illustrate these API functions. We discuss each function call below
in detail. You can load the project and run the MyComputer
subroutine to see the functions in action. Step through the code to
see how each one works as the routine builds a message box with
all of the answers.
Computer Name
The API function call GetComputerName is used to access the
computer's name stored in the registry. This function accepts a
string buffer and its length and returns a long telling you how many
characters are stored in the string buffer that is returned. A sample
call to the function is shown in the following listing.
Dim CompName As String
CompName = Space$(50)
LngResult = GetComputerName(CompName, 50)
This API is an example of the type that stores data in the argument
and returns the number of characters there.
User's Login Name
You can use the API function call GetUserName to access the
user's login name stored in the registry. This function accepts a
string buffer and its length and returns a long telling you how many
characters are stored in the string buffer that is returned. A sample
call to the function is shown in the next lines of code.
Dim UserName As String
UserName = Space$(50)
LngResult = GetUserName(UserName, 50)
This API is an example of the type that stores data in the argument
and returns the number of characters there.
Page 233
The API function call fills out all of the fields in the structure; you can then process
the data any way you like. A sample call to the function follows.
Dim sysTime As SYSTEMTIME
GetSystemTime sysTime
This API is an example of the type that stores data in a structure (object). Once you
have retrieved the data structure, you need to format the data into the form you want.
The API function call GetTimeFormat is built explicitly for that purpose. You pass it
the filled data structure with a few parameters on how you want the returned data to
look, and the function converts the raw data into the format you specified. It then
returns it in a string buffer that you pass in.
strBuffer$ = String$(255, Chr$(0))
lngResult& = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, sysTime, 0,_
strBuffer$, 254)
Page 234
The GetSystemTime API function call performs exactly like the
local time function except that it returns the actual system time
used by the computer not the local time using the time zone (there
is an API function call for getting time zone information called
GetTimeZoneInformation). You must also use the GetTimeFormat
API function call to get the returned data into the format you want,
just like with the local time data. A sample project called
WindowsOS.dvb is supplied to illustrate these API functions. Load
it and run (stepping through it one line at a time) the macro
MyComputer.
The Windows Temporary Directory
You can use the API function call GetTempPath to access the
Window's Temporary directory stored in the registry. This function
accepts a string buffer and its length and returns a long telling you
how many characters are stored in the string buffer that is returned.
A sample call to the function is shown as follows.
Dim strTempDir As String
strTempDir = Space$(50)
lngResult = GetTempPath(50, strTempDir)
This API is an example of the type that stores data in the argument
and returns the number of characters that are there. Notice how this
function call's syntax is backward from the GetComputerName and
GetUserName functions. Its string length is first, and the string
buffer is second.
System Environmental Variable
You can use the API function call GetEnvironmentVariable to
access the system's variables stored in the registry. This function
accepts the environmental variable name, a string buffer, and its
length, and it returns a long telling you how many characters are
stored in the string buffer that is returned. A sample call to the
function getting the Path variable from the system environment is
shown next.
Page 235
Dim strVarContents As String
strVarContents = Space$(255)
lngResult = GetEnvironmentVariable(''PATH", strVarContents, 255)
This API is an example of the type that stores data in the argument and returns the
number of characters there.
In the example above, you have more information than you really wanted, and
nowhere is the number of free bytes for the drive. This is because the number of
bytes available on a hard drive depends upon such variable factors as the size of a
cluster and sector. For you purists out there, you might say that it is another level
deeper at the hardware level and you would be right. There you need to consider
such factors as cylinders, heads, physical sectors, bad block mapping, and so on.
Thankfully, most programmers do not need to concern themselves with these issues
unless they are working on device drivers (not a domain for VBA programmers).
These numbers are good enough to work with in VBA. Once you have these
numbers, it is easy to get the actual free bytes on the drive. The following code
fragment shows what is needed to extract that information from the returned
information.
Page 236
TotalBytes = TotalNumberOfClusters * SectorsPerCluster * BytesPer-
Sector
FreeBytes = NumberOfFreeClusters * SectorsPerCluster *
BytesPerSector
While the API call doesn't give you back the exact number you want, it does give you
back the numbers you need to determine the number you want. Like they say, do the
math.
Conclusion
The API function calls covered in this chapter are just a tip of the iceberg. The six or
seven API function calls we covered are the ones you might use on a regular basis, but
there are literally hundreds of these calls into various corners of the Windows system.
As your applications become more and more sophisticated, you may find that the
investment in an API book is well worth your while.
Page 237
Chapter Ten
VBA Toolbox Routines
While VBA has many built-in functions for manipulating strings
and other data types, it's still up to the programmer to create
support functions for those situations that the VBA language does
not support. A VBA programmer must develop his or her own
toolbox routines that are best suited to the application being
developed. Using the basic functions supplied in VBA, the
programmer creates new utilities to speed up the process of
creating reports on screen or in a file, stripping information out of a
string for other uses, dealing with directories and paths, and many
other situations. This chapter covers several of the routines
necessary for working in the AutoCAD environment. Many of the
routines in this chapter are VBA versions of AutoLISP toolbox
routines created for The AutoLISP Programmer's Toolbox (MIS
Press). A special thanks to the management of MIS press is in
order for granting permission to use some of the same material for
this chapter.
The test functions that are supplied with this chapter on the CD
show how to use the functions. We have placed a stop breakpoint in
each test function so you can use the step next debug feature to
walk through the toolbox functions to see how they work. Many
programmers won't care:
Page 238
it's enough to know that you pass in some data and the function passes out
what you wantand this chapter is structured around that principle. We
have documented each function as to what the syntax of the function call
is and what data is returned. We have covered example situations, but they
are by no means the only way you can use these toolbox functions.
Definition of Terms
character A string with a length of one character.
control data string A string of data passed as an argument to the routine.
data item A string, substring, integer, or a real number.
substring A group of characters inside a string.
control A form control.
Toolbox Overview
The toolbox functions presented here are from actual projects and may or
may not be of use to you specifically. These functions solve a variety of
simple problems, and, like objects, are re-usable. That is, you can copy
them into your current project and use them to help in your programming
should you find a need for the same functionality.
For each toolbox entry, we have provided a description of the syntax for
that function including its parameter list. We have then described the
arguments supplied as parameters in more detail and have detailed
conditions under which the utility is expected to function. We have also
itemized the returning value or resulting action. Next, we have described,
in general terms, the situation in which the utility might be used and have
provided the examples on the CD that is supplied with the book.
The selections on the opposite page are presented in alphabetical order by
each function's description header.
Page 239
Situation:
A common way of transferring data into a routine from a data file is to
place the data on a line with a delimiter between each piece of data. The
delimiter can be any legal ASCII character, but you want to use a
character that would not normally appear in the data. Many programmers
use a comma or the pipe symbol ( | ). Once you read in the line of data to a
text string you can extract a specific data item from the string using the
position in the string record. This means you must know what each
position in the string is used for. The routine will return the string data
item from the requested position in the form of a string.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
PARSE_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A series of message boxes showing the position and the content of each of
the sub-strings being parsed.
Page 240
Situation:
Both the AutoLISP and BaseLISP (Cyco Workflow) languages view the
single back slash as a flag to treat the next character literally instead of as
a special character. This means that if you are creating a line that is going
to one of these languages for processing, you need to fix it with double
back slashes. A common situation is the string path for a file name. In
VBA, it needs only single back slashes, but in the other languages, it
needs two. This function takes a string and doubles its back slashes. You
can then use it by jamming it down to AutoLISP or to BaseLISP through a
DDE connection to Cyco's Workflow.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
BACK2_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A message box showing the results of processing both types of strings
(one without any back slashes and one with).
Page 241
Situation:
When you have a string that you know has a path in it but you're not sure
that the path ends in a directory separator, this function takes the string
and returns it with the separator added. This is typical when you have a
directory path in an INI file or the registry and you need to make sure you
can use it with a file name.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
BACKSLASH_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
A message box showing the results of processing both types of strings.
Page 242
Situation:
Each AutoCAD object in the object model has an entity type number
associated with it. Autodesk has supplied a slightly English version of the
number using enumeration but each type has the characters ac as a prefix.
This function takes the entity object and translates the entity type into
plain English. Instead of acCircle, you would get Circle for a circle entity
object. This makes checking in your code a little easier to read and debug.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
ENT_TEST in the immediate window of the Visual Basic Editor. The
main work is being done in the form's btnGetObj_Click procedure. We
have provided no stop in this example because it would leave you in the
VBE window when AutoCAD wants a response on the AutoCAD
graphics screen. It's too confusing unless you want to try it yourself.
CD Example Result:
A message box stating the entity object's entity type in plain English.
Page 243
Situation:
Many times you will need to determine that a path is present in a file
name. Checking to see if a colon or back slash is present in the string is
one way of doing it. The function can also be used to determine that a
string is in the correct format for parsing. It is always a good idea to check
your data before processing it. You almost never have full control of data
being read into your routine. When you expect a string with five items
separated by delimiters, you can use this function to double check that the
line you are about to process has the correct number of delimiters in it.
Then you can make a programmatic decision on what to do with
erroneous data lines.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
COUNT_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A message box appears telling you the results of the test.
Page 244
Situation:
When you're manipulating files on the system it is sometimes necessary to
move or copy a file to a directory you are not sure exists. There are
functions to determine the existence of a path, and the MkDir function
will create a new directory but only when the parent directory of the new
directory already exists. This function allows you to give the whole path
you want created, and it will create the whole path for you whether part of
it already exists or not.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
PATH_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
The path C:\TEMP\VBA is created on your hard drive whether you
already had a C:\TEMP or not.
Page 245
Situation:
The cosmetics of your program's interface with the user counts more than
you might guess. A program that gets the jobs done but does not present
the solution to the user in a professional format often is judged as an
inferior program. Making your program intelligent when it goes to print
out a sentence can make the program seem superior. Legal word codes are
as follows:
_1 returns ''s" or nothing ("")
_2 returns "are" or "is"
_3 returns "were" or "was"
_4 returns "have" or "has"
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
PLURAL_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A message box showing the sentence using proper tense on the words that
relate to the number of items found.
Page 246
Situation:
Certain situations must stop the process of your program. Many a program
depends upon data from an ini, cfg, or dat file. This function issues a
message box for four of those situations dealing with files and has a trap
for unknown error codes. You can add your own to the function. The
supplied errors are
1 - A missing file.
2 - The file could not be opened.
3 - A missing section header in an INI file.
4 - A missing key in an INI file.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
FATAL_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
Message boxes showing whether the specified files were found. The file
not found calls the fatal error subroutine and ends the program.
Page 247
Find a File
Syntax: Findfile (string).
Arguments: Where the string is a file name and extension (with or without
an explicit path).
Conditions:The string must be in string form.
Returns: The file, extension, and path in one string when found or
NULL when not found.
Situation:
This function mimics the Findfile function in the AutoLISP language,
which searches down the AutoCAD search hierarchy looking for the first
occurrence of the file it finds. The only difference between it and its
AutoLISP cousin is that a NULL is returned instead of a nil when the file
is not found. This allows you to use the IsNull function to test the returned
value.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
FINDFILE_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
Message boxes showing whether the specified files were found.
Page 248
Situation:
When loading a listbox control with data, many programmers want to then
display a default item in the listbox. You can accomplish this by storing
the default line (usually stored in an INI file or in the registry) and then
matching it in the listbox data once it is loaded. Should the line be missing
from the listbox data, a 0 ensures that the first item in the list is displayed.
This function accomplishes the task of determining what the index
number of the item is or returning the default 0 when it can't find it. The
more data in the listbox, the slower the search.
CD Example:
There is no example for this function. The toolbox also has a VB version
of this function called LST_MEMB_IDX. To build your own example,
create a form and give it a listbox control. In the UserForm_Initialize
subroutine, load the list and call this function giving it a default line item.
Take the returned value and use it in the Setfocus method for the listbox.
Page 249
Situation:
When working with other applications from VBA in AutoCAD, it's a
good idea to check to see if the other application is already launched
before you send information to it. That way, you can launch the
application when it is missing and not have your program crash. This
function uses Windows APIs to search for the application's caption in its
application window. There are many windows in the background, so the
function has to churn though them all checking their captions for a match.
The example searches for the AutoCAD Text window because it must be
there for VBA to be running. You can substitute any application's caption
and search for it instead. API functions were discussed in more detail in
Chapter 9.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
FIND_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A message box stating the results of the search (in this case, it found the
application window).
Page 250
Situation:
Many times you will wish to show the user a selected point on the dialog
box. You must break up the point into its X, Y, and Z components, convert
them to strings, then build the new string point for display. These steps are
straightforward enough, but it is always nice to display the point in the
current drawing precision format. This function takes the string containing
the partial point and returns the point in the current drawing precision
format (assuming that you supplied it to the function). The precision is
supplied as an argument instead of being coded into the function to give
the function more flexibility. This way you can force a precision that is
not the current drawing precision.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
FORMATPNT_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
The point string is built and displayed in a message box. See the test
routine to view how the point was assembled.
Page 251
Situation:
Forget zoom previous. This function allows you to save the current view
corner points for later use with the zoom command. This is handy for
situations in which you zoom around, do some other work, then decide to
undo the work but leave the zoom display in the new position. Simply
grab the current view corners before working, then use the points to
restore the view at any time.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
VIEWCORNERS_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
A dialog showing the lower left and upper right corner points. This test
routine shows you how to build string points from arrays and how the
Format function comes in handy.
Page 252
Situation:
Sometimes you need to grab just the extension from a string and use it to
build another file. This function gets the extension for you. This function
(unlike the RightToken function) returns an extension without the period.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
GETEXTENSION_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
A dialog box showing the returned extension.
Page 253
Situation:
There are many ways of getting a path from a file name. This is one of
them. In many situations you already have a string containing a file name
(or it's easy to obtain), but you want to get the path to the file name from
another string. This function was designed for exactly that situation. One
important note here is that you must assume a back slash is in the path
string. There is one situation that can occur in legal data but this function
can't trap. That situation is when you have a path in a string such as
'C:Autoexec.bat'. There is no back slash in the string path, but DOS will
accept this path and use it (in certain situations). The simplest function for
retrieving paths that covers this situation is the Get_Path function, which
is covered later in this chapter.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
GETSUBSTR_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A message box showing the path.
Page 254
Situation:
Sometimes you need to grab just the path from a string and use it to build
another file. This function gets the path for you. This function (unlike the
Token function) always returns a path even when there is no back slash in
it. For example, C:TEMP.DAT).
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
GETPATH_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A dialog box showing the returned path.
Page 255
Situation:
This is another way of stripping the path off a string. The difference
between this function and the Token function is that this function returns
everything in the string starting from the string2 substring (a file name) to
the end of the string. In this case, you know that the file name might have
a path on it, and you want to remove the path and keep the file name and
extension. This function was designed for exactly that situation.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
GETRSUBSTR_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
A message box showing the file name.
Page 256
Situation:
Used to create columns in single column list boxes. It's kind of crude
compared with using multiple columns but handy for those times you
choose to be different.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
PAN_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A dialog box showing the string before and after the padding. Try
changing the second parameter to a number smaller than the length of the
string and see the results.
Page 257
Situation:
Many API calls need a predefined string buffer. They take the string
buffer and place the data into it with a null character [chr$(0)] terminator
at the end of the data. Many of the string functions cannot deal with a null
terminated string. This function lets you pass in the string buffer with the
null terminator, and it returns a string that the string functions can work
with.
CD Example:
To test the function, open any drawing, load the WindowsOS project, and
type MYCOMPUTER in the immediate window of the Visual Basic
Editor.
CD Example Result:
A dialog box showing your computer's settings. This example is part of
Chapter 9. Try stepping through the subroutine and viewing the string
buffers for each setting. Watch how they change from a fixed-length string
buffer to a smaller string once they have been sent to the StripTerminator
function.
Page 258
Situation:
Handy for replacing delimiters with different ones. Replaces all
occurrences of the search character with the replacement character in the
line and returns the line.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
REPLACECHR_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
Commas in a string are replaced with pipe symbols. This is shown in the
message box that appears in the test routine.
Page 259
Situation:
Used for accessing data in the Windows directory from your project. This
function is actually a wrapper function for the API call
GetWindowsDirectory. For more API call information see Chapter 9
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
GETWINDOWSDIR_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
The Windows directory string that is returned to the test routines is
displayed in a message box.
Page 260
Situation:
Whether you're in VBA or AutoLISP or any other programming language,
it is a good idea to entertain the users whenever the program leaves them
to do some lengthy computations. This practice lets the user know that
something is indeed happening and that he or she should let the program
keep running. Besides giving a message before you leave, it is a common
practice in AutoLISP to leave a spinner spinning at the command line.
You can't do that in VBA, and the spinner control for the dialog box is
used for incrementing countersnot showing a spinner. This routine takes a
character and shows it on a label of the form with the word ''working"
before the character. The routine passes back the next character that
makes it look like it is spinning. Passing the routine nil starts the routine
with the default character.
Note: Most processing that needs a spinner occurs in a loop of some kind.
Try to space the spinner routine so that the spinning characters appear to
be evenly spinning. This sometimes means that you need to space the
spinner routine in the program unevenly in the code flow to get an even
look on the display.
Page 261
CD Example:
To test the function, open any drawing, load the Toolbox project,
and type SPIN_TEST in the immediate window of the Visual Basic
Editor.
CD Example Result:
A label on a form that shows the word ''Working . . . " with a
spinner on the end.
You can check out the code in the start_click procedure of the form
to see how to use the spinner in a loop.
Page 262
Situation:
You might frequently want to process data from a file or table and write a
report or some other data using the file name with your own extension
attached. This function takes the path, file name, and extension and
returns just the path and file name. The path is an optional part of the
string. Only the period needs to be present for the function to find the
extension. This function is used most when processing block table
information. Autodesk stores the extension on external references when
the Xref is selected using the dialog box. Since you cannot presume that
the extension is not there, it is best to run each Xref obtained from the
table through this function to make sure that the extension is stripped off
the file name.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
EXTENSION_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
The new file name is returned without the extension. The test routine
shows a message box with the original drawing name and the name
missing the extension.
Page 263
Situation:
This is perhaps the easiest way of stripping the path off a string. The
difference between this function and the others documented in this chapter
is that you do not have to know the file name or path to get the file name
back.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
SPLIT_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A message box showing the file name.
Page 264
Situation:
It is always a good idea to check to see if a control exists before you try to
initialize it. If it doesn't exist, you will get an error. VBA lets you create or
remove controls on the fly as the program runs. This function allows you
to check before you try anything with the control.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
CONTROL_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
A True result causes the test routine to show a message box.
Page 265
Situation:
It's always nice to know that a file you want to open is out there before
you go to open it. You must explicitly supply the path and extension along
with the file name to the function. There is no extended search.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
ISFILE_TEST in the immediate window of the Visual Basic Editor.
CD Example Result:
Message boxes showing whether the specified files were or weren't found.
Page 266
Situation:
At times you will need to manipulate data strings from one listbox control
to another. Many times you will want to verify if the string is already in
the listbox's list so you can avoid placing duplicates on the list. This
function allows you to check the listbox first before adding a string and
determine whether you should add it. Naturally, as the list grows, the
speed decreases. Therefore, you should avoid using this function with
very large lists unless you are willing to take the speed penalty.
CD Example:
To test the function, open any drawing, load the Toolbox project, and type
LIST_TEST in the immediate window of the Visual Basic Editor. Try
both a lowercase b then an uppercase B to see the differences.
CD Example Result:
A lowercase b gets a message box stating that it is not in the list (it isn't
because the search is case sensitive). The uppercase B gets a message box
stating that it was found in the list.
Page 267
Chapter Eleven
VB versus VBA
How does VBA stack up against VB? Remember that VBA is a
subset of VB (actually VB is an add-on to the VBA core). As a
consequence, VBA does not have all of the abilities of VB. In this
chapter, we will explore those differences and explain how VBA
fits into the AutoCAD development scheme of things. We will then
turn our attention to building help files for your applications. Help
files are often the best way to avoid technical support phone calls
for sophisticated applications. We will discuss the differences
between the help systems of VB and VBA along with how to create
help files.
As you've already seen, VBA is a powerful tool, but there are
others that are even more powerful, such as VB and ObjectARX.
These tools are not supplied with AutoCAD; you'll have to
purchase additional software and learn more skills for them to work
properly.
Page 268
Figure 11.2
Memory differences
Porting Issuesfrom VB to VBA
Moving code from VB to VBA can be very simple or incredibly
difficult. It all depends on what the program does. If it has a form
with data controls for database integration, then it will be difficult.
VBA is missing some of the more robust data controls for database
integration. That means that you will need to try to reference the
ActiveX controls inside VBA. Not all controls will import into
VBA. Another stumbling block is the form itself. A VB form will
sometimes transfer to a VBA user form, but the controls will have
only VBA properties and methods associated with them. This
means that a control such as a text box will lose all of its DDE
linkage methods going from VB to VBA because VBA does not
support those methods. You need to check each control on the VB
form before transferring to make sure that you are not using some
method or property that is not supported in VBA.
Page 274
The two languages' terminology are slightly different and can cause
some problems. VB calls its forms by the name Form while VBA
calls its form a Userform. This means that any procedure that
passes a form in VB must be adjusted accordingly in VBA.
Remember that you will not have the implied reserved word ThisDrawing in VB. You will
need to always use it in front of the model object. Once you use these lines of code in VB, the
AutoCAD object model is exposed to you and you can use VB code just as if you were in
VBA. This gives you an advantage when you need to interact with the command line or use
sophisticated database controls.
The above example uses no error trapping and assumes that the AutoCAD application is
already running. This would cause an error if AutoCAD were not already running. The code
below shows the proper way to check first, then try to recover before proceeding. We have
shown a simple print to the debug window to illustrate that the code behaves the same in VB
as in VBA once the connection is made.
Public Sub Attaching ()
On Error Resume Next
Dim Application As AcadApplication 'declare the application object
Set Application = GetObject(, "AutoCAD.application")'set it to AutoCAD
If Err.Number <> 0 Then ' Was AutoCAD running?
Err.Clear ' No, clear the error
Set Application = CreateObject("AutoCAD.application") ' Try to launch
If Err.Number Then ' Did it launch?
MsgBox "Unable to launch AutoCAD session." ' No - tell the user
End ' bail out
End If
End If
Page 276
Dim ThisDrawing As AcadDocument ' declare the active document object
Set ThisDrawing = Application.ActiveDocument ' set the active document
Dim olay As AcadLayer ' declare an active layer object
Set olay = ThisDrawing.ActiveLayer ' set it
Debug.Print olay.Name ' display various properties
Debug.Print olay.Color
End Sub
A VB 5.0 project for testing if you like. It is called Attach.vbp. Load it into VB 5.0 and test
run it from the immediate window by running the macro called Attaching.
VB and VBA Help
The Windows help engine has been available for AutoLISP programmers since Autodesk
tapped into it late in the life cycle of Release 12. VB and VBA can also access the Windows
help engine with the addition of context-sensitive help for a form's controls. Each language
has a slightly different way of accessing the help engine, but they all use a Windows help file
that you can create. You also have the ability, should you need it, to tap into Autodesk's
ACAD.HLP file. This section covers accessing help in VBA, along with a few techniques you
can use in VB or VBA. We have defined a project to illustrate the techniques and supply a
detailed listing of all projects included on the companion CD-ROM.
VB Help versus VBA Help
Both languages use the WinHelp API call to deliver help. Both have context-sensitive help for
controls and forms and both can use a control's HelpControlId property to directly access a
topic via the function key {F1}. The only basic difference between them is that VB has an
extra control property for accessing Win95's What's This help tips, which VBA does not have
on its controls. We have documented the WinHelp API call here in the same manner as the
API calls in the API chapter.
Page 277
Accessing VBA and VB Help
You can define a default help file for your project in both VB and VBA. You can define
VB's default project help file from a dialog called from the Project/Project Properties
menu item. The dialog is shown in Figure 11.3.
Figure 11.3
ProjectProject Properties window
The VBA project's property dialog box is almost the same and it is also used to set the
default help file for your project. The dialog is shown in Figure 11.4.
Figure 11.4
HelpProject Properties window
In both languages, you must select a default help file for use with the function key
{F1} help, and you can set a default Context ID for the help file. This allows your
application to default to a Table of Contents page should you call for help from a
control that doesn't have a context ID set or has an invalid ID set.
Whether you use the context-sensitive help feature or you just want to call help, you
need to use the WinHelp API. This API takes a help file name and a topic and displays
the help on the subject. Should the topic be missing or misspelled, you will get the
default subject. This is the function declaration on one line of code that is placed in
your declaration section.
Declare
Function
WinHelp
Lib ''user32"
Alias
"WinHelpA"
(ByVal
hwnd As
2042015b45d2b5416108e486be44e8bc. Long, ByVal 2042015b45d2b5416108e486be44e8bc.
gif lpHelpFile gif
As String,
ByVal
wCommand
As Long,
ByVal
dwData As
Long) As
Long
The four parameters control what kind of help you are requesting from the WinHelp
engine. Those arguments are shown in Table 11.3, below.
Page 278
Table 11.3
hwnd The window handle of the application requesting the help or the ID
control or window about which help is requested when the wCommand
parameter is either HELP_CONTEXTMENU OR HELP_WM_HELP.
lpHelpFile The application's HLP file name. May have a greater than sign (>) and
a window name specified after it. If so, the help is displayed in a
secondary window. The secondary window name must be specified in
the Windows section of the HPJ file.
wCommandThe Windows help system command. See Table 11.4, below, for
details.
dwData Additional data provided for the wCommand parameter.
The wCommand parameter tells Windows help which help command you
want to use. These commands must be defined in your declaration section
as global constants. They are shown in the command column used by the
help system table.
Table 11.4
Command Value Description
HELP_COMMAND &H102&Executes the help topic. The dwData parameter
is used to point to the requested topic in the
file.
HELP_CONTENTS &H3& Windows 3.x command: displays a Contents
page in your HJP file.
HELP_CONTEXT &H1 Displays the topic that is associated with the
context ID specified by the dwData parameter.
HELP_CONTEXTPOPUP&H8& Uses the topic that is associated with the
context ID specified by the dwData parameter.
HELP_FINDER Windows 95 and NT command: displays a
Contents page in your HJP file.
HELP_FORCEFILE &H9& Ensures that the proper help file is being
displayed.
HELP_HELPONHELP &H4 Windows 3.x command: accesses the Windows
help file on Windows help. Win 95 and NT
users should use the HELP_FINDER
command instead.
Daunting, is it? Well, the good news is that VBA does all of the work
when it comes to context-sensitive help (once you've set up the context ID
for the control) and you need to use only the HELP_COMMAND
command and the jumpid option for your online help. We explain other
techniques in detail later in this chapter.
Much of the diverse material presented above is used in writing help for C++ applications; you need no
yourself with it since the context-sensitive help and the HELP command with the jumpid can handle an
might want to supply to the user. The additional material is presented only so you can get a feel for the r
environment that exists on the next level of development.
On-Line Help
You usually initiate this type of help by selecting a button or menu item. You write your code to use the
API using the HELP_COMMAND option with the jumpid topic. The jumpid is simply a mechanism th
HELP_COMMAND uses to find a topic in your help file. The topic is a string with no spaces that you s
your help file. An example for a call to help using this syntax is below:
2042015b45d2b5416108e486be44e8bc. WinHelp 0, ''MyHelpFile.hlp", 2042015b45d2b5416108e4
gif HELP_COMMAND,_"jumpid("MyTopic")" gif
Figure 11.5
HelpProject dialog box
You then fill out the location and help file name in the Help File
Name field and give the project context ID default number in the
Project Help Context ID field. This default is used whenever help
is called for a subject that is not present in the help file. Usually the
default is the table of contents for the help file, but you can set it to
anything you wish. Unfortunately, you can do this only at design
time. There is no mechanism to set the program's help file at
runtime. This means that you must select the location and help file
at design time, and you can't change it at runtime. Another problem
is that your VBA program does not use the search hierarchy or the
help file registry setting to find your help file. This means that you
must explicitly give the path along with the file name in the
project. That means having a standard setup for all machines in the
organization to keep maintenance simple. The Help project
supplied with the book has context-sensitive help IDs attached to
the poplist and Help button. Actually, all of the buttons have
context-sensitive help IDs of 0 (meaning the table of
Page 283
contents for the project help file). This is the default ID for any newly created control on the form.
By creating a table of contents in the help file with an ID of 0, you automatically set up the default
for any new control on your form.
Accessing AutoCAD Online Help
Autodesk states that it does not use context-sensitive help IDs in its AutoCAD help file
(ACAD.HLP). This means that you cannot tie into its help file using a context-sensitive help ID from
your form, but you can still tie in using the jumpid with the HELP_COMMAND method. The Help
project supplied with the book has examples of this method of accessing AutoCAD help. You must
build your API call using the correct path and help file name along with the correct topic for the
jumpid. We have shown an example of this method in the following listing.
param = "jumpid(Plot)"
WinHelp 0,''D:\PROGRAM FILES\AUTOCAD R14\HELP\ACAD.HLP", HELP_COMMAND, param
The code shown above calls the help illustrated in figure 11.6. The topic in the jumpid is where you
must guess and experiment. The few topics that are supplied in the list in the help project were
simple to guess. The plot command uses a topic of plot, the line command uses a topic of line, and
the arc command uses a topic of arc. You must guess because there is no documentation on the topics
in the AutoCAD help file. You can see the code that builds the AutoCAD help string in the
btnHelp_Click subroutine of the Help project.
Figure 11.6
AutoCAD Command Reference window
Page 284
Building a Help File
Building a help file is a very complicated and tedious task. The
task is made easier by purchasing a program for creating Windows
help files. ForeHelp by ForeFront of Boulder, Colorado, is one
such program. You can contact the company at (303) 499-9181.
The help file created for this book was created in version 2.95 of
ForeHelp. This is not the only program on the market to generate
Windows help files, but it does have the features you need to create
simple or complex files. Features included in any good help file
generator are listed below:
HyperLinks
Context IDs
Rich text file import
Topic Properties
Targets
Alias
The VBA Help Project
This project contains examples of both context-sensitive help and
calling for online help using the jumpid method. It also contains
help on all of the other projects included in this book. Information
on techniques, useful code fragments, miscellaneous tips for each
project, and part of one of the chapters is included in the help file.
The VBA Help project dialog box is shown in Figure 11.7.
Figure 11.7
VBA Help dialog box
You need to change the path in the help project of the VBA and the
AutoCAD help (if it is not at its default location) folder before
using the program. The VBA help file path for context-sensitive
help is found in the project's properties dialog box shown in Figure
11.8.
Page 285
Figure 11.8
Help Project Properties dialog box
The steps to change the VBA help file path for using context-
sensitive help are as follows:
1. Open the help project in whatever folder you placed it.
2. Select the Help Properties . . . menu item from the Tools menu.
3. Use the Browse button . . . next to the Help File Name edit box
to select the VBA.HLP file from the project folder.
4. Select the OK button and save the project.
The VBA help file path must be adjusted to your system for online
help to work. The steps to change that path are as follows:
1. Open the help project in whatever folder you placed it (unless it
is still open).
2. Double click on the frmHelp item of the Forms folder in the
project window.
3. Double click on the Help button in the dialog box.
4. In the subroutine Get_On_line_Help (beneath the btnHelp_Click
subroutine), change the string D:\VBA BOOK\COMPARE\ to a
string containing your path to the VBA.HLP file (i.e.
C:\HELPFILES\).
The help project assumes that the AutoCAD help file is in the
default location that Autodesk places it. Should you have changed
the location of the AutoCAD help folder path, you need to change
the program. The steps for changing the AutoCAD help file path
are as follows:
5. Open the help project in whatever folder you placed it (unless it
is still open).
Page 286
6. Double click on the frmHelp item of the Forms folder in the
project window.
7. Double click on the Help button in the dialog box.
8. In the subroutine Get_On_line_Help (beneath the btnHelp_Click
subroutine), change the object ThisDrawing.Application.Path &
''\HELP\" to a string containing your path to the VBA.HLP file.
(i.e. C:\HELPFILES\)
Now you can use the help project to experiment with the various
help concepts covered in this section.
On-Line Help
There are several methods in the help project illustrating how you
can use help in your project. On-line help is attached to the Help
button and is controlled by the pop list. You need only to select an
item from the list, then the Help button to view help on the subject.
The list is set up as a double column list with the help topic column
showing and the help file name column hidden. When the Help
button is selected, the item is used as the topic for the help file and
the hidden column entry. This technique is used to show you how
you can use multiple help files from one project. The pop list
contains several different help topics that exist in the AutoCAD
ACAD.HLP file and the VBA Help file provided with this book.
One pop list item is there to illustrate how the WinHelp API
handles a topic that does not exist in the help file. Try the Missing
Topic item to generate the WinHelp error message shown below in
Figure 11.9.
Figure 11.9
Windows Help topic error message
The message appears, then you are put into the help file's content
area. This happens because the WinHelp API makes the contents
topic in the help file the default topic when a requested topic can't
be found.
Page 287
On line help is also behind the Linetype, Plot, and VBA Help
Contents buttons, but the method coded for them does not use the
pop list. This method of accessing on-line help is done to illustrate
the more traditional way of accessing on-line help. The subroutines
are just used to set up the topic and help file names; a generic
subroutine does the work of calling the WinHelp API. Check out
the code in the buttons' click subroutines.
Context-Sensitive Help
Since the AutoCAD help file does not contain context-sensitive
IDs, only the VBA-related objects on the form have a context-
sensitive ID attached to them. You can tab around the various
objects on the form and use the function key {F1} to access their
context-sensitive help topics in the VBA help file.
Missing IDs are handled differently by the help file than missing
topics are handled by the WinHelp API. Instead of defaulting to the
content page, you are placed in the index portion of the help file.
This allows you to choose any existing topic. The Linetype, Plot,
and Done buttons illustrate this feature.
You'll set up the context-sensitive IDs at design time in the controls
of the form in VBA and at design time in the help file. The context-
sensitive ID must match for the help to be found.
VB and VBA Help Conclusion
As you've seen, help is a complex subject. However, it is a subject
you need to address to make your projects as professional as
possible. Users will have questions on even simple programs. On-
line and context-sensitive help give you the mechanism to create
concise and informative help that can reduce the calls for support.
Page 288
Chapter Twelve
Gotcha's and Tips
Every programming language has its quirks and special rules. VBA
is no exception. Some of the ways it works contrasts with other
languages you may already know; this chapter discusses some of
the interesting features you will encounter. Subjects covered in this
chapter are:
Handles data types comparison
Uses control keys to maneuver
Creates User defined Objects
Handles dates
Handles Arguments
Pointer Arguments
Short Circuit Evaluation
Access objects on the same level
Creates columns and uses multiselect in the listbox control
Deals with Variable name shortcuts
Deals with the Command line in AutoCAD
Page 289
If you don't know what some of these things are, do not despair. Some of
these are advanced topics and we will endeavor to explain them as we get
into the various nuances of the VBA programming environment.
Most of the data types are self-explanatory, except the Variant type.
Variant is very special in VBA. It can hold any of the other data types so
you can use it as a general catch-all. There are some things to watch out
for with the Variant, however. Since it can contain any type, you might be
tempted to use it almost to the exclusion of the others. This will cause
problems such as divergent data type comparison. Other disadvantages of
using it exclusively are that it takes more storage space, and maintaining
the code is more difficult because it is not obvious what type of data you
are holding.
Despite these disadvantages, there are many good uses of Variant
variables. One is for passing pointers to arrays as arguments. Since VBA
does not allow you to pass an array into a subroutine or function, you pass
in a pointer to the array, and the subroutine or function can then access the
array through the pointer. Another advantage of a Variant variable is its
ability to contain a NULL or Empty value. This is very useful when
dealing with database records since the Microsoft Jet engine returns all
data in variant form. Switching it to other data types and back would be a
waste of time. Another good use is when you're working with listbox
values. A listbox value is a variant. You need to declare a variant type to
take its value and use it. If the user has not selected anything in the
listbox, you could get a NULL value. You should check that you have a
value before proceeding.
When you are not sure what type of data your variant might contain and
you need to find out before processing it; you can use a special VBA
function to determine the data type of the data stored. The function is
called VarType. Pass your Variant variable to the function and it will
return the data type of the data in the variable.
Page 291
Two special values (Null and Empty) are used with Variant variables. To
test for those special values you must use the IsNull or IsEmpty tests. Once
you get a response from the test, you can then do further tests or process the
data.
One advantage of the Null value is how it behaves with VBA operators.
When you use an operator like plus (+) with a NULL value variable and a
string or number, you get NULL as a result. But when you use the
ampersand (&) operator with a NULL value variable and a string or number
you get the string or number back. This is what allows you to get around
the problem of divergent data types that could contain NULL values. An
example is shown below.
Dim groupname As Variant
groupname = frmGroupNames.1stGroupNames.Value
In the example, the Variant variable group name is loaded with the contents
of the listbox (1stGroupNames) selection. There is no guarantee that
anything is selected or that a value was passed. If you were to check for the
length of the variable and it contained NULL, the program would stop with
an error. The Len function must have a string passed to it. Line #1 is the
workaround to the problem. VBA binds the zero-length string with the
Variant variable. When the variable is NULL, it returns a zero-length string
that the Len function can deal with. When the variable has something in it,
a zero-length string is added, but that does not affect the original string.
This same method can be used with database recordsets. You can also use it
with numbers instead of strings. Just remember that you must use the
ampersandnot a plus sign.
Using Control Keys to Maneuver in VBA
The standard Microsoft function keys apply when you're cutting and
pasting inside the IDE and function key {F1} gets you help just like in
Page 292
any Microsoft product. There are a few special VBA control keys
sequences that can really make your life easier when programming.
Finding code in your project is one of the most difficult things
about object-oriented code. Other common useful tools are the
ability to shift (indent) blocks of code and the ability to step
through your code one line at a time in debug mode. VBA has
given you some shortcuts for accomplishing these things. These
control keys sequences are
Tab
Shift + Tab
{F2}
Shift + {F2}
Ctrl + Shift + {F2}
{F8}
We indent our code for maintenance purposes. It is easier to read
the code when it is lined up vertically. To indent code blocks you
use the Tab or shift + Tab key sequence. The process is simple. Just
highlight the lines of code, then use the key sequence. The Tab key
moves the code block to the right while the Shift + Tab key
sequence moves the code block to the left.
The {F2} key takes you to the Object browser covered in Chapter
3.
One of the most useful key sequences is the Shift + {F2} key
sequence. You use this to bounce around in the module definition,
variable declaration, or object browser. You place your cursor over
a variable or procedure and use the key sequence. VBA will take
you to the declaration of the variable or to the declaration of the
procedure. When you place your cursor over an object, the key
sequence takes you to that object's definition in the Object
Browser.
The Ctrl + Shift + {F2} key sequence returns you to the last
position of your cursor (unless you are in the Object Browser).
These features are very handy for moving quickly around the code
modules, checking that
Page 293
you have properly declared a variable within the current scope, or
seeing an object's definition and getting back to where you started.
When debugging your code, the {F8} function key is of primary
importance to you. It allows you to step into (through) your code
one line at a time. You can place a break point on a line of code
near the suspect code, and the program will halt processes at that
line in a wait state. You can then use the {F8} key to move one line
at a time through the problem area, viewing variables or watching
the flow of your program. There are other key sequences that work
with {F8}. You can see them on the Debug pull-down menu.
Or
ShowEmp "My Name", 22, #2/3/76#
The name is a string in the first position, age is an integer in the second position, and
the birth date is in the third position.
Passing by Name
You can pass the arguments into the procedure by name in any order you wish. The
method is to give the name of the argument in the procedure's declaration followed by a
colon, equal sign, and the value. For the same procedure call to ShowEmp listed above,
the call would look like this:
Call ShowEmp (bDate:=#2/3/76#, Name:="My Name", Age:=22)
Or
ShowEmp Age:=22, bdate:=#2/3/76#, Name:="My Name"
The position of the argument does not matter when you use the named argument
method.
Optional Arguments
The sample routine supplied for the two previous argument methods shows how the
third optional argument method works. Each of the examples shown will work fine
even though the height argument was not present. That is because the Optional
declaration was used for the height argument. When you want to pass the height into
the routine, just add it to the list of arguments.
There is only one rule for optional arguments. They must be declared last in the
procedure's declarations. You can put in as many as you wish as long as they are last in
the list. When you use the optional height argument, your call might appear like this:
Page 298
Call ShowEmp ("My Name", 22, #2/3/76#, 72)
Or
ShowEmp Age:=22, bdate:=#2/3/76#, Height:=72, Name:="My Name"
Notice that even though the declaration had to be last in the procedure, the call
does not have to make it last when using named arguments.
High-level languages such as C use pointers to pass around variables and arrays.
The one trap that you can fall into in VBA is thinking that you can define the
array in the calling procedure and set a variant pointer to it, then pass the pointer
to the called procedure (much like
Page 299
in C). This method simply does not work in VBA. Since there is no
pointer capability in VBA, the passed-in variant is treated as the
array, and the original array is never filled. This is because the
variant is passed-in by reference as its own variable and not as a
pointer to the array it was set equal to. This whole process exists
because you cannot pass arrays into procedures imposed by VBA
on the procedure's declaration list. Below we have illustrated a
typical situation of passing a Variant into a procedure. The called
procedure can then use variant as an array and fill it using
subscripts. The filled array is then available in the calling routine
after the called procedure is finished.
Dim Pnt As Variant
Dim Ent As Object
Call GetEnt(Ent, Pnt)
Public Sub GetEnt(Ent As Object, Pnt As Variant)
Another AutoCAD model object that uses the array of doubles as an argument for its
method is the Selectionset object. The methods are
SelectAtPoint
SelectByPolygon
SelectOnScreen
There are many more examples in the AutoCAD object model. In general, when a model
object's method needs a point, it needs an array of doubles. We have shown the syntax
for that type of operation below.
Dim ptPick(0 To 2) As Double
ThisDrawing.utility.GetEntity mobjBlockRef,ptPick,''Select a Block"
Figure 12.1
AutoCAD Object Model
Given the following code, you could access the preferences while
working on the document (same level).
Dim preferences As AcadPreferences
Set preferences = ThisDrawing.Application.Preferences
Listbox Columns
Listbox columns are one of those things that you would think
obvious, but even intermediate level programmers can stumble on
it the first time. It's not hard, but columns in lists are very flexible,
and you can do many things with them. For example:
You can have up to ten columns in a listbox.
Columns can be different sizes.
Columns can be hidden.
You can specify which column will return a value on selection.
You can load data into the columns or specify a two-dimensional
array that is linked to the listbox and its columns.
You can create a column header within the listbox.
Multiple Columns
Creating the columns in a listbox is easy. Simply enter how many
columns you want into the ColumnCount property of the listbox
object.
Column Size
Controlling the width and visibility of the columns is not as
obvious, even though there is a ColumnWidth property on the
listbox. The ColumnWidth property uses points per inch (much like
a font) to measure the width. When you set a column position to 0,
the column is not shown. If you do not specify a width, the default
is to split up the columns into equal sizes. The minimum size is 72
points, but you can make them smaller. A sample of column widths
for a listbox with three columns is shown below.
ColumnWidth | 40 pt; 40 pt; 40
Page 306
It should be noted that you could use inches instead of points in the
above example. Consult your VBA online help for ColumnWidths
to see a more detailed discussion of this property.
Column Visibility
To make the second column invisible the ColumnWidths property
would be set as shown below.
Listbox Column Specification
One of the nice features of using columns in a listbox is the ability
to access any of the columns on a selected item. You can set the
BoundColumn property of the listbox to the column number you
want values from when an item is selected in the listbox. This
works even when the BoundColumn is set to a column that the user
can't see! This allows you to build a two-dimensional array in
which one element of the array is visible to the user but the other
isn't. When the user selects from their visible list, you can use the
invisible list to process the data item. This is a great feature for
things like associating a color in English that the user sees, but
processing the associated color number behind the scenes.
Loading Listbox Columns
There are three methods for loading listbox columns. Actually,
only one example is a method; the other two are properties of the
listbox. They are
AddItem
List
Column
AddItem Method
The AddItem method allows you to add data to a single column or
multiple columns in a listbox. Given a listbox called
lstItemWindow with a ColumnCount of 1, the code to load an array
of data into the listbox would look like that shown below.
Page 307
Dim intI As Integer
With IsItemWindow
For intI = 0 To UBound(SampleArray)
.AddItem SampleArray(intI, 0)
Next intI
End With
Notice that the only difference between the single loading example and the one
for two columns is the line of code marked in italic. You must first use the
AddItem method to put the data into the first column, then immediately use the
Column property to add the next piece of data.
List and Column Properties
Both of the above AddItem examples use a two-dimensional array (previously
constructed and loaded). There are two different properties of the listbox that
allow you to link a two-dimensional array directly to a listbox without having
to load each item individually. The List property is just one line of code as
shown below.
1stListWindow.List = SampleArray 'load using list property
Just setting the listbox property equal to the array is enough to access all of the
data in the array. The Column property behaves the same way
Page 308
except for the fact that it inverts the X,Y of the array to Y,X. When you
have need of this feature, you should use the column property instead of
the List property. The load would look like that shown below.
1stColumnWindow.Column = SampleArray 'load using Column
property
Column Headers
Column headers are available when you set the ColumnHeads property of
the listbox to True. But they will work only with a rowsources attached.
This is not a feature that can be currently used with AutoCAD.
To review the various column features, you can open the Columns.dvb
project (supplied with this book) and run the ColumnSamples macro.
Multiselect in a Listbox
There are three types of selection you can use in a listbox:
fmMultiSelectSingle to select a single item at a time.
fmMultiSelectSingle to select multiple items one at a time.
fmMultiSelectSingle to select multiple items in groups using the shift key.
Single item selection is the default, but you can select any of the three
using the MultiSelect property of the listbox. The supplied sample project
Columns.dvb has three list boxes on the form. The left one is a single
select box, the middle one is a multiselect box, and the right one is an
extended multiselect box. To review the various multiselect features, you
can open the Columns.dvb project (supplied with this book) and run the
ColumnSamples macro. After loading some data into the boxes, try
selecting in each box to see the difference in how they work.
Page 309
Chapter Thirteen
Programming Style
Style is always a difficult subject to broach because everyone
believes that his or her system is the best. Still, there are many
things about programming style that programmers can agree upon.
The reason we need a common style is so anyone trying to
maintain our code can read it and understand it. Whether you write
for multiple clients, or in-house for your company, or at home to
make your projects run more quickly, it is best to follow some
simple guidelines for your code. Good style code always has the
following guidelines in common. Some of the important common
guidelines are:
The code is always well commented.
The code is kept concise and simple.
Repetitive actions are placed in their own subroutines or functions.
Variables are defined within the proper scope, precedence, and life.
All modules have error trapping.
We can look at these common guidelines in detail in the following
pages. Whole books have been written on the subjectand this
chapter just covers some of the more common guidelines.
Page 314
The above code example tells the future programmer about the incoming argument and why
the function was created. It even gives an example of how to use the function in the calling
program. All of the comments are placed at the head of the function and are sometimes
referred to as header comments. Because of these comments, any programmer can
understand the nature of the function and plug it into any program by copying and pasting
the example code into the program to use it.
The other type of comment is the comment that tries to clarify the action of the code. One
way to use this comment is on condition statements and loops. An example of this type of
comment is shown below.
' The following code loops through all entries in the selection
set and assigns the xdata to each entity.
Dim ent As Object
For Each ent In sset 'For each entity in the selection set
ent.SetXData xdataType, xdata 'assign the xdata to the entity
Next ent
The above comments clarify what the loop is going to do. Some programmers mistakenly
think that each line in the program needs this type of comment. That isn't true (although, we
sometimes do it when commenting code for a book or article). Simple coding like setting a
variable or declaring a variable is so common that all programmers know what you are
doing; and commenting on it is unnecessary and clutters up the code. Occasionally, you
might comment on the declaration of a variable or its usage when it is not obvious why it is
being used or where it was created (if it seems out of scope). It's perfectly all right to do this
when this happens. However, you need to keep out of those situations as much as possible
because it makes it hard to understand the code when you or someone else is in maintenance
mode.
Page 316
Another example of action commenting is when you are filling in some data that you feel
might need better explaining for anyone who's working on the code later. An example of this
type of action comment is shown below. A discussion of the scope and life of a variable is
included later in this chapter.
' The following two variable definitions must be arrays of the
same size.
' The first variable holds integer values that define the types of
the data in the second variable. The first value
' (index 0) of one variable maps to the same index of the other
variable.
Dim xdataType(0 To 1) As Integer 'Define xdataType for the data types
Dim xdata(0 To 1) As Variant 'Define xdata for the data values
' The following variable assignments define the values for each
array.
xdataType(0) = 1001 '1001 indicates the RegApp name
xdata(0) = appName 'RegApp name string value
xdataType(1) = 1000 '1000 indicates a string value
xdata(10 = xdataStr 'Xdata string value
The example shown above clarifies the data type and other type of data being placed into the
arrays. Notice that even in a situation where the comments are helpful, comments on every
line make the code look cluttered. One way of making sure the clutter is at a minimum is to
use tabs and align the comments. This is a common practice and helps a lot with the look of
the code. Perhaps the single best reason to comment your code is that even though a program
might be a couple of lines long, it will someday have to be read and maintained by someone
else.
Keeping Code Concise and Simple
You would think that keeping code concise and simple would be common sense items, but
programmers often abused them. When your code starts running on, page after page, it
becomes hard to decipher and
Page 317
maintain. It is better to divide the code into subroutines or
functions and call them as needed. This shortens the routine you're
in and makes it easier to read. Some programmers argue that this
method can actually make it harder to read the code. While this can
happen, it is better to comment the action of the call to the
subroutine and move on. With good comments, it does become
easier to read the code (but not always easier to maintain). A good
rule of thumb is to keep routines no longer than one paper page
(about forty lines of code) long. This makes it easy to print out the
code when needed for review. Younger programmers are using
paper less and less as they have gotten used to the screen and the
search mechanisms in the editors. Many programmers that have
been around for a while still like to print out the code for review.
This is a matter of convenience; however you choose to go about it,
but by following the rule, your code is simple to read by either
group.
Experienced programmers sometimes laugh at simple code. They
seem to feel that because it is simple it is not useful or they feel the
need to show off their expertise with the language. This is nice for
the ego but terrible for the programmers who follow and must
maintain the code. It is far better to write a simple piece of elegant
code than to write code that is complex for its own sake. The
average programmer can maintain simple code, and the average
programmer is always the bulk of the programmers out there. An
example of code differences in VBA is collections and arrays.
Microsoft would rather we used the new paradigm of collections to
hold lists of items, but most programmers who have been around
for a long time and used VB or BASIC know how to use arrays for
that type of activity. Collections have a clear advantage over arrays
because they do not have to be declared as a specific length, and
you do not have to re-dimension them on the fly when you add data
from a data list of an unknown length (thus making them simpler
than arrays). However, using an array is more common and
therefore easier to maintain by a greater number of programmers.
Some programmers will argue (rightfully so) that all programmers
should understand the language to that depth, and they will use the
collection instead of the array to do the
Page 318
work. The thing to remember in that situation is to comment the
process for later maintenance.
Knowing when to use a complex or a simple piece of code is
important and, in certain situations, it can drive how you code. The
example of collections and arrays is a good illustration of this
problem. A common use of arrays in AutoCAD is to hold a point.
The X, Y, Z points are stored in the array and referenced by their
position in the array. This process in this situation is actually more
complex using a collection. Using an array (usually the more
complex code) is better because the collection is more complex to
code, understand, and maintain in this simple situation.
Error Trapping
Another critical style item is error trapping. Just when you think you have the
program bullet-proof, a brain-dead user comes along and breaks it. Who's
wrong in that situation, the user for trying something out of the ordinary or the
programmer who didn't anticipate the potential problem? Sorrythe programmer
is the correct answer. You should develop a style of programming that includes
error trapping in every module. This brings up another style item. Good object-
oriented programming means having only one point to enter a procedure and
one point to exit a procedure. Error trapping has to be considered as part of this
one-point entry and exit style. An example of one-point entry and exit and error
trapping is shown below.
Public Sub ErrorTest1()
Dim FileName As String
FileName = ''c:\"
On Error GoTo HandleErr
'all work goes here
FileLen (FileName)
ExitHere:
Exit Sub
HandleErr:
Select Case Err.Number
Case 53
Msgbox "File" & FileName & "not found.,_
vbOKOnly + vbExclamation
Page 323
Case Else
'Call a generic last-
ditch error handler
Call HandleErrors
End Select
Resume ExitHere
End Sub
This typical error trapping code can be installed into any routine
and modified for the type of errors expected. It uses the select
statement and labels to control the flow of the program after an
error is encountered. Notice how everything leads to the ExitHere
label whether an error is encountered or not. Situations can occur in
which it seems pointless to include code of this type, but it is good
practice to include it anyway as you never know when a procedure
might be expanded. Notice that there is a trap for errors that are not
specifically handled by the routine. That trap calls a subroutine that
passes along the regular error message to the user but allows them
to keep working. Certain critical errors will still bomb the program,
but in most cases it is a graceful way to trap an error. It also
emphasizes the fact that you must do error handling in each
procedure, but you can call out to other subroutines once you have
trapped the error in the procedure. An error-trapping example is
supplied on the CD called 'Errors.dvb'. You can experiment with it
to walk though the code and see how the error handler works.
Do You Need to Change Your Programming Style for VBA?
Whether you need to change your programming style for VBA all
depends on how you have been programming up until now. If your
style already includes the points discussed in this chapter, then you
probably don't need to change much. This assumes that you have
already been programming in an event- driven language such as
VBA. If you have been writing code in a procedure- driven
language, like AutoLISP, it
Page 324
could be a different story. You could have been doing all of the
things listed in this chapter and still have to change your
programming style. That is because event-driven programming
requires a different programming approach than procedural-driven
programming does. The differences are discussed later in this
chapter, but you need to understand that the difference is enough to
revisit these issues in a new light.
One common habit to avoid in your programming style is the use
of global variables. This can be a very tempting trap because it is
something you can declare once and then you don't have to worry
about the darn things again. When you do this, the issue of scope,
precedence, and life comes into play, and you have the added
problem of some routine changing a value of a global variable
when you don't expect it. The better approach is to use global
variables to define constants but pass arguments to routines for
processing. The routines can then declare variables locally and
process the passed argument. This is a good rule of thumb, but like
any general rule you will have exceptions where it is compelling to
use a global variable. Don't be afraid to use global variable; just
keep them to a minimum for maintenance's sake.
It is important to know that Error handling in VBA is hierarchical
in nature. That means that an error will be trapped by the first
routine that has error handling in it. If an error occurs in your
routine, and there is no trapping in your routine, the error is passed
up to the calling routine. If that routine does not have error
trapping, the program will keep handing up the error to the calling
routines until it reaches the topmost routine. If that routine does not
handle the error, VBA handles it (and this is not always pretty).
Event-Driven versus Procedural-Driven Language
The biggest difference between event- driven and procedural-
driven programming languages is finding your code in the event-
driven program. Naturally, this is from the point of view of a
procedural language programmer who has to switch to a language
such as VBA. When you
Page 325
stop and think about it, it really is not all that different. A very
complex procedural language program that has been divided into
modules can be as difficult to read as any event-driven program.
Procedural languages are linear in nature. The program has one
starting point and continues one line after another until the end of
the program. You can place calls to subroutines, but there is always
a main program that drives everything.
Event-driven languages (like VBA) are different because they can
have a common starting point (the loading of a form), but they
don't necessarily have to start with a form. You can select from a
list of subroutines to start from whether a form is present or not.
Once a form is loaded, the program waits for you to select
something on the form. When you select something on the form, it
triggers an event and the code associated with that event. The
associated code can then call other subroutines or just process and
return to the wait state of the form or end the program. There are
lots of options for just one event on one form.
Event-driven language is further complicated by the fact that you
can place all of the procedures in the form module or you can
separate them into multiple modules. This has a direct effect on
your style. What is best? That is a hard question to answer. This
subject is much like the layer and file naming argument that has
been around for years among AutoCAD users. Everyone has an
opinion and a standard; therefore there is no standard. Probably the
best solution is to separate your code in a systematic fashion. Keep
the form module holding any event code for the form. Create at
least one support module that contains routines that support the
form's routines. You can split up the support routines into multiple
modules if you like. A common method of splitting support
modules is to have a global module for generic support routines
and other modules for supporting things like registry, database,
MAPI, and Window API calls. This allows you to have support
modules that you can plug and play into any project. Many of the
support modules in this book follow that method of splitting
support files.
Page 326
Using the above examples, a few typical variable names would be:
BolAnswer for a true/false variable
VarField for a variant type
Lngx for a long counter
StrLine for a string
Use explicit data type definition at all times in conjunction with the
naming conventions. Never assume that the programmer reading
your code knows the short cuts or understands the implicit defaults
of a variable's data type definition. Some explicit data type
definitions are below:
Dim bolAnswer as Boolean
Dim varField as Variant
Dim lngX as Long
Dim strLine as string
bolAnswer = True
VarField = ''"
lngX = 0
strLine = ""
Page 328
Constants
Keeping track of constants is relatively easy. Tack 'con' on to the
front of the constant. You can add a tag for class modules if you are
worried about constants conflicting between modules. You could
use 'usr' for a user class with a 'c' tacked on after for the class
distinction before the constant tag.
conPi for Pi
usrcError123 for an error handler
Procedures
VBA names the event procedures for the formand you can't change
them (or the code wouldn't work). User-named procedures should
have the first letter of each word capitalized:
CmdOK_Click
RightToken
Chk_Plural
Fatal_Error
Page 330
Modules
Since modules are Visual Basic modules, use 'bas' as a prefix for
the module names. This also solves a problem in VBA that is not
present in VB programs. VBA does not allow a module called
Global. By adding the prefix, you get 'basGlobal', which is legal in
VBA.
basRegistry
basDatabase
basMAPI
basWindows
Conclusion
As you can see by the material covered in this chapter, style is a
complex subject. Entire books have been written on it. The material
presented here was designed to stimulate your interest in the
subject. There are several good books on the market covering
programming style in much more depth than a single chapter can.
Page 331
Chapter Fourteen
Class Modules and Objects
There are objects everywhere in programming these days.
Understanding the different types of objects can be daunting to a
programmer who doesn't have experience with them. In general, an
object is a container that is used to store data, to maintain data, and
(on certain types of objects) to respond to events. This chapter will
explore the use of custom classes in VBA. Specifically, we are
going to show how to create our own objects, and how we can
manipulate these objects into programming tools that greatly
enhance our ability as programmers to produce good applications.
Now let's take a closer look at these variables and how they are used in the class definition.
Xdatatype, Xdatavalue, AryXdata
When designing your own program object's properties, you need to consider how you intend to use
the object in your programs. In the case of the extended data object we desired to have the arrays
(named xdatatype and xdatavalue) remain exposed or public. We also desired to be able to put that
information into a list box or combo box control on a form without much difficulty. This meant
creating a two-dimensional array for the object (called aryXdata) that would contain the combined
Page 339
arrays and could then be used to load the list control in the calling
module. Loading the two-dimensional array into a list control is
then simply a matter of using the .LIST method of the object. To
make the programming even easier, it is now possible to add a
method to the extended data object that takes a list box control
pointer as a parameter and puts the contents of the extended data
arrays into the control.
Now, should the situation arise in which it is needed to load several
extended objects into a control, they can be combined into one
master object. You can use the List method of the extended data
object (or of another form control) to populate the control. The net
effect is that the tough part of the programming has been left to the
object, and our application only has to worry about manipulating
multiple extended data objects. This is one of the more difficult
concepts behind objects to understand. You can re-use objects and
build objects from other objects. It may sound confusing, but stay
with it and you will get it. (Remember how hard loops and
conditionals were to understand at first?)
You will handle the manipulation of multiple extended data objects
using a collection. The collection holds all of the extended data
objects created from all of the data found attached to a drawing
object. Why multiple extended data objects and not just one big
object holding all the data found? Because it is easier to break up
any overall extended data (that could have multiple applications
inside it) into individual child objects for each application in the
master object. That is the beauty of objects. We can manipulate the
data into smaller or larger chunks just by using multiple child
objects to store the data in and then combining them when we're
done back into a master (parent) object. The object definition that
we create must have the methods and properties to do the
manipulations, but you have to program that only once and then
use the object over and over again to accomplish the desired tasks.
Think of a master object as something that holds all of the extended
data attached to an object (an AutoCAD object, group, or a Xdata
object). You then pass the master object to a new extended data
object
Page 340
along with the requested application name and tell it to get all of
the extended data for that particular application name. You now
have just that application's extended data from the passed in master
object in your child object. The child object is added to the
collection in the main program and used with all of the other
children to rebuild a new master object when needed. You should
be starting to see how the extended data object is being used over
and over again and how it is doing all of the work for our
applications. Once the object is completely defined, our
applications have to manage only the collection(s) of extended data
objects.
AppNames
The need to be able to break down an object's extended data into
separate children objects, based upon an application's name,
prompted the need for an applications name collection (called
AppNames) to be exposed as a property of the extended data
object. Once an extended data object fills its array with data from
the passed in object, it fills the AppNames collection by spinning
through the data value array and placing only application names
into the collection (located using the group code 1001 in the group
code array).
The isolated application names allow you to easily check how
many applications were present in the extended data of the object
(a master object could have no name when no extended data is
attached to the object, or a name for each application attached). It
also lets you loop through the collection to build all of the
necessary child objects and add them to the collection in the main
program.
Another benefit from storing the application names as a property of
the object is that you can easily check for the presence of a specific
application name. In fact, the AppExist method presented with the
other methods for this object below uses its own AppNames
property to check if an application name is among the collection.
Then it simply passes back a true when it is found and a false when
it is not (more on the methods later in this section).
Page 341
ItemsCount
When an extended data object is loaded and the arrays filled, the
program then places the upper bound count of the xdatavalue array
into the ItemsCount property. This property is used for iterating
through any of the three arrays in an extended data object or for
checking to see if the object has any data. This property is set to 0
when there is no data in the object.
EntityType
The entity data object we are creating is able to process extended
data for any legal AutoCAD object as well as another extended
data object. The Entity Type is an EntityType property, just like the
one used by AutoCAD objects. (By the way, AutoCAD is an
integer that is enumerated [assigned] to a constant name [number]
for each object type. This is a bit of a problem for VBA because
you cannot enumerate your own EntityType in VBA. However,
AutoCAD does not use the number 0 as an EntityType and that fact
was taken advantage of in the object definition.) By declaring the
EntityType property as a long in the public declarations area of the
Xdata object, VBA initializes its default to a 0. The methods in our
object will not really be using the number except to provide
equality among the data passed to the routines. In several of the
methods that make up this object's definition, a Select Case
function checks for each legal AutoCAD object and then assumes
that any object that made it through is an Xdata object. Here is one
area where the error checking can be vastly improved. That is,
what happens when an entity type that is not recognized is
provided?
Methods
The methods that are in a class are the functions and subroutines
that are defined as public. Private functions and subroutines can be
accessed only by the other functions in the same module, while
public ones can be accessed outside of the module.
Page 342
Table 14.1 contains the public functions and subroutines in the extended
data class module. These are the functions that are exposed to the
application program and that do the actual work of the Xdata object. Once
again, these methods evolved over the life of the project as some were
added and some that were once thought to be useful were discarded.
Table 14.1: Public functions and subroutines in the extended data class module
AppExist Returns true if the application name exists in the AppNames
collection, false otherwise.
GetXdata Retrieves any extended data found to be attached to an object and
places it in the extended data object container arrays.
List Loads the two-dimensional container array aryXdata and displays
the data in a list control on a form.
SetXdata Attaches the extended data object contents to an AutoCAD object.
Split Reloads the data type and value arrays from the two-dimensional
array data in aryXdata. Used after the list box contents have been
modified along with the data in the two-dimensional array.
StoreAppNamesStores the application names found in the extended data container
arrays into the application names collection.
Now let's take a closer look at these functions and what they accomplish
for the manipulation of our custom extended data object. When an
application wants to manipulate the extended data, it will call these
functions and subroutines to achieve the desired results. There are only a
few, but they accomplish a lot.
To view the source code for these methods, open the extended data project
and double click on the class module in the project explorer. The project is
stored under the name XdataObject.DVB on the CD supplied with this
book.
AppExists
To better control the extended data objects collection in your project, it is
important to check to see if the application you are processing is already
Page 343
in the object. This method takes an application name and returns a
true when it is already in the object, or a false when it is not. It's
handy to know this when you're deciding whether you have to add
an application or replace an application.
GetXdata
Several different steps are employed in the class module for the
GetXdata method. It takes an AutoCAD entity object, figures out
what kind of object it is by testing the object type, transfers the
generic object into a specific AutoCAD object of the correct type,
then does an AutoCAD object GetXdata on the object. When the
supplied object is not an AutoCAD object, the routine assumes that
it is an extended data object and processes it differently. The result
is that the extended data object has its properties (container arrays
and parameters) filled.
There are two ways in which the program could be written. The
approach taken was to demonstrate the technique of using the
object type in the AutoCAD entity to assign a local variable of the
proper type, thereby establishing an early binding relationship for
VBA. The generic AutoCAD entity object container could have
been used once we established a non-zero object type. The problem
with that approach is the time of execution. The GetXdata method
would not be bound to the object until the project runs, thereby
forcing a late binding call. A late binding call means that the same
object types test takes place, but under the control of the VBA host
processor, and that takes longer. In this case, more programming
results in a faster overall execution speed. Just how much faster is
left as an exercise to the student.
List
This method performs two main activities. It is used to load the
two-dimensional aryXdata property. It also accepts an optional
argument that will list the extended data object properties to a
message box, to the immediate window (the default), or to a
control (such as a list box). Pass in D (for debug.print) to send it to
the immediate window, M to
Page 344
send it to a message box, or L, Form.listbox control, to load a
listbox or combobox on a form. One of the primary purposes of
this method is to make life easier when you're developing routines
that use list box controls and extended data, just like the object
example project will be doing.
SetXdata
Much like the GetXdata method, several different steps are
employed in the SetXdata method. The routine starts by taking an
unknown AutoCAD object, figures out what kind of object it is,
transfers the generic object into a specific AutoCAD object of the
correct type, then does an AutoCAD object SetXdata on the object.
The SetXdata method for a extended data object does not write to
another extended data object. Like the GetXdata method, this
function uses a test of the enumerated values for the object types to
establish what kind of object it is addressing. The reason is to
establish an early binding relationship with that object so that the
overall execution speed of the process is maximized. The decision
between programmer time and operator time should always fall in
favor of the operator unless the coding requirements are too
extreme.
The use of the name SetXdata and GetXdata matches the name of
the method used in each of the entity objects of AutoCAD. This is
a classic case of polymorphism at work in the VBA system. The
SetXdata method that is defined in the class module works with the
custom extended data objects we are building. The other SetXdata
method is associated with the AutoCAD entity objects. It is the
second method that writes the data into the AutoCAD database
when called from our SetXdata method. It may seem confusing to
use the same name over and over again; however, keep in mind that
the names of the routines are associated with the objects, thus
making them unique in the system. The use of the same name just
saves you from having to remember a lot of subroutine names for
each type of object you want to manipulate.
Page 345
Split
This method is the opposite of the List method. It splits the
aryXdata array property of an extended data object into its
xdatatype and xdatavalue arrays. It is exposed for rebuilding an
extended data object from a list box control after edits have been
made.
StoreAppNames
This method is exposed for rebuilding extended data objects from a
form's list box or combobox control after edits have been applied to
the data in the list. It takes the extended data objects XdataValue
container array and stores all application names in the AppNames
collection.
That concludes the public methods associated with this class
definition. If you look inside the source code for the module, you
will find additional private routines that have been defined to
further manipulate the data and perform the dirty work associated
with the extended data. The object itself does not do much other
than supply a library of routines to work with and some data to
place things in. When you use the objects, you create an instance or
copy of the object's properties. At the same time you establish a
path to the library routines associated with the object.
The Extended Data Example Project
Now let's turn our attention to using the custom object we just
defined. This application is supplied in its entirety on the CD
associated with this book under the name xdataObject.DVB and
can be loaded using the VBAMAN command in AutoCAD 2000.
There is also a drawing provided that already contains a variety of
extended data on the entities in it. The name of the drawing is
XdataObj Test.DWG, and it should be opened as well as the VBA
project for testing the functions.
To test the extended data object project, run the Xdata macro (in
bas-Global) after loading the project. Selecting the run button
launches the Xdata Control application. The dialog box interface
that will appear is
Page 346
Figure 14.1
Xdata control
shown in Figure 14.1. From this dialog box you can view and edit
all of the manipulation of variable objects and extended data
objects. The dialog box contains two tabs. You'll use the Registered
Applications tab to view all the registered application names
currently in the drawing. You can also add a new registered
application name in that tab area. The Xdata Maintenance tab is
where the extended data located for an object or group is displayed.
The use of the application is relatively simple. After starting the
entry macro (named Xdata), the dialog in Figure 14.1 is displayed.
Pick the Select Object button, then select an entity object that has
extended data attached to it. If the object selected has extended
data, it will be displayed in the list box. Otherwise, the dialog box
will be displayed again, but nothing will be in the list box.
Once data is displayed in the list box, you can select the individual
items. The column of radio button matching the data type will then
highlight type of data just selected in the list box. The value
associated with the same selection will be presented in the edit box.
If you change the value in the edit box, the updated value will be
displayed in the list
Page 347
box showing all the extended data. Use the Replace button to write
the extended data back to the list selected. When finished with all
the changes for the extended data of an entity object, select the
Update command button to put the extended data back into the
entity object.
Now let us focus more on the usage of the extended data object in
the program as driven by the functions within the interface. There
are a lot of openings left in this example that can be filled in as
needed by your own application requirements should you choose to
do so. This example also demonstrates some interesting features of
VBA, such as tabs and radio column control, that may be of
interest to students just learning VBA.
The application can manipulate extended data stored with entity
objects or with groupsthus the Select Object > and Select
Group . . . buttons. Whether you select from an entity object on the
screen or from a group in the group dialog interface, the application
loads any attached extended data from the object or group into the
extended data object using the GetXData method. The particular
GetXdata method used is the one for the extended data object. It
will load the arrays xdatatype, xdatavalue, aryXdata, the
application names collection, and the ItemsCount properties of the
extended data object. The program can then verify that extended
data does exist for the object or group selected by checking the
ItemCount property.
Once the extended data object is loaded with data, it is used to
propagate the dialog box controls. The big list box on the interface
is loaded from the object using the associated List method, and
then the Application Name poplist is loaded from the object (again
using the List method). After that the application splits all of the
data in the master object into child objects (one for each
application name in the master object). The child objects are stored
in a collection for later retrieval using the application name for the
extended data it contains as a key. That's how it is set up when
extended data is found attached to the selected object or group.
From the dialog box, the operator can add, remove, or replace
extended data items from an existing application, or even create a
new
Page 348
application name and define extended data for it using this simple
extended data editor application. Bear in mind that the Binary item
is not editable and you cannot add new binary extended data or
change any existing binary data. That is strictly the realm of
ObjectARX and the C++ language. Also, the technique for adding
a new extended data application and associated items is a little
cumbersome. But that is because this utility is intended for editing
existing extended data and not necessarily for adding new
applications and data. About the only time you would need to
create a new application is when you're testing an application
module that wants to read existing data and you have not yet
written the module to create the data.
Further usage of the extended data object is demonstrated when the
operator selects the Update button to place your changes back into
the selected object or group. The application has maintained child
Xdata objects and has rebuilt them each time you made a change to
one in the list box. It is now a matter of rebuilding a new master
object from all of the available child objects and then using that
master object to update the entity object or group that was selected
to begin with. Stepping through the code starting in the Update
button's subroutine will give you a good idea of the complexity that
was programmed into the Xdata object. This is not coding you
would want to do over and over again in multiple places in your
application.
Extended Data Object Conclusion
That covers one practical application of a class module object in
VBA programming. When building your own, remember that it is
important to design your object to store the data you need in the
form you need and to develop methods for handling that data based
on the use you are going to put the object to in your program.
These are simple rules for creating the object but the programming
of the object's behavior will be as complex as you need to make it
to do the job.
Classes are a way to store both data and program functions. In this
example, there were several exposed properties and methods. But if
you
Page 349
look at the source code for the class module there were also several
private (non-exposed) functions defined. These functions were
used internal to the object and are not available to other modules.
Our next example is different in that all the properties are
considered private, and the only way to access them is through the
methods provided.
Objects Example 2
Hole Chart
Our next example project demonstrates how objects can be used to
keep the clutter in the main application to a minimum and to allow
for expansion of the system with minimal changes in the base
application source code. This example demonstrates how one
object can contain another object. In this example, we are going to
have a base object and then a collection of these objects as another
object. There will be methods for manipulating each object type,
allowing the application to treat the collection or the individual
objects as singular items.
The application is to create a hole chart. A hole chart is a table of
locations for holes to be drilled or machined in some way. On the
drawing, each hole (or circle) is labeled with a letter or number. A
hole chart is the table that contains the label, coordinates, radius,
depth, and type of operation. This chart is typically used by the
drill operator or to develop a CNC program or for a coordinate
measurement system to verify hole locations and sizes. The goal of
this program is to allow the user to select circles in the drawing,
then label them and build a hole chart graphic. This example is
greatly simplified since the real goal is not to develop a complete
hole chart application but to use the concept to demonstrate how
object classes can contain references to other object classes.
Like all applications involving objects, the object presented in
these pages represents the result of an evolutionary process. It is
not uncommon to start with a group of properties and methods and
then add more as the project evolves. And if you find that this
application is useful and want to expand it, then you will most
likely be adding to the methods and properties of the objects. That's
okay. Objects that we define for our own use in our own
applications are not used by other processes and are
Page 350
thus under our complete control. Only when an object definition
(class) is shared among several applications can it become
hazardous to change objects. And then the problem is only if the
base functionality of the object is changed or if items inside the
object, such as properties or methods, are removed. Normally one
does not remove a component from an object once the object is
shared among several applications. And so long as new items are
the change, then modifying the base object will not change the
operation of the other applications at all.
The Holes.DVB project contains the source code for the hole
charting example. This project consists of two class modules
named Holes and Hole, a form named HoleChart, and a code
module containing the startup macro. Most of the code is
documented to allow other programmers interested in seeing
working examples of the VBA system to explore it. In the next few
paragraphs we are going to discuss the concepts behind the code.
An Object in an Object
Absurd as this concept may at first appear, it makes good sense
from a data organizing point of view. The innermost object is one
item. It can be manipulated by itself as a singular element. Multiple
objects can be kept in a list or collection, and that can be thought of
as a singular object as well. This allows our programs to reference
just one member or the whole group of members and do things
with them. In VBA, when you create a collection, you are defining
an object that can contain other objects. But if you need to do more
than just the operations provided by the collection object, you need
to create your own form of collection. From an object
programming point of view you are deriving a new collection
object using the existing collection object as a base from which to
start.
So what doesn't the basic collection object do for us already that
we could possibly want it to do? That answer is found the first time
that you try to organize previously unorganized data in some way.
The hole chart application demonstrates this in the Holes class
module definition. We want the hole chart organized as follows:
sorted by diameter first, then
Page 351
the X ordinate value, then the Y ordinate value. The add( ) method
does not do this normally, so we need to write our own version as
seen in the class module source code definition.
There are some other confusing aspects of this source code for
those who are relatively new to VBA. The class module name is
Holes. In the class module is a collection defined as public by the
same name. That is not a mistake and not something that is to be
removed. This code is a class definition. The class we are defining
is a clone of the collection object. We didn't have to use the same
name in the public variable as the class, but it makes the code
easier to work with at the applications level and easier to code
internally as the name Holes is now mapped to a collection. That
makes all of the methods that are normally found in the collection
object available to the new class we are defining.
Note the other methods inside the definition of the Holes class have
simple access to the collection methods to accomplish their own
tasks. For example, the count method accesses the count method of
the collection Holes. In the class definition source code, the name
Holes is associated to a standard collection object. When the
application program references the name Holes, it is talking about
the class Holes that includes the collection. When creating a cloned
object of this nature you must redefine all the methods that will be
used in your application or use a double nested named access to get
back to the basic object type. For example, if we didn't provide a
count method for obtaining the number of Hole objects inside the
holes collection, the application would first access the class and
then the collection to obtain the count. As it is coded, an
application gets the count as ''normal" directly from the Holes
object. Internally, the Holes object gets the count from the
collection to pass back as a result.
The Holes object, since it is our object, can also contain methods
not normally found in the collection object. The method
Draw_Holes is an example of that sort of programming. The
routine Draw_Holes loops through the collection of Holes,
extracting each Hole object one at a time and calling the draw
method for that hole object.
Page 352
The application module can now make a single call to the holes
collection and have all of the holes drawn on the screen with the
labels and centerlines added according to the hole's object drawing
definition. Between the addition of the matching methods for the
collection and the new methods added on top of the class, Holes
provides an easy way for an application to manipulate an entire
collection of Hole objects. More methods can be added to the
Holes class such as resorting the collection based on another key
sequence (such as the label or name) or placing the collection
contents into a list box control, and so forth.
The Inner Object
Our next stop is to look at the Hole class module. This is another
class definition, but it is different from what we've seen before
since all of the variables are defined as private. That means that if
we want to allow the operator to access any of the properties, we
must provide a function or method that accomplishes that task. By
shielding the data in this manner we can make sure that the
information is legitimate at all times. That means that the radius is
not 0 and that the operations that can be performed at the hole
(such as drill and tap) are of a finite number so that our other
processes (like a CNC program generator) can make sense of the
selections.
The choice of public or private is one of programmer preference.
Some applications may actually dictate that the data be public by
the nature of the object and how it will be manipulated. In most
cases it is actually better to write small routines to handle the data.
This allows for future expansion as the object is evolved into a
more advanced piece of coding.
For example, the Hole object contains methods that set and retrieve
the X and Y values as well as another set that sets and retrieves the
center point. What is the difference and why provide both options
in the first place? The reason is to provide the application with the
options of addressing the same data in multiple ways. The
application may not need multiple calling options, and in that case
the object should provide
Page 353
only those that are really required. Another reason to use methods
instead of allowing direct access to the properties is to allow for
future expansion of the module. Suppose this application was to
screen out values less than 0 for the X ordinate or it was needed to
apply a variable offset to the numbers provided. These
enhancements can be made to the object and not affect the
application that uses the object. When the object (class module) is
updated, the application continues calling the methods it always
has and continues on its way.
The Hole class module contains other methods used to manipulate
the individual Hole objects. There are routines to transfer data from
the AutoCAD circle object into the Hole private properties as well
as routines that draw the labeled hole on the drawing. The hole
label and draw routine is the most complex of all the routines in
this class as it not only draws a new circle, but it also places
centerlines through it, then attaches a label to a leader that points at
the newly created circle. This function is an excellent beginner
example of drawing slightly more complex creations under the
control of VBA.
The Hole object can be used by the Holes collection object as well
as by the application. In the application, an assignment is made
through the SET statement to a variable defined as type Hole. With
the reference to a specific hole, the methods can be called to draw
it or change the properties internally.
The Holes and Hole objects are intended for use by other
applications and not just the hole chart drawing utility. These
objects can be expanded as needed for the creation of CNC code
(simply add a method to the Hole object that creates the CNC
statement to drill the hole) or other reports and drawing utilities
that would use the hole chart information. The ability to expand
objects is important in the Hole object's case. The module as
presented here draws hole representations for drilling and tapping
only; it does not include anything for counter-boring, reaming,
counter-sinks, and so forth. If you need those representations, you
can add them to the object definition without forcing the change of
any of the applications. Instead, the applications just got smarter.
Page 354
Table 14.2: Hole object private properties
Lbl String Label at hole.
Dia Double Diameter of hole.
X Double X ordinate of center of hole.
Y Double Y ordinate of center of hole.
Z Double Z ordinate of center of hole.
Typ Integer Hole type code number.
Default_Typ Integer Default hole type code number.
Figure 14.2
Hole chart dialog box
The circle data found will be presented in the list box of the
display. The X, Y, Z, and Diameter values are taken directly from
the circle objects selected in AutoCAD. The holes are sorted in
order by diameter, then X, then Y.
When circles are first selected in this application, they have no
label and are assigned a standard default operation code. To change
any of the values, select the line to change in the list box. Then
change the values in the edit box windows provided. After making
changes to an item in the list it is important to remember to select
the Change to list button to write the values in the edit boxes back
to the list display.
Other buttons to press include Round all, which will round the
values of all real numbers (X, Y, Z, and Diameter) to the precision
set in the popup list box next to the button. Labels 1,2,3 . . . will
automatically label all holes with a sequential number starting with
1 and incrementing by 1. Redraw holes will erase the selected
circles, then redraw them using the label and centerline inclusive
method from the Hole object. Finally, Draw Chart will accept the
input of a point, then generate a chart from the data in the list box
using the current default text height to control the size of the chart
rows and columns.
Page 357
Index
2042015b45d2b5416108e486be44e8bc. Special Characters and
gif Numbers
2042015b45d2b5416108e486be44e8bc.gif* (asterisk), 123
2042015b45d2b5416108e486be44e8bc.gif@ (at sign), 123
2042015b45d2b5416108e486be44e8bc. ACAD_MLINESTYLE
gif dictionary, 133
2042015b45d2b5416108e486be44e8bc.gifAcadPreferences object, 65
2042015b45d2b5416108e486be44e8bc. AcAttributeModeConstant
gif mode, 165
2042015b45d2b5416108e486be44e8bc. AcAttributeModeInvisible
gif mode, 165
2042015b45d2b5416108e486be44e8bc. AcAttributeModePreset
gif mode, 165
2042015b45d2b5416108e486be44e8bc. AcAttributeModeVerify
gif mode, 165
2042015b45d2b5416108e486be44e8bc. acBlockReference constant,
gif 159
2042015b45d2b5416108e486be44e8bc.gifAccess (Microsoft), 5
2042015b45d2b5416108e486be44e8bc.gifActive property, 72
2042015b45d2b5416108e486be44e8bc.gifAngleToString function, 79
2042015b45d2b5416108e486be44e8bc.gifapplication(s).
2042015b45d2b5416108e486be44e8bc.gifSee also projects
2042015b45d2b5416108e486be44e8bc.gifassembling, 201203
2042015b45d2b5416108e486be44e8bc.gifloading, 204
2042015b45d2b5416108e486be44e8bc.gifArc object, 10
2042015b45d2b5416108e486be44e8bc.gifArea property, 90
B
2042015b45d2b5416108e486be44e8bc.gifbackslash (\), 240, 241, 243
2042015b45d2b5416108e486be44e8bc.gifBeginClose function, 76
2042015b45d2b5416108e486be44e8bc.gifBeginOpen function, 76
2042015b45d2b5416108e486be44e8bc.gifBeginPlot function, 76
2042015b45d2b5416108e486be44e8bc.gifBeginQuit function, 76
2042015b45d2b5416108e486be44e8bc.gifBeginSave function, 76
2042015b45d2b5416108e486be44e8bc.gifBlocks property, 72
C
2042015b45d2b5416108e486be44e8bc.g C programming, 223,
if 298299
2042015b45d2b5416108e486be44e8bc. C++ programming, 10, 272,
gif 347
2042015b45d2b5416108e486be44e8bc.gifAPIs and, 216, 223
2042015b45d2b5416108e486be44e8bc.gifCirLin object, 49
2042015b45d2b5416108e486be44e8bc.gifclass(es)
2042015b45d2b5416108e486be44e8bc.gifsymbols for, 57
2042015b45d2b5416108e486be44e8bc.gifClear method, 108
2042015b45d2b5416108e486be44e8bc.gifcollections.
2042015b45d2b5416108e486be44e8bc.gi
f See also specific collections
2042015b45d2b5416108e486be44e8bc. basic description of, 12, 53,
gif 8385, 102103, 300302
2042015b45d2b5416108e486be44e8bc.gifdrawing tables as, 132133
2042015b45d2b5416108e486be44e8bc.gifnaming, 327
2042015b45d2b5416108e486be44e8bc.gifthe object model and, 8385
2042015b45d2b5416108e486be44e8bc.gifworking with, 120
2042015b45d2b5416108e486be44e8bc.gifcontrol(s)
2042015b45d2b5416108e486be44e8bc.gifbasic description of, 10
D
2042015b45d2b5416108e486be44e8bc.gifdash (-), 206
2042015b45d2b5416108e486be44e8bc.gifdata.
2042015b45d2b5416108e486be44e8bc.gifSee also data types
2042015b45d2b5416108e486be44e8bc.gifsharing, 210211
2042015b45d2b5416108e486be44e8bc.gifstorage, 188
2042015b45d2b5416108e486be44e8bc.gifdata types
2042015b45d2b5416108e486be44e8bc. Boolean data type, 7, 65,
gif 289290
2042015b45d2b5416108e486be44e8bc.gifByte data type, 289290
2042015b45d2b5416108e486be44e8bc.gifcomparisons of, 7, 289290
2042015b45d2b5416108e486be44e8bc.gifdebugging, 3738
2042015b45d2b5416108e486be44e8bc.gifdecimal point (.), 96
2042015b45d2b5416108e486be44e8bc.gifdescriptions
2042015b45d2b5416108e486be44e8bc.gifDictionaries property, 72
2042015b45d2b5416108e486be44e8bc.gifDIESEL, 2
2042015b45d2b5416108e486be44e8bc.gifretrieving, 259
2042015b45d2b5416108e486be44e8bc.gifDisplay object, 65
2042015b45d2b5416108e486be44e8bc.gifDisplay property, 95
2042015b45d2b5416108e486be44e8bc. DisplayScreenMenu
gif property, 65
2042015b45d2b5416108e486be44e8bc.g
if DistanceToRead function,
79
2042015b45d2b5416108e486be44e8bc. DLLs (Dynamic Link
gif Libraries), 48
2042015b45d2b5416108e486be44e8bc. Document object, 5253, 61,
gif 6667, 7073
2042015b45d2b5416108e486be44e8bc. Documents collection, 61,
gif 8385, 6770
2042015b45d2b5416108e486be44e8bc.gifDocuments property, 63
2042015b45d2b5416108e486be44e8bc.gifDrafting property, 95
2042015b45d2b5416108e486be44e8bc.gifdrawing tables
2042015b45d2b5416108e486be44e8bc.gifDWG variable, 68
2042015b45d2b5416108e486be44e8bc.gifDWGS variable, 68
E
2042015b45d2b5416108e486be44e8bc.
gif early binding, 172173,
211212
2042015b45d2b5416108e486be44e8bc.gifencapsulation, 4647
2042015b45d2b5416108e486be44e8bc.gifEnd statement, 37
2042015b45d2b5416108e486be44e8bc.gifEndCommand function, 76
2042015b45d2b5416108e486be44e8bc.gifEndLisp function, 76
2042015b45d2b5416108e486be44e8bc.gifEndOpen function, 76
2042015b45d2b5416108e486be44e8bc.gifEndPlot function, 76
2042015b45d2b5416108e486be44e8bc.gifEndSave function, 76
2042015b45d2b5416108e486be44e8bc.gifEndUndoMark method, 63
2042015b45d2b5416108e486be44e8bc.giftext, 9394
2042015b45d2b5416108e486be44e8bc.gifEntityName property, 89
2042015b45d2b5416108e486be44e8bc.gifEPS files, 52
2042015b45d2b5416108e486be44e8bc.gifErase method, 88, 108, 152
2042015b45d2b5416108e486be44e8bc.giferror(s)
2042015b45d2b5416108e486be44e8bc.gifESP format, 71
2042015b45d2b5416108e486be44e8bc.gifevent(s)
F
2042015b45d2b5416108e486be44e8bc.giffatal_error function, 246
2042015b45d2b5416108e486be44e8bc.giffiles
2042015b45d2b5416108e486be44e8bc.giffinding, 247
2042015b45d2b5416108e486be44e8bc.giffiltering, 117123
2042015b45d2b5416108e486be44e8bc.gifinserting, 202203
2042015b45d2b5416108e486be44e8bc.gifForm_Load function, 26
2042015b45d2b5416108e486be44e8bc.gifFORTRAN, 10
2042015b45d2b5416108e486be44e8bc.gifkeys, 291293
2042015b45d2b5416108e486be44e8bc.gifproper use of, 317318
G
2042015b45d2b5416108e486be44e8bc.gifGetAngle function, 80
2042015b45d2b5416108e486be44e8bc. GetEnvironmentalVariable
gif function, 231, 234235
2042015b45d2b5416108e486be44e8bc. GetFileAttributes function,
gif 231
2042015b45d2b5416108e486be44e8bc.gifGetFileSize function, 231
2042015b45d2b5416108e486be44e8bc.gifGetFreeDiskSpace, 235236
2042015b45d2b5416108e486be44e8bc.g
GetGridSpacing function,
if
150
2042015b45d2b5416108e486be44e8bc.gifGetInput function, 80
2042015b45d2b5416108e486be44e8bc.gifGetInteger function, 80
2042015b45d2b5416108e486be44e8bc.gifGetWidth function, 90
2042015b45d2b5416108e486be44e8bc.gifGroups property, 73
H
2042015b45d2b5416108e486be44e8bc.gifHandle property, 89
2042015b45d2b5416108e486be44e8bc. HELP_COMMAND
gif command, 278, 279280, 283
2042015b45d2b5416108e486be44e8bc. HELP_CONTENTS
gif command, 278
2042015b45d2b5416108e486be44e8bc.
gif HELP_CONTEXT command,
278
2042015b45d2b5416108e486be44e8bc. HELP_CONTEXTPOPUP
gif command, 278
2042015b45d2b5416108e486be44e8bc.gi HelpControlID property,
f 276
2042015b45d2b5416108e486be44e8bc. HELP_FINDER command,
gif 278
2042015b45d2b5416108e486be44e8bc. HELP_FORCEFILE
gif command, 278
2042015b45d2b5416108e486be44e8bc. HELP_HELPONHELP
gif command, 278
2042015b45d2b5416108e486be44e8bc.g HELP_INDEX command,
if 279
2042015b45d2b5416108e486be44e8bc.gifHELP_KEY command, 279
2042015b45d2b5416108e486be44e8bc. HELP_MULTIKEY
gif command, 279
2042015b45d2b5416108e486be44e8bc. HELP_PARTIALKEY
gif command, 279
2042015b45d2b5416108e486be44e8bc.gi HELP_QUIT command,
f 279
2042015b45d2b5416108e486be44e8bc. HELP_SETCONTENTS
gif command, 279
2042015b45d2b5416108e486be44e8bc. HELP_SETINDEX
gif command, 279
2042015b45d2b5416108e486be44e8bc.
gif HELP_SETWINPOS
command, 279
2042015b45d2b5416108e486be44e8bc.gifHide method, 37, 82
2042015b45d2b5416108e486be44e8bc.gifHide operation, 37
I
2042015b45d2b5416108e486be44e8bc.g IDE (Integrated
if Development
Page 363
2042015b45d2b5416108e486be44e8bc.gifEnvironment)
2042015b45d2b5416108e486be44e8bc.gifimporting files, 52
2042015b45d2b5416108e486be44e8bc.gifinfinite loops, 74
2042015b45d2b5416108e486be44e8bc.gifinheritance, 4647
K
2042015b45d2b5416108e486be44e8bc.gifkeywords, 48
L
2042015b45d2b5416108e486be44e8bc.gifLastHeight property, 145
2042015b45d2b5416108e486be44e8bc.gifLeft property, 64
2042015b45d2b5416108e486be44e8bc.gifLen function, 36
2042015b45d2b5416108e486be44e8bc.gifLispCancelled function, 76
2042015b45d2b5416108e486be44e8bc.gifListARX method, 62
2042015b45d2b5416108e486be44e8bc.gifcolumns, 305308
2042015b45d2b5416108e486be44e8bc.gifLoadARX method, 62
2042015b45d2b5416108e486be44e8bc.gifLoadShapeFile method, 71
2042015b45d2b5416108e486be44e8bc.gifLocaleID property, 64
M
2042015b45d2b5416108e486be44e8bc.gifMacintosh, 42
2042015b45d2b5416108e486be44e8bc.gifmacro(s)
2042015b45d2b5416108e486be44e8bc.giftesting, 3334
2042015b45d2b5416108e486be44e8bc.gifMenuBar object, 65
2042015b45d2b5416108e486be44e8bc.gifMenuBar property, 64
2042015b45d2b5416108e486be44e8bc.gifMenuGroups object, 65
2042015b45d2b5416108e486be44e8bc.gifMenuGroups property, 64
2042015b45d2b5416108e486be44e8bc.gifmethods.
2042015b45d2b5416108e486be44e8bc.gifsymbols for, 57
2042015b45d2b5416108e486be44e8bc.giftesting, 68
2042015b45d2b5416108e486be44e8bc.gifMid$ function, 36
2042015b45d2b5416108e486be44e8bc.gifMirror method, 88
2042015b45d2b5416108e486be44e8bc.gifMirror3D method, 88
2042015b45d2b5416108e486be44e8bc.gifmodules
2042015b45d2b5416108e486be44e8bc.gifnaming, 330
N
2042015b45d2b5416108e486be44e8bc.gifNam variable, 69
2042015b45d2b5416108e486be44e8bc. Name property, 64, 68, 72,
gif 108, 139, 145, 146, 148, 150
2042015b45d2b5416108e486be44e8bc.gifNew method, 71
2042015b45d2b5416108e486be44e8bc.gifOpenSave property, 95
2042015b45d2b5416108e486be44e8bc.gifOutput property, 95
P
2042015b45d2b5416108e486be44e8bc.gifPad function, 256
2042015b45d2b5416108e486be44e8bc.gifparameters
2042015b45d2b5416108e486be44e8bc.gifPascal, 48
2042015b45d2b5416108e486be44e8bc.gifPlot property, 73
2042015b45d2b5416108e486be44e8bc.gifpoints
2042015b45d2b5416108e486be44e8bc.gifformatting, 251
2042015b45d2b5416108e486be44e8bc.gifPolarPoint function, 79
2042015b45d2b5416108e486be44e8bc.gif
polylines, 9192
2042015b45d2b5416108e486be44e8bc. polymorphism, 32, 4647,
gif 5455, 57, 8586, 89
2042015b45d2b5416108e486be44e8bc.gifporting issues, 273274
2042015b45d2b5416108e486be44e8bc.gifpound sign (#), 123, 295
2042015b45d2b5416108e486be44e8bc.gifprocedures
2042015b45d2b5416108e486be44e8bc.gifproject(s).
2042015b45d2b5416108e486be44e8bc.gifembedding, 205
2042015b45d2b5416108e486be44e8bc.gifproperties.
Q
2042015b45d2b5416108e486be44e8bc.gifquestion mark (?), 123
2042015b45d2b5416108e486be44e8bc.gifQuit method, 62
R
2042015b45d2b5416108e486be44e8bc.gifre-using code, 207208
2042015b45d2b5416108e486be44e8bc.gifReadOnly property, 73
2042015b45d2b5416108e486be44e8bc.gifRotate method, 88
2042015b45d2b5416108e486be44e8bc.gifRotate3D method, 88
S
2042015b45d2b5416108e486be44e8bc.gifSave method, 71, 72
2042015b45d2b5416108e486be44e8bc.gifSaveAs method, 71
2042015b45d2b5416108e486be44e8bc.gifSaved property, 73
2042015b45d2b5416108e486be44e8bc.gifSaveSetting function, 228
2042015b45d2b5416108e486be44e8bc.gifScaleEntity method, 88
2042015b45d2b5416108e486be44e8bc.gifScaleFactor property, 93
2042015b45d2b5416108e486be44e8bc.gifscript file option, 1
2042015b45d2b5416108e486be44e8bc.gifSetVariable method, 71
2042015b45d2b5416108e486be44e8bc.gifSetView method, 150
2042015b45d2b5416108e486be44e8bc.gifSetWidth method, 90
2042015b45d2b5416108e486be44e8bc. SingleDocumentMode
gif property, 69
2042015b45d2b5416108e486be44e8bc.g SnapBasePoint property,
if 151
2042015b45d2b5416108e486be44e8bc.gifSnapOn property, 151
2042015b45d2b5416108e486be44e8bc.gifStartPoint property, 90
2042015b45d2b5416108e486be44e8bc.gifStartUndoMark method, 63
2042015b45d2b5416108e486be44e8bc.gifstring(s)
2042015b45d2b5416108e486be44e8bc.gifSystem property, 95
T
2042015b45d2b5416108e486be44e8bc.gifTagString property, 166
2042015b45d2b5416108e486be44e8bc.giftesting
2042015b45d2b5416108e486be44e8bc.gifmacros, 3334
2042015b45d2b5416108e486be44e8bc.gifmethods, 68
2042015b45d2b5416108e486be44e8bc.gifnumeric relational, 120123
2042015b45d2b5416108e486be44e8bc.gifprograms, 3738
2042015b45d2b5416108e486be44e8bc.gifTimer function, 77
2042015b45d2b5416108e486be44e8bc.gifTop property, 64
2042015b45d2b5416108e486be44e8bc.giftrain systems, 4345
U
2042015b45d2b5416108e486be44e8bc. UBound function, 100, 162,
gif 163
2042015b45d2b5416108e486be44e8bc. UCS (user coordinate
gif system), 79, 145147
2042015b45d2b5416108e486be44e8bc. UCSIconAtOrigin property,
gif 151
2042015b45d2b5416108e486be44e8bc.gifUCSIconOn property, 151
2042015b45d2b5416108e486be44e8bc.gifUnloadARX method, 62
2042015b45d2b5416108e486be44e8bc.gifUser property, 95
V
2042015b45d2b5416108e486be44e8bc.gifvariable(s).
2042015b45d2b5416108e486be44e8bc.gifdeclarations, 172173
2042015b45d2b5416108e486be44e8bc.gifWith statement, 82
W
2042015b45d2b5416108e486be44e8bc. WCS (World Coordinate
gif System), 146, 147
2042015b45d2b5416108e486be44e8bc.gifWhile loop, 36
2042015b45d2b5416108e486be44e8bc. Width property, 64, 145, 148,
gif
151,