Programming On AutoCad
Programming On AutoCad
Introduction to
Visual Basic for
Applications
(VBA)
Learning Objectives
After completing this chapter, you will be able to:
Explain object-oriented programming.
Describe the AutoCAD object model.
Change an objects properties.
Use an objects methods.
Use the VBA Manager.
Develop a VBA project using the Visual Basic Editor.
Explain the data types used in VBA.
Store data in variables.
Run a VBA macro.
Create a form (dialog box) in a VBA project.
Visual Basic for Applications (VBA) is a version of Microsofts Visual Basic (VB)
programming language that is built into AutoCAD. All of the features of the full
version of VB are included, in addition to functions and procedures that are specific
to programming the AutoCAD application. This chapter is intended to give you an
overview of the basics of VBA. You will learn how easy to use, and yet powerful, the
language is. This chapter is by no means an in-depth look at VBA. For more complete
discussions and study of VBA within AutoCAD, refer to VBA for AutoCAD published
by The Goodheart-Willcox Company, Inc.
In order to use VBA in AutoCAD 2010, the VBA module must be downloaded
from the Autodesk website. If the module is not installed, selecting any of the VBA
tools (Visual Basic Editor, Run VBA Macro, or VBA Manager) from the Applications
panel on the Manage tab of the ribbon opens a dialog box that will guide you through
the process.
Object-Oriented Programming
VBA is an object-oriented programming language. Although lines, arcs, and circles
are objects, AutoCAD entities are not the only objects. The many parts that make
up the AutoCAD application itself are considered objects. The whole program and
all that it is composed of are considered the object model. The AutoCAD object model
Copyright by Goodheart-Willcox Co., Inc.
Chapter 30 Introduction to Visual Basic for Applications (VBA) AutoCAD and Its ApplicationsAdvanced 688
contains all of the objects and provides access to their methods, properties, and events
in a tree-like hierarchy. See Figure 30-1. To display this object model, pick the Help
button in the InfoCenter on the AutoCAD title bar. Once the help file is displayed, pick
the Contents tab. Then, double-click on ActiveX Automation and VBA. Finally, in the
right-hand pane, select Object Model.
Figure 30-1.
The object model for AutoCAD.
Application
Preferences 3DFace
Documents 3DPoly
Document 3DSolid
Database Attribute
ModelSpace AttributeRef
PaperSpace BlockRef
DynamicBlockReferenceProperty
PViewport
Circle
Dictionaries Dictionary
Dim3PointAngular
XRecord
DimAligned
DimStyles DimStyle
DimAngular
FileDependencies FileDependency
DimArcLength
Groups Group
DimDiametric
Layers Layer
DimOrdinate
Hyperlinks
Layouts Layout
DimRadial
Hyperlink
Linetypes Linetype DimRadialLarge
PlotConfigurations PlotConfiguration DimRotated
SortentsTable Hatch
TableStyle Leader
MinsertBlock
Views View
MLeader
Viewports Viewport
MLine
DatabasePreferences
MText
Plot
Point
SummaryInfo
PolyfaceMesh
Utility
Polyline
MenuBar PolygonMesh
PopupMenu Raster Wipeout
MenuGroups Ray
MenuGroup Region
PopupMenus Shape
Solid
AcCmColor PopupMenu
Spline
PopupMenuItem
LayerStateManager Table
Toolbars Text
SecurityParams
Toolbar Tolerance
ToolbarItem Trace
XLine
VBAMAN
Ribbon
Figure 30-2. It also allows a project to be created or saved to a file. The VBAMAN Manage
> Applications
command opens the dialog box.
The active drawing file is shown at the top of the dialog box. Any other open VBA Manager
drawings are available within the drop-down list. Just below the drop-down list, the Type
name of the embedded project is shown, if a project is embedded in that drawing. VBAMAN
New Pick to
project create a new
project
Loaded
project Pick to
load a
project
file
New. Picking this button creates a new project and adds it to the Projects list.
The new project has the default name ACADProject name and is generically
listed as Globaln, where n is a sequential integer. The project name can only be
changed in the Visual Basic Editor, which is covered in the next section. The
Globaln location is updated when the project is saved as a file or embedded in
a drawing.
Save as. Use this button to save to a file the project highlighted in the Projects
list. A standard Windows save as dialog box appears when the button is
picked.
Load. Picking this button displays a standard Windows open dialog box in
which you can select a project file (DVB) to be loaded. The project is loaded into
the drawing selected in the Drawing drop-down list.
Unload. This button allows a project to be unloaded, making its macros unavail-
able. Highlight the project to unload in the Projects list and then pick this button.
Macros. Picking this button closes the VBA Manager dialog box and opens
the Macros dialog box. The available macros are listed in the Macros dialog
box. The Macros dialog box has a VBA Manager button that displays the VBA
Manager dialog box.
There is also the Visual Basic Editor button in the lower-left corner of the VBA
Manager dialog box. Picking this button opens the Visual Basic Editor, which is covered
in the next section.
Ribbon
AutoCAD. The VBAIDE command displays the Visual Basic Editor. It can also be opened Manage
> Applications
by picking the Visual Basic Editor button from within the VBA Manager dialog box.
Now that you have been introduced to VBA terminology and have a basic under-
Visual Basic Editor
standing of how to manipulate projects, you will create a project to allow you to Type
examine the Visual Basic Editor. To avoid confusion, first unload all loaded projects: VBAIDE
[Alt]+[F11]
1. Open the VBA Manager.
2. Select a project in the Projects list.
3. Pick the Unload button.
4. Do the same for all other projects until the Projects list is empty.
Figure 30-3.
The Visual Basic Editor.
Project
Explorer
window
Properties
window Code
window
Pick a type
Pick a scope
Figure 30-5.
Picking the View
AutoCAD button
returns you to
AutoCAD. Pick to
return to
AutoCAD
Select
a macro
10. Display the Macros dialog box using the VBARUN command. Notice that the
VBARUN
Ribbon
BigPickBox macro is listed in the dialog box. See Figure 30-6. The name shows Manage
> Applications
that it is a global macro, it is stored in a module named PickBoxBig, and the
Sub is named BigPickBox.
Run VBA Macro
11. With the macro highlighted, pick the Run button. Notice that the pick box is Type
now slightly larger. VBARUN
PROFESSIONAL TIP
Be sure that the PICKFIRST system variable is set to 1 (noun/verb
selection enabled) so that the pick box is displayed with the cross-
hairs. Also, you can use a higher value in the macro to make the
change in the pick box size easier to see.
You have just created your first VBA macro! You will now add another module
to change the pick box back to the default size and then save the project as a DVB file.
Follow these steps:
1. Display the Visual Basic Editor.
2. Pick inside of the Code window to make it active.
3. Select Procedure from the Insert pull-down menu.
4. In the Add Procedure dialog box, enter NormPickBox as the name of the new
Sub. Also, pick the Sub and Public radio buttons, then pick the OK button.
5. Enter the following code in the new Sub. Remember, type the code between
the Public Sub and the End Sub lines.
Application.Preferences.Selection.PickBoxSize = 3
6. Display AutoCAD.
7. Display the Macros dialog box. Notice the new macro is now listed along with
the first macro. Select the new macro and pick the Run button.
8. Notice that the pick box size is now set to the default size. The default PICKBOX
value is 3.
Exercise 30-2
Complete the exercise on the student website.
www.g-wlearning.com/CAD
For the examples in the rest of this chapter, you will use the String, Integer, Double, and
Variant data types. The practical applications for these data types are:
String. Used for command names, prompts, AutoCAD system variables, and so
on. When using strings within a program, the characters making up the string
are enclosed in quotation marks like this.
Integer. Used for counting. Often, the program has to progress through a list in
increments. Integers are used to do so.
Double. Used for lengths; distances; and X, Y, or Z coordinate values (when
dealing with X, Y, and Z separately).
Variant. Used for point coordinates (when working with X, Y, and Z values
together).
To store a string supplied by the user, the Utility objects GetString method is used.
The GetString method has one required argument, which must come first, and one
optional argument, which must come second. An argument is additional information
that can be passed to the method. The arguments are listed within parentheses imme-
diately after the method. Each argument is separated by a comma. This additional
information is required in some instances and optional in other instances.
In the case of the GetString method, the first argument is a TRUE or FALSE test
and determines whether or not the string that the user enters can contain spaces. Actu-
ally, it determines whether the space bar is interpreted as a space or as the [Enter] key.
If the argument is FALSE, spaces are not allowed. If the user presses the space bar, the
text input is ended. If the argument is TRUE, spaces are allowed in the input string.
The second argument for the GetString method is an optional prompt. If included,
it must be a string. The provided string is displayed on the command line when the
method is called. This can be used to let the user know what is expected of them. Even
though this argument is optional, it is almost always included.
The following code gets a string input by the user and stores it in a variable. Notice
that spaces are not allowed in the string.
Dim strName as String
strName = ThisDrawing.Utility.GetString(FALSE,"First name only: ")
Now that the value is stored, it can be used in some way. For the test macro, it
will just be sent to the command line using the Prompt method. The Prompt method
requires one argument, which must be a string. The data stored in the strName variable
represent a string, so pass this variable to the Prompt method:
ThisDrawing.Utility.Prompt (strName)
Another feature of the Visual Basic Editor becomes apparent as you enter func-
tions that can have arguments passed to them. The Auto Quick Info feature displays
information about the arguments as soon as you type the opening parenthesis. The
argument that you are working on is in bold. Arguments that are optional are shown
enclosed in brackets. Required arguments are shown without brackets.
The following shows additional example code for the GetInteger, GetReal, and
GetPoint methods. For each method, the variable is passed to the Prompt variable.
Sub GetSamples ()
End Sub
Copyright by Goodheart-Willcox Co., Inc.
Chapter 30 Introduction to Visual Basic for Applications (VBA) AutoCAD and Its ApplicationsAdvanced 698
Some items of note regarding the GetPoint code:
The GetPoint method can have two arguments, but in this case only a prompt
string argument needs to be supplied. However, this must be the second argu-
ment. The first argument is left blank, but still separated from the second argu-
ment with a comma.
The GetPoint method returns (produces) a set of X, Y, and Z coordinates. These
three values are stored in what is called an array in VBA, which is similar to an
AutoLISP list. The items in an array are indexed beginning with 0, rather than
1. So, the X value is in the array at an index of 0, the Y value at index 1, and the
Z value at index 2. Each item can be passed as an argument by using its index
in the array. In the above example, the X and Y values (at index positions 0 and
1) are passed to the Prompt method.
The Prompt method can only have one argument, a string, passed to it. Multiple
strings can be concatenated (added together) using the ampersand (&). In the
above example, only the X value varPoint(0) and Y value varPoint(1) are supplied
and they are separated by a comma and a space (", ").
Exercise 30-3
Complete the exercise on the student website.
www.g-wlearning.com/CAD
End Sub
The Set statement and = assignment operator are used to assign a reference to a
particular object type. This is how you store a value in an object variable. The AddCircle
method is used to create a circle, in this case as a member of the ModelSpace collection
(created in model space). This example also introduces a new data type. AcadCircle
is an object data type exclusive to AutoCAD. Variables for use with object data types
have their names prefixed with obj. A list of all AutoCAD-specific object data types is
located in the developers help:
Finally, in the right-hand pane, select Object Model.
1. Pick the Help button in the InfoCenter on the AutoCAD title bar.
2. Once the help file is displayed, pick the Contents tab. Then, double-click on
ActiveX Automation and VBA.
3. In the right-hand pane, select Objects.
Copyright by Goodheart-Willcox Co., Inc.
Chapter 30 Introduction to Visual Basic for Applications (VBA) AutoCAD and Its ApplicationsAdvanced 699
4. The right-hand pane now displays a list of all AutoCAD-specific data types.
Picking on an object name displays information specific to that data type.
The next example creates a line between two points that the user selects. This
example is similar to the previous example.
Sub CreateLine()
End Sub
The only new concept introduced in this macro is that the first selected point, which is
stored in a variable as a Variant data type, is being passed as the first argument for the
second use of the GetPoint method. By including this, a drag line is shown from the
first point to the cursor location until the second point is picked or entered.
Exercise 30-4
Complete the exercise on the student website.
www.g-wlearning.com/CAD
objCir.Radius = dblCirRad
End Sub
The GetEntity method assigns both the selected object and the selection point to
the variable. This is similar to the argument-passing concept. A third argument is the
prompting string. Notice how the Radius property of the variable objCir, which is an
AcadCircle data type, is set equal to the value of the dblCirRad variable.
Copyright by Goodheart-Willcox Co., Inc.
Chapter 30 Introduction to Visual Basic for Applications (VBA) AutoCAD and Its ApplicationsAdvanced 700
Exercise 30-5
Complete the exercise on the student website.
www.g-wlearning.com/CAD
Figure 30-7.
This is the dialog
box you will create
using VBA.
Figure 30-8.
A new form has been added to the project. Its name and caption have been changed.
Toolbox window
UserForm
window
Change
the
name
Change
the
caption Blank
form
5. The controls can be moved around on the form by picking on the object and
dragging it to a new location. Multiple controls can be selected by pressing
the [Ctrl] key before picking the objects. Arrange the controls as shown in
Figure 30-9.
When the form (dialog box) is being used, the two text boxes will be displaying numeric
values. It is common practice to display numeric data right justified. Select the two text
box controls and continue as follows.
12. In the Properties window, select the TextAlign property. Pick the drop-down
arrow and select 3fmTextAlignRight from the list.
13. Individually select, resize, and relocate each of the controls until the form
appears as shown in Figure 30-10.
14. Pick the Save button on the toolbar in the Visual Basic Editor to save the
project.
PROFESSIONAL TIP
It is important to use logical names with standard prefixes for
objects on a form. These names are used to reference the objects
within code. Using logical names and standard prefixes help to
keep everything organized and easily identified.
3. Between the Private Sub line and the End Sub line, type the following lines
of code. Notice how blank lines and tabs are used to visually organize the
code.
frmAreaCalc.Hide
Else
Exit Sub
End If
4. Save the project.
Else
Exit Sub
End If
The only difference between these lines of code and those for the Add Object
button is this line:
dblTotalArea = dblTotalArea dblObjectArea
This line subtracts the area of the selected AutoCAD object from the total
area.
4. Save the project.
As you double-click to add code for the various objects on the form,
the Private Subs are added to the Code window in alphabetical
order. The Private Subs can be rearranged using cut-and-paste
editing to more closely follow the flow of the program, if desired.
For example, you may wish to rearrange the Private Subs for the
controls on the frmAreaCalc form as:
Private Sub btnAddObject_Click()
lines of code
End Sub
frmAreaCalc.Show
End Sub
6. Save the project.
CAUTION
This routine is not error proof. It will break down if you do not select
an object when prompted to do so. Error checking is an important
feature of programming. For information on adding error checking
to your VBA programs, refer to VBA for AutoCAD published by The
Goodheart-Willcox Company, Inc.
2. Create a VBA macro that will ask the user to select a line. Then, display the length
of the selected object in a message box. If the selected object is not a line, display a
message informing the user of this. Name the macro P30_02_LineLength.
3. Create a VBA macro that will draw three circles.
A. Draw the first circle using a center point and radius provided by the user.
B. Draw the second circle using the same center point and a radius 25% larger
than the first circle.
C. Draw the third circle using the same center point and a radius 25% smaller
than the first circle.
D. Provide prompts for the user for the center point and radius.
E. Name the macro P30_03_DrawCircles.
4. Create a VBA macro that will reduce the radius of a selected arc or circle to half of
its original radius. If the selected object is not an arc or circle, display a message
informing the user of this. Name the macro P30_04_ChangeRadius.