Youread about: ✦ Global and local variables ✦ Some of the features of ActiveX ✦ How to use some of Visual LISP’s debugging features, including the Error Trace window,break points, and th
Trang 1STEPS: Working with Break Points
1 Open AutoCAD and start a drawing using any template.
2 Start the Visual LISP Editor Open ab36-a.lsp from the CD-ROM Choose File ➪ Save As
and save it as ab36-01.lsp in the AutoCAD 2007\Support folder or in another folderthat you’ve added to the support file search path
3 Choose Load Active Edit Window from the Tools toolbar.
4 Read through the code This routine creates a vertical list of numbers The new FOREACH
function steps through each item in a list The comments explain why it contains a bug
5 If you didn’t do the previous exercise, choose Debug ➪ Break on Error (Don’t do
any-thing if the Break on Error item is already checked.)
6 Type the following in the Console window:
(list-beautify-with-bug ‘(1 2 3 4 5 )) ↵
The Console returns the following:
(1
; error: bad argument type: FILE 1
7 Choose Last Break on the Debug toolbar to jump to the error in the source code.
8 To place a break point in the code, place the cursor after (princ (chr 40)) Press F9.
Visual LISP marks the break with a red box
9 Place another break point after (princ (car aList)) Finally, place a third break point
after the closing parenthesis on the line that follows (princ item 1) Your code shouldlook like Figure 36-3
10 After the code produces an error, you need to reset Click Reset on the Debug toolbar.
11 Click the Visual LISP Editor window and reload the function into Visual LISP (Choose
Load Active Edit Window on the Tools toolbar.)
12 Type the same expression that produced the error in the Console:
(list-beautify-with-bug ‘(1 2 3 4 5 )) ↵
13. Visual LISP highlights the expression (princ (chr 40)) Choose Step Into on the
Debug toolbar Visual LISP highlights (princ (car aList))
14 Choose Step Into Now only (car aList)) is highlighted.
15 Choose Step Into until you reach the error, (princ item 1).
16 Edit (princ item 1) so that it reads (princ item).
17 Click Reset again.
18 Choose Debug ➪ Clear All Breakpoints Click Yes to confirm.
19 Activate the Editor window and reload the function.
20 In the Console, type (list-beautify-with-bug '(1 2 3 4 5 )) ↵
21 Activate the Editor window and save the file.
Trang 2Chapter 36 ✦ Exploring Advanced AutoLISP Topics
Figure 36-3: Your code should look like this after you place three break points.
If you have difficulty in fixing this bug, you can find the “repaired” version in the Resultsfolder on the CD-ROM, with the filename list-beautify-without-bug.lsp
Using the Watch window
The Watch window enables you to examine expressions and variable values as they’rebeing evaluated To watch a variable, select it in the code and choose Debug ➪ AddWatch, or press Ctrl+W Visual LISP opens the Watch window listing the expression or vari-able and displaying its value after an equal sign If you select an expression or nothing isselected and you press Ctrl+W, the Add Watch dialog box opens If it is not already displayed,enter the expression that you want to watch and click OK For example, if you add a watch for(princ (chr 40)), the Watch window displays (PRINC (CHR 40)) = “(“ because (princ(chr 40))is another way of telling AutoLISP to print a left parenthesis After the Watch win-dow is open, you can add expressions or variables by selecting them and choosing AddWatch on the Watch window toolbar
If you have a routine with arguments, you can execute the function with various argumentsand see the results on your watched expressions and variables in the Watch window
Furthermore, you can add any expression to the Watch window and alter the contents of anyvariable while debugging a function
The file used in the following exercise on using the Watch window, ab36-01.lsp, is in theResultsfolder on the CD-ROM
On the CD-ROM
On the CD-ROM
Trang 4Chapter 36 ✦ Exploring Advanced AutoLISP Topics
12 To remove the break point, choose View ➪ Breakpoints Window to open the Breakpoints
dialog box Click Delete All to delete the break point Visual LISP automatically closes thedialog box
13 Click Reset on the Debug toolbar.
14 Close the Watch window and the Visual LISP IDE without saving the file.
As you can see, Visual LISP is not just an editor; it’s a full-featured, integrated developmentenvironment for AutoLISP
Summary
In this chapter, you examined some of the advanced features of AutoLISP and Visual LISP Youread about:
✦ Global and local variables
✦ Some of the features of ActiveX
✦ How to use some of Visual LISP’s debugging features, including the Error Trace window,break points, and the Watch window
In the next chapter, you read about the basics of Visual Basic for Applications, another gramming language that you can use with AutoCAD
Trang 637 C H A P T E R
Programming with Visual Basic for
Applications
Visual Basic for Applications (VBA) is a programming languageand environment that is included with many Microsoft applica-tions, such as Word, Excel, PowerPoint, and Access Since Release 14,VBA has been available with AutoCAD as well VBA is ideally suited forsituations in which you need to work with more than one application
at a time ActiveX, which I discussed in the last chapter in relation
to Visual LISP, enables you to access objects in other applications
However, you can also use VBA to program AutoCAD alone This ter introduces you to VBA and shows how you can start to use thispowerful language to customize AutoCAD
chap-AutoCAD LT does not support VBA This entire chapter applies toAutoCAD only
Visual Basic for Applications is a variation of Visual Basic VisualBasic is not related to any specific application Visual Basic code iscompiled into an executable file that stands alone, unrelated to anyspecific document VBA, on the other hand, is connected to its appli-cation and the document in which you created the code VBA pro-vides a simple way to customize AutoCAD, automate tasks, andprogram applications from within the application
VBA in AutoCAD works slightly differently from VBA in most otherapplications, in that VBA projects are stored in a separate file, withthe DVB filename extension, but can also be stored within the draw-ing file
Starting to Work with VBA
After you decide to program AutoCAD, the first step is to select a gramming language to use
Debugging andtrapping errors
Trang 7✦ VBA is faster than AutoLISP, even when AutoLISP is compiled.
✦ VBA is common to many other applications If you’ve used VBA before, you can easilytransfer your knowledge to using VBA in AutoCAD You’re also more likely to find otherprogrammers who know VBA compared to AutoLISP
✦ VBA is generally easier to learn than AutoLISP because of its syntax
On the other hand, AutoLISP has the advantage of backward compatibility with prior releases
of AutoCAD Of course, if you’re familiar with AutoLISP but not VBA, it’s hard to beat the ease
of working with a language that you already know and use
VBA programs are saved in projects A project contains all of the parts that are needed to
exe-cute the function of the program You can use the VBA Manager to view your VBA projects.The VBA Manager also enables you to load, unload, save, and create VBA projects To openthe VBA Manager, choose Tools ➪ Macro ➪ VBA Manager
Opening the VBA environment
To start working with VBA, you must open the VBA environment VBA has its own interface,just like Visual LISP To open VBA in AutoCAD, choose Tools ➪ Macro ➪ Visual Basic Editor
(or type vbaide ↵) Like Visual LISP, VBA has its own interface, called an integrated development
environment, or IDE AutoCAD displays the VBA environment window.
VBA projects can contain modules A module is a self-contained piece of programming code.
A VBA project can have one or more modules
To add a module, choose Insert ➪ Module, or click the drop-down list to the right of thesecond button on the VBA IDE Standard toolbar Then choose Module AutoCAD opens amodule text editor window so that you can start typing code In the Project window, VBA adds
a new module to the list of modules By default, the first module is called Module1 Figure 37-1shows the VBA IDE, including the text editor If you don’t see the Project Explorer or theProperties window, use the View menu of the VBA IDE to choose Project Explorer or PropertiesWindow
You can resize the module text editor as you would any window As you start adding code tothe text editor, you’ll find it easier to work with a larger window Click the Maximize button toenlarge the text editor to its maximum size
AutoCAD is still running in the background You can return to it at any time by clickingits button on the Windows task bar, or by clicking View AutoCAD on the VBA IDE Standardtoolbar
Getting acquainted with VBA
VBA enables you to easily retrieve, create, and manipulate objects To get a list of objects,open the Object Browser by clicking Object Browser on the Standard toolbar or choosingView ➪ Object Browser Objects are organized into libraries All of the objects that you workwith in AutoCAD are in the AutoCAD library
Tip
Trang 8Chapter 37 ✦ Programming with Visual Basic for Applications
Figure 37-1: The VBA environment window.
To see the list of AutoCAD objects, click the <All Libraries> drop-down list and chooseAutoCAD You can see the result in Figure 37-2
You can resize the panes in the VBA window Place the mouse cursor on the bar between thepanes until you see the double-headed arrow, and drag it either left or right
Figure 37-2: You can use the Object Browser to see the
AutoCAD library of objects
Tip
Trang 9Objects and collections of objects
In the left pane, labeled Classes, you see the list of objects In VBA, you can have both ual objects and collections of objects For example, AcadLayer would be the layer object, andAcadLayers would be the collection of layers The purpose of collections is to enable you towork with a group of objects For example, to add a layer, you add it to the collection of lay-ers; this is because the new layer is not related to any existing layer
individ-Methods and properties
What can you do with objects in VBA? First, objects can have properties For example, youcan set an ellipse to the color red because one of the properties of the ellipse object isTrueColor (Of course, all drawing objects have TrueColor as one of their properties.)
Second, objects have methods A method is an action that you can take on the object For
example, you can delete (erase) an ellipse because Delete is a method of the ellipse object(as well as of all drawing objects)
In the Object Browser, the right pane, Members, lists the properties and methods of anyobject that you choose in the Classes pane
Investigating the hierarchy model
Although you might first think that an object in VBA is the same as an object in an AutoCAD
drawing, there is more to the story In VBA, everything is an object For example, AutoCAD as
an application is an object Your current drawing is also an object Model space and paperspace are also objects Therefore, to specify an object in your drawing, you need to specifythe application, the drawing, and finally the object in the drawing To do this, VBA works with
a hierarchy of objects For example, the hierarchy makes it possible to distinguish between
an object in your drawing and an object in an Excel spreadsheet
Objects are specified from the most general to the most specific, with a period between eachpart of the definition You then add the desired method or properties after another period.For example, you can use the following VBA code to add a circle:
Within AutoCAD, choose Help ➪ Additional Resources ➪ Developer Help You’re now in anew Help system On the Contents tab, double-click ActiveX and VBA Reference Click ObjectModel to see the hierarchical model shown in Figure 37-3, or double-click Objects to see thealphabetical object list
Note
Trang 10Chapter 37 ✦ Programming with Visual Basic for Applications
Figure 37-3: The object model shows you the hierarchy of all of
the VBA objects so that you can work with them
STEPS: Becoming Acquainted with the VBA Environment
1 With any drawing open in AutoCAD, choose Tools ➪ Macro ➪ Visual Basic Editor.
AutoCAD opens the VBA IDE
2 Choose Insert ➪ Module from the menu The VBA IDE opens the module text editor
window
3 Move down to the Windows task bar and click the AutoCAD button to return to
AutoCAD Now click the Microsoft Visual Basic button to return to the VBA IDE
4. Click Object Browser on the VBA IDE Standard toolbar Click the <All Libraries>
drop-down list and choose AutoCAD If necessary, maximize the window by ing the Maximize button at the top-right corner of the window
click-5 In the Classes pane, click AcadLine You see the associated properties and methods in
the right pane
6 In the right pane, which is labeled Members of AcadLine, click Delete You see the
fol-lowing at the bottom of the window:
Sub Delete()Member of AutoCAD.AcadLineDeletes a specified object
Trang 117 In the right pane, click Layer At the bottom of the window, you see the following:
Property Layer As StringMember of AutoCAD.AcadLineSpecifies the current layer of the objectThis indicates that Layer is a property of AcadLine String refers to the data type, dis-cussed later in this chapter
8. Click Help in the Object Browser window You see the Help page for the Layerproperty
9 On the Contents tab, double-click Objects and then click Line object Scroll down to see
all of the properties and methods that belong to the Line object
10 In the second paragraph of the description, the word AddLine is underlined with a
hypertext line Click it to see the description of the AddLine method
11 At the top of the page, click Example (also with a hypertext underline) You see an
example of VBA code for creating a line
12 Close Help by clicking the Close button at the top-right corner of each window.
Leave the VBA IDE window open if you’re continuing on to the next exercise
Accessing help
VBA offers several help features You’ve already seen the Object Browser, which provides youwith a list of objects as well as their properties and methods To access help on an object,choose it in Object Browser and click Help You can do the same for a method or property,
as shown in Figure 37-4
After you open a help page, click Example to see an example These examples are a great way
to learn VBA You can copy a snippet of VBA code and paste it into your own routine, andthen edit it as you want
For more general help, AutoCAD offers two systems:
✦ The ActiveX and VBA Reference is an alphabetical listing of objects, methods, ties, and events
proper-✦ The ActiveX and VBA Developer’s Guide explains ActiveX automation concepts andtechniques
To access these reference guides, switch to AutoCAD and choose Help ➪ AdditionalResources ➪ Developer Help
The Microsoft Visual Basic for Applications Help provides information on the general VBAenvironment Click Help on the VBA IDE Menu Bar toolbar, or choose Help ➪ MicrosoftVisual Basic Help Here you see help for other VBA-enabled applications that you mayhave You can use this when you’re ready to write VBA code that integrates more than oneapplication
Trang 12Chapter 37 ✦ Programming with Visual Basic for Applications
Figure 37-4: The help page for the Center Property.
After you start programming, you can get help on any expression by clicking it and
pressing F1 For example, you can type AddLine and press F1 to access help on how to
create a line
Writing VBA Code
Now that you’re familiar with the structure of VBA objects, methods, and properties, you’reready to start writing some code As with any programming language, you need to learn syn-tax and understand variables and when to use them Luckily, AutoCAD’s VBA Help includesmany examples to guide you along the way After you write some code, you can use it inAutoCAD
Table 37-1 lists the various components of VBA code This table defines various terms thatyou can often use when working with VBA
Trang 13Table 37-1: Components of VBA Code
Term Definition
Procedure Code that does something and has a name A procedure can be a subroutine, a
function, or a property
Project A set of forms and modules
Module A set of subroutines, functions, and declarations that are usually related and comprise
a distinct component in a project A module can contain zero (0) or more procedures(subroutines and functions)
Form A container for the visual components, such as buttons and text boxes, of a dialog box
that you create for your VBA project
Subroutine A procedure, written in VBA code, that does not return a value
Function A procedure, written in VBA code, that returns a value
Property A procedure, written in VBA code, that specifies a value (the property of an object).Declaration One or more nonexecutable statements that name constants or variables and define
their attributes (such as data type)
Macro A public subroutine that a user can directly execute
When you start to create code, VBA can create the basic structure for each procedure foryou With a text or code window displayed, choose Insert ➪ Procedure to open the AddProcedure dialog box shown in Figure 37-5
In the Name text box, type in a name for the new procedure, and then choose the type of procedure that you want to create Choose whether you want the scope to be Public or
Private and then click OK If a subroutine (called sub for short) is declared Public, it is visible
(can be called) from other modules or from the AutoCAD Macros dialog box A sub that isdeclared Private is visible only within that module
Figure 37-5: The Add Procedure dialog box.
Trang 14Chapter 37 ✦ Programming with Visual Basic for Applications
If you check the All Local Variables as Statics check box in the Add Procedure dialog box, yourvariables retain their values between the times that they’re used
Looking at VBA syntax
To start programming, you need an idea of how a VBA routine is put together Here is a plete VBA routine that draws a 3D box
com-‘Insert a 3D Solid BoxSub Box()
‘declare input variables to AddBox()Dim dOrigin(0 To 2) As Double ‘origin is array of doubles ‘(x,y,z)Dim dLength As Double ‘length
Dim dWidth As Double ‘widthDim dHeight As Double ‘heightDim myBox As Acad3DSolid ‘holds return from AddBox()dOrigin(0) = 0# ‘set origin to (0,0,0)dOrigin(1) = 0#
‘change the viewpoint to better see the boxThisDrawing.SendCommand (“VPOINT 1,1,1 “)End Sub
Here’s what the code means:
✦ Line 1: Any text starting with an apostrophe (‘) is a comment Placing comments in
your routines helps you and others to understand what you’re doing
✦ Line 2: Sub indicates the start of a procedure, which is a named, unified piece of code.
You can have several subroutines in a VBA project A project is the file that you save,and it has a DVB filename extension Each project contains the components of yoursubroutines, dialog boxes, and so on The next word is the name of the subroutine
Within the parentheses, you can add arguments, if any Use an empty set of ses if there are no arguments Declaring variables is discussed later in this chapter
parenthe-✦ Line 3: Another comment describing the next few lines of code It’s always a good idea
to comment your code, indicate what is happening, and even write notes to yourself toremind you of your intent
✦ Line 4: You can also declare variables using the Dim statement Here dOrigin is used
as the variable for the center of the box (0 To 2) means that the origin will have threeparts to it, for the X, Y, and Z coordinates Double is a type of variable that is suitablefor most coordinates More about variable types later
Note
Trang 15used as the length, width, and height of the box These are declared as type Double,which is also indicated by the d prefix on the variable names This isn’t required, butit’s a good idea to use a naming scheme for variables to help remind you of their type,especially as you get deeper into programming or have to come back to some codeafter not seeing it for a while.
✦ Line 8: Here you declare a variable called myBox as an Acad3DSolid to refer to the new
box that will be created Acad3DSolid is a data type that is specific to AutoCAD, andsuitable for (you guessed it) referencing a 3D solid in your drawing You can find otherAutoCAD data types by looking in the Object Browser, or by looking at the Object Model
as I explained earlier in this chapter
✦ Lines 9–11: Here you specify the X, Y, and Z coordinates of the origin of the box.
The values are assigned to the dOrigin variable The pound sign (#) is used toindicate a double-precision floating-point value Use of the # sign is not required herebut is more accurate and more clearly indicates your intentions In some situations,rounding errors can occur when assigning numbers of one type to variables of anothertype, such as when you assign integers to doubles and doubles to integers
✦ Lines 12–14: Set the length, width, and height of the box to 5.
✦ Line 15: Another comment.
✦ Line 16: Finally, you’re ready to actually do something The Set statement is used to
set a variable to an object Here you set the variable myBox to an Acad3DSolid defined
by AddBox(dOrigin, dLength, dWidth, dHeight) The AddBox method creates a new3D box You need to define its origin, length, width, and height by using the variablesthat you’ve previously defined The AddBox method is a member of ModelSpace, which
is a member of ThisDrawing You use ThisDrawing in VBA to access the current ing Because VBA within AutoCAD is automatically connected to AutoCAD, you don’tneed to specify the application (that is, AutoCAD)
draw-✦ Line 17: Not another comment! Ask yourself these questions: If I looked at this code
without the comments, would I have a harder time understanding it? What if there is
a bug and I ask another programmer to find it? What if I am that programmer?
✦ Line 18: Here we send the VPOINT command to change the viewpoint Otherwise, the
box that we just created will simply look like a square viewed from the top The spaceafter the numbers 1,1,1 and before the quotation mark is important; it signifies the end
of the command It’s like pressing the Enter key for this command
✦ Line 19: End Sub ends the subroutine.
To find the syntax for a statement that you want to use, look in VBA Help, as explained in the
“Accessing help” section earlier in this chapter In the preceding VBA routine, you might want
to click AddBox and press F1 to find the syntax and elements that are required for creating abox Then click Example to see an actual example of code for that statement
Saving a VBA routine
As I mention earlier, the AutoCAD version of VBA saves VBA projects as separate files with
a DVB file name extension However, when you run a routine, AutoCAD lists it in the formatModuleName:Procedure Name If your project has only one module, you can give the moduleand the procedure the same name However, most VBA routines have more than one module,with one module controlling the rest By running the controlling module, you run the wholeproject
Trang 16Chapter 37 ✦ Programming with Visual Basic for Applications
To name a module, look in the Properties window After you’ve created a module, the VBA IDElists its name property as Module1 by default Double-click Module1 and type a new name
Notice that the module name in the Project window also changes accordingly
A module name (as well as the names of other forms and controls) must start with a letterand can be up to 31 characters Only letters, numbers, and the underscore character areallowed
To save a project as a separate file, which includes all of the modules, click Save on theVBA IDE Standard toolbar VBA returns you to AutoCAD and opens the Save As dialogbox Type a name for your project, choose a location, and click Save
You can save your project in the Sample\VBA subfolder in the AutoCAD 2007 folder, or useanother folder that is in AutoCAD’s support file search path
Loading a VBA routine
Before you run a VBA routine, it must be loaded If you’re working on the routine and want torun it to check how it works — which you’ll do often — you don’t need to load the routine
However, if you want to run a routine that hasn’t been loaded, you need to use the VBALOAD
command When you choose Tools ➪ Macro ➪ Load Project (or type vbaload ↵), AutoCADopens the Open VBA Project dialog box Navigate to your project, choose it, and click Open
(AutoCAD asks you to confirm that you want to enable macros.) The project is now loaded
Running a VBA routine
After you complete a subroutine, you can run it in AutoCAD After all, that’s the reason forwriting VBA code in the first place To run a VBA routine, choose Tools ➪ Macro ➪ Macros
(or type vbarun ↵) In the Macros dialog box, choose the module that you want to run andclick Run AutoCAD runs the module, including other modules that may be controlled by themodule that you run
Using the Visual Basic Editor
When you type code from scratch in the Visual Basic Editor, you immediately notice thatVisual Basic color-codes your text as you go The most common colors are:
Normal text BlackSyntax-error text RedComments GreenKeyword text BlueKeywords include variable types and other words that Visual Basic recognizes, such as Dimand Sub
You can customize these colors by choosing Tools ➪ Options from the Visual Basic menu andthen choosing the Editor Format tab Choose a type of text and then choose the desired color
Click OK
Tip
Note
Trang 17that enables you to choose from a list, or that helps you to complete the word The editoralso adds or removes spaces, and capitalizes certain words for you to improve your syntax.
If you make a syntax mistake, a small error message often appears as you work In theseways, the Visual Basic Editor helps you to type accurate code
STEPS: Creating, Saving, and Running a VBA Program
1 Open a new drawing using the acad.dwt template Choose Tools ➪ Macro ➪
Visual Basic Editor
2 Choose Insert ➪ Module VBA opens the module text editor (If you’ve previously
opened a module, Visual Basic may launch with a blank module already open In thatcase, skip this step.)
3 Choose Insert ➪ Procedure In the Name text box, type DrawTorus The type should be
Suband the scope should be Public Click OK
4 Type the following code (Note that the second and last lines are already there for you.)
‘insert a TorusPublic Sub DrawTorus()
‘declare variablesDim dCenter(0 To 2) As DoubleDim dRadius1 As Double
Dim dRadius2 As DoubleDim myTorus As Acad3DSolid
‘set center of torus to 0,0,0dCenter(0) = 0#
‘set the viewpoint and shade itThisDrawing.SendCommand (“VPOINT 1,1,1 VSCURRENT CONCEPTUAL “)End Sub
5 In the Properties window, change the name of the module to DrawTorus.
6 Because this routine is active, you don’t need to load it Choose Save on the VBA IDE
Standard toolbar Save the project as ab37-01.dvb in your AutoCAD Bible folder
7 Use the Windows task bar to return to your drawing Choose Tools ➪ Macro ➪ Macros.
In the Macros dialog box, choose DrawTorus and click Run VBA draws and shades thetorus
Don’t save your drawing
Trang 18Chapter 37 ✦ Programming with Visual Basic for Applications
Here’s an explanation of the routine that you just wrote and used Note that blank lines areignored
✦ Line 1: Comment describing routine.
✦ Line 2: This is a public subroutine named DrawTorus with no parameters.
✦ Line 3: Comment indicating which variable declarations are next.
✦ Line 4: Declare the array to hold the X, Y, and Z coordinates for the center of the torus.
✦ Line 5: Declare the variable to hold the radius of the torus.
✦ Line 6: Declare the variable to hold the radius of the tube.
✦ Line 7: Declare the variable to hold the created 3D object.
✦ Line 8: Comment.
✦ Lines 9–11: Set the center to 0,0,0.
✦ Line 12: Set the torus radius to 10.0.
✦ Line 13: Set the tube radius to 2.0.
✦ Line 14: Comment.
✦ Line 15: Create the torus.
✦ Line 16: Comment.
✦ Line 17: Send commands to AutoCAD to set the viewpoint and set the visual style to
Conceptual for better viewing
✦ Line 18: End of subroutine.
Understanding variables
A variable holds a value for later use in your program In VBA, you don’t need to explicitlydeclare your variables in advance (as long as you don’t include Option Explicit, which Iexplain later) You use the Set statement to set a variable to an object, as in the examplehere This statement creates a variable, cir, and sets its value equal to the circle that theAddCirclemethod creates
Set cir = ThisDrawing.ModelSpace.AddCircle(cen, radius)
When you create a variable in this way, VBA assigns the default variant type to it The variant
type of variable can contain numbers, dates, or strings (of text)
However, declaring variables explicitly in advance has two advantages:
✦ You can specify the type of variable, which usually uses less memory than the defaultvariant type
✦ As you continue to enter code, VBA checks the variable’s spelling for you, thus ing the chance for errors
reduc-You declare variables using the Dim statement Here’s an example:
Dim radius As Double
Trang 19✦ A Public variable is available to all procedures in the project It is shown as follows:Public dRadius As Double
✦ A module-level variable is available to all of the procedures in the module You create amodule-level variable by placing the declaration (with the Dim statement) at the top of
a module, in a Declarations section Another way to create a module-level variable is touse the Private statement Examples are shown here:
Dim dNum3 as DoublePrivate dNum2 as Double
✦ A procedure-level variable is used only within a procedure You can place the variableanywhere within the procedure, as long as you declare the variable before you use it.Placing the statement Option Explicit in a Declarations section requires all variables to bedeclared Using Option Explicit is a way to force yourself to write your code more carefully.Declared variables are easier to debug because they’re easier to find
Table 37-2 describes the kinds of variables that you can declare
Table 37-2: VBA Variable Types
Variable Description
Boolean For variables that can have only two values — True or False
Byte Positive integers from 0 to 255
Integer Integers from –32,768 to +32,767
Long Integers from –2,147,483,648 to +2,147,483,647
Currency Values from –922,337,203,685,477.5808 to +922,337,203,685,477.5807 Use this variable
for currency or for other values that need accuracy to several decimals
Single Single-precision floating-point values Single variables use less memory than double
variables, but their values are limited
Double Double-precision floating-point values Double variables offer much greater precision
than single variables Most coordinates use this variable type Three double variablescreate the X, Y, and Z values
Date Holds dates and times that are stored as real numbers The number to the left of the
decimal is the date, and the number to the right of the decimal is the time
String Fixed- or variable-length text strings, including letters, numbers, spaces, and punctuation
characters
Object Objects such as an application, a drawing, or a drawing object
Variant Contains numbers, dates, or strings When you don’t declare a type for a variable, VBA
uses this type by default
Trang 20Chapter 37 ✦ Programming with Visual Basic for Applications
Here’s an example that uses the Date variable type and displays it in a message box:
Sub DateDemo()Dim dt As DateDim dbl As Double
dt = Now ‘set the dt to the current date and timedbl = dt ‘assign this date value to a doubleMsgBox “Normal date version: “ & dt & “ Double version: “ & dblEnd Sub
Running DateDemo (by pressing F5) would show something similar to:
Normal date version: 5/10/2005 8:03:13 PMDouble version: 38482.8355671296
Creating VBA statements
Although a complete discussion of how to write VBA code is beyond the scope of this book,some general principles will be helpful
A statement in VBA is the most basic unit of code It contains a complete instruction Thereare three kinds of statements:
✦ A declaration names a variable, constant, or procedure, as in this example:
Dim dOrigin as Double
✦ An assignment assigns a value to a variable or constant For example:
dOrigin = 0#
✦ An executable creates an action For example, it can execute a method or function, or
create a loop or branch that acts on a block of code, as shown here:
Set myBox = ThisDrawing.ModelSpace.AddBox(dOrigin, dLength, dWidth,dHeight)
VBA has many keywords, functions, and other components that you can use to create code
To find the basic components of the VBA language, choose Help ➪ Microsoft Visual BasicHelp From the Contents tab, double-click Visual Basic Language Reference, which lists termsthat are part and parcel of VBA Here are some examples:
✦ Constants: Constants can be used anywhere in your code to provide a named value.
For example, VBA offers color and date constants that you can use to specify colorsand dates
✦ Functions: VBA includes many functions that you’ll find familiar if you’ve used AutoLISP.
For example, the ABSfunction returns the absolute value (without a plus or minus sign)
of any number The DATEfunction returns the current system date
✦ Keywords: Keywords are words that have a special meaning in VBA They are often
used as parts of VBA statements For example, Else is a keyword that is used in theIf Then Elsestatement You’re already familiar with the Set keyword, which isused in the Set statement
Trang 21You can also use & to concatenate text strings There are several logical operators,such as and, not, and or.
✦ Statements: Statements help you to create the flow of your code You’re already familiar
with the Set statement Other statements are For Each Next and If Then Else.These provide looping capabilities in VBA
Remember that you can also find a list of objects and their properties and methods in theObject Browser, as I explained earlier in this chapter
Getting User Input
The examples shown in this chapter weren’t very useful, partly because the routines vided no way to get user input for the properties of the objects that they drew There are twomain ways to get user input: on the command line and through a dialog box In this section,
pro-I explain how to get user input on the command line
In order to use the user-input methods, you need to first use something called the Utilityobject The Utility object belongs to the Document object, and controls the methods thatget user input You can also use ThisDrawing, as in the following example
Dim iReturn as IntegeriReturn = ThisDrawing.Utility.GetInteger(“Enter an integer: “)Here you set a variable called iReturn that is equal to the integer that the user types on thecommand line The prompt is Enter an integer:
You can use this type of user input to get a pick point, a numeric value (such as the radius of
a circle), a text string, or an object Use this method when the input is short and sweet
To avoid several prompts appearing on the same line, use vbCrLf, the carriage return/linefeedconstant, at the beginning of a prompt, as in the following example:
prompt1 = vbCrLf & “Specify center point: “Here’s an example that illustrates how to get user input on the command line:
Sub AddCircle()Dim thePt As VariantDim theRadius As DoubleDim myCircle As AcadCirclethePt = ThisDrawing.Utility.GetPoint(, vbCrLf & “Enter CenterPoint:”)
theRadius = ThisDrawing.Utility.GetReal(“Enter radius: “)Set myCircle = ThisDrawing.ModelSpace.AddCircle(thePt, theRadius)End Sub
Trang 22Chapter 37 ✦ Programming with Visual Basic for Applications
Table 37-3 lists some commonly used methods for getting user input If you know the GET
functions in AutoLISP, you’ll be familiar with these methods
Table 37-3: Common User-Input Methods
Method Syntax Description
GetEntity GetEntity Object, The user selects an object (entity) by picking it Returns the object
PickedPoint, Prompt in the first parameter and the point picked in the second parameter
The prompt is optional Example: ThisDrawing.Utility
GetEntity getObj, basePnt, “Select an object”wheregetObjhas been declared as an Object type variable
GetInteger RetVal = GetInteger Any integer from –32,768 to +32,767 is valid The prompt is
(Prompt) optional Example: getInt = ThisDrawing.Utility
GetInteger(“Enter an integer: “)GetPoint RetVal = GetPoint Returns a variant (which contains a three-element array of doubles)
(Point, Prompt) The user can pick a point, or type in a coordinate If the Point
parameter (optional) is provided, AutoCAD draws a rubber bandline from Point to the current crosshair position The prompt is alsooptional Example: getPnt = ThisDrawing Utility.GetPoint(, “Specify a point: “)
GetReal RetVal = GetReal Gets any real (positive or negative) number The prompt is optional
(Prompt) Example: getaReal = ThisDrawing.Utility.GetReal
(“Enter a real number: “)GetString RetVal = GetString The HasSpaces parameter specifies whether the string can contain
(HasSpaces, Prompt) spaces If the HasSpaces parameter is TRUE, the string can
contain blanks and the user must press Enter to end input IfHasSpacesis FALSE, either entering a blank or pressing Enterends input The prompt is optional Example: getaString =ThisDrawing.Utility.GetString(False, “Enter text(a space or <enter> terminates input):”)
STEPS: Creating a VBA Routine That Gets User Input
1 Open a new AutoCAD drawing using the acad.dwt template.
2 To start a new project, choose Tools ➪ Macro ➪ VBA Manager Click New and then click
Visual Basic Editor
3 Choose Insert ➪ Module and then choose Insert ➪ Procedure Name it HappyFace and
click OK
Trang 23Dim prompt As String, prompt2 As StringDim cen As Variant
Dim rad As DoubleDim cir As AcadCircleDim arc As AcadArcDim pi As DoubleDim dStart As Double ‘start angleDim dEnd As Double ‘end angle
pi = 3.1415prompt = vbCrLf & “Specify center point: “prompt2 = vbCrLf & “Specify radius: “
‘get center point from usercen = ThisDrawing.Utility.GetPoint(, prompt)rad = ThisDrawing.Utility.GetDistance(cen, prompt2)
‘draw headSet cir = ThisDrawing.ModelSpace.AddCircle(cen, rad)
‘draw smiledStart = 225 * pi / 180 ‘pi / 180 converts to radiansDEnd = 315 * pi / 180
Set arc = ThisDrawing.ModelSpace.AddArc(cen, rad / 2, dStart, dEnd)
‘draw eyescen(0) = cen(0) - rad / 4cen(1) = cen(1) + rad / 4Set cir = ThisDrawing.ModelSpace.AddCircle(cen, rad / 8)cen(0) = cen(0) + rad / 2
Set cir = ThisDrawing.ModelSpace.AddCircle(cen, rad / 8)
5 Change the module name to HappyFace.
6 Choose Save from the VBA IDE Standard toolbar, and save the VBA project as
ab37-02.dvbin your AutoCAD Bible folder
7 Return to your drawing and choose Tools ➪ Macro ➪ Macros In the Macros dialog box,
choose HappyFace and click Run
8 Respond to the prompts HappyFace draws the circle with the center point and radius
that you specify
You don’t need to save your drawing
The previous example uses GetDistance rather than GetReal to enable the user to selectthe radius of the circle with the mouse The center point that you previously selected feedsinto the GetDistance function Also, there are calculations to convert degrees to radians.The location and size of the eyes and smile are relative to the center and radius
Trang 25Understanding the Toolbox toolbar
The Toolbox toolbar contains the tools that you need to create a dialog box These are thefamiliar controls that you see in the dialog boxes that you use all the time, such as text boxes,list boxes, check boxes, and so on
Table 37-4 explains the Toolbox toolbar buttons
Table 37-4: The Toolbox Toolbar Buttons
Button Description
Select Objects Enables the user to select objectsLabel Creates a label on the dialog boxTextBox Enables the user to type in textComboBox Combines features of text and list boxesListBox Enables the user to choose from a listCheckBox Creates a box that can be checked or uncheckedOptionButton Enables the user to choose one option from several possibilities (also called a
radio button)ToggleButton Creates an on/off switchFrame Creates a box around a section of the dialog boxCommandButton Creates a button that executes a command, such as OK and Cancel buttonsTabStrip Creates tabs along the top of the dialog box
MultiPage Creates multiple pagesScrollBar Creates a scroll barSpinButton Enables the user to specify a numberImage Inserts an image
If you think that the Toolbox toolbar has a lot of possibilities, right-click the Toolbox toolbarand choose Additional Controls From the Additional Controls dialog box, you can choosefrom many more controls
Changing dialog-box properties
After you insert a user form, you should name it Find the Name property in the Propertieswindow, and change it from UserForm1 (the default name) to any useful name that you want
You might find it useful to use the word frm in the name For example, for a routine to draw a
circle, you could call the user form frmCircle
Tip
Trang 27Add a command button
To add a command button, click CommandButton on the Toolbox toolbar Move your cursorover the dialog box, and drag to create a button Figure 37-8 shows a dialog box with a newcommand button The selection border and handles indicate that the button is a selectedobject You can move the button by dragging it You can resize the button by dragging one ofthe handles Add all of the command buttons that you need Don’t forget to include at least aCancel button Many dialog boxes also have an OK button If you know in advance all of thecontrols that you’ll need, you can add them all at once
Figure 37-8: A dialog box with one
selected command button
There’s an art to laying out a dialog box so that it’s clear and easy to understand After awhile, you’ll get the hang of it Pay more attention to the dialog boxes that you use every day
to pick up some design pointers
Just as the dialog box has properties, each control on the dialog box has properties When acontrol such as a command button is selected, you see its properties in the Properties win-dow You generally would change at least the caption and the name of a command button.It’s a good idea to change the names to something meaningful, rather than using the defaultname For example, instead of CommandButton1, use a name such as cmdDrawBox or cmdOk
Write the VBA Code for a command button
After you create a command button, you can attach VBA code to it To attach VBA code
to a control, double-click the control The text editor opens with the Sub and End Sub linesalready entered for you Type the code that you want to attach to the button
VBA dialog boxes are modal by default, which means that they must be closed beforeAutoCAD can do anything further To close a dialog box after your VBA code has run, useUnload Meat the end of a routine
To run VBA code that is attached to a dialog box, you need to show the dialog box so thatyou can use it — click a command button, type in text, and so on The VBA IDE creates privatesubroutines for each dialog box control To show the dialog box, start a new module and cre-ate code that looks like the code in this example
Sub DrawArc()frmArc.ShowEnd Sub
Tip
Trang 28Chapter 37 ✦ Programming with Visual Basic for Applications
FrmArcis the name of the user form in this example Don’t forget to name the user form inthe Properties window Also, remember to name the module, because the module name iswhat appears in the Macro dialog box when you want to run the routine
Getting User Input for a Circle Radius
Here’s another example of a routine that draws a circle, although here you get user input for theradius using the VALfunction The VALfunction returns a numerical value from a text string Here youcreate a text box that enables users to type in a radius The VALfunction converts the string in thetext box to a number, and uses it as the circle’s radius Follow these steps:
1 Open AutoCAD with a new drawing, using the acad.dwt template Open the VBA IDE.
2 Choose Insert ➪ UserForm.
3 In the Properties window, change the name of the form to frmDrawCircle, and the
cap-tion to Draw a Circle Demo
4 From the Toolbox toolbar, choose Label and drag a small rectangle on the left side of the
form, around the middle
5 Change the name to lblRadius and the caption to Radius.
6 Choose Textbox on the Toolbox toolbar, and drag a box on the form to the right of the
label
7 Change the name to txtRadius.
8 Choose CommandButton on the Toolbox toolbar, and drag a larger box at the top-center
of the form
9 Change the name to cmdDrawCircle and the caption to Draw Circle.
10 Double-click this command button to bring up the code editor in the
cmdDrawCircle_Click ()subroutine
11 Add the following lines:
Dim dCenter(0 To 2) As DoubleDim dRadius As Double
Dim myCircle as AcadCircledCenter(0) = 0#
dCenter(1) = 0#
dCenter(2) = 0#
dRadius = Val(txtRadius)Set myCircle = ThisDrawing.ModelSpace.AddCircle(dCenter, dRadius)myCircle.Update
12 Close the code window Save the routine if you want On the VBA IDE menu, choose Run ➪
Run Sub/UserForm Visual Basic returns you to your drawing and displays the dialog box
Enter a number for the radius, and click the Draw Circle command button
13 Add as many circles as you like Click the Close box of the dialog box when you’re done.
Trang 29Add a label
A command button is quite simple You just click it, and it performs You can label its functionright on the command button However, most other controls require some more explanation.For example, if you want the user to type in text, you need a text box However, a text box has
no caption Therefore, you need to add instructions to the user A dialog box may also needother instructions to clarify the purpose of the controls, which responses are required, and
so on
You add instructions with the Label tool on the Toolbox toolbar Click Label and drag a angle on your dialog box Then type the label You can resize or move the label as needed
rect-Add other dialog-box controls
The code for some of the dialog-box controls can be quite complex For example, to create alist box that enables the user to choose from an existing list of options, you’d probably createthe list of options in advance For help on creating dialog boxes, choose Help ➪ Microsoft VisualBasic Help On the Contents tab, double-click Microsoft Forms Reference, and then MicrosoftForms Object Model Reference From there, you may want to double-click Objects, Collections,and Controls You can double-click a control, such as the ListBox control, and then read moreabout it The specific controls also offer hyperlinks to examples that you can look at
STEPS: Creating a Dialog Box with a Command Button
1 Open a new drawing in AutoCAD using the acad.dwt template.
2 To start a new project, choose Tools ➪ Macro ➪ VBA Manager Click New and then click
Visual Basic Editor
3 Choose Insert ➪ UserForm If the Toolbox toolbar covers the user form or project
win-dow, drag it to the right
4 With the user form active (click its title bar to make it active), change the Name
prop-erty of the user form to frmArc in the Properties window
5 Change the Caption property of the user form to Draw an arc Watch the caption of the
user form change as you type
6 Choose CommandButton on the Toolbox toolbar (It’s the last button in the second row.
If you don’t see the Toolbox toolbar, click in the user form on the right side of yourscreen.) Move the cursor over the user form, and drag to create a wide button acrossthe upper center of the user form
7 Change the Caption property of the button to Draw the Arc! Change the Name property
to cmdDrawArc
8 Again, choose CommandButton on the Toolbox toolbar Create a smaller button below
the first one near the right side of the user form
9 Change the Caption property of the smaller button to Cancel Change its Name
prop-erty to cmdCancel Your dialog box should look like the one in Figure 37-9
10 Double-click the larger button In the text editor, type the following code at the cursor’s
current location between the Private Sub and End Sub statements:
‘declare variablesDim startang As Double
Trang 30Chapter 37 ✦ Programming with Visual Basic for Applications
Dim endang As DoubleDim ctr(0 To 2) As DoubleDim rad As Double
Dim newarc As Object
‘specify arc parametersstartang = 0
‘angles are in radians
endang = 100ctr(0) = 5ctr(1) = 2ctr(2) = 0rad = 2
‘draw arcSet newarc = ThisDrawing.ModelSpace.AddArc(ctr, rad, startang,endang)
‘close dialog boxUnload Me
11 From the left (Object) drop-down list at the top of the text editor, choose cmdCancel to
add the code for the second button In the space below the start of the subroutine(Private Sub cmdCancel_Click()), type Unload Me
12 Choose Insert ➪ Module In the new text editor, type the following to display the
dialog box
Sub DrawArc() frmArc.Show
Visual Basic places the End Sub statement for you after the code
13 In the Properties window, change the module’s name to DrawArc.
14 Click Save on the toolbar and save the file in your AutoCAD Bible folder as
ab37-03.dvb
15 Return to your drawing Choose Tools ➪ Macro ➪ Macros In the Macros dialog box,
choose DrawArc and click Run
16 Click the large button AutoCAD draws the arc.
Figure 37-9: A simple dialog box created in VBA.
Trang 31To add a layer, use the Add method of the Layers collection of objects:
Set Newlayer1 = ThisDrawing.Layers.Add(“fixtures”)You can then set the layer’s properties For example, the following code makes the layer notplottable
Newlayer1.Plottable = FalseThe UPDATEcommand forces the changes to the current view It updates the change to thescreen so that you can see it For example, you can create a circle with the following code:Set myCircle = ThisDrawing.ModelSpace.AddCircle(dCenter, cRadius)
Accessing Other Applications
The true power of VBA comes when you can integrate other applications into your work For themost part, accessing other applications is beyond the scope of this book, but here are a couple
of simple examples that you may find helpful to explain the process
The technology that enables two applications or components to communicate with each other is
called automation Automation requires a client and a server The server is the application or ponent that provides services to the client The client is the application that makes use of these
com-services Many applications can perform as both Automation clients and Automation servers,including AutoCAD, Access, Excel, and Word Most ActiveX controls are Automation servers Anyapplication that supports VBA can be an Automation client
In order for a client to properly communicate with a server, it must properly use the server’sobject model or hierarchy (The AutoCAD object hierarchy was discussed earlier in this chapter.)You can view a server’s object model or hierarchy using the Object Browser Most componentshave a Type Library file (most have a TLB or OLB file name extension) that can be imported fromthe Tools ➪ References menu in the VBA IDE If the server is in the current list, make sure that it’schecked If it isn’t in the list, click Browse, locate its TLB file, and click Open This will add it to thelist of references and make it available to the Object Browser
There are two approaches for creating instances of automation component objects: early binding
and late binding With early binding, you use the VBA keyword New to reference the components
type library at design time With late binding, you declare a variable using the Object data type,and later use CreateObject or GetObject to create the specified type at runtime Early bindingoffers several benefits over late binding, including speed, syntax checking in the VBA editor, andonline help Some automation components do not support early binding
Trang 32Chapter 37 ✦ Programming with Visual Basic for Applications
This adds the circle to the current drawing’s database, but has not yet updated the view
If you do this from a dialog box, the view will not be updated until you exit the dialog box,
unless you force an update with the following code:
myCircle.Update
Using constants
Constants are names that are given to commonly used values For instance, AutoCAD definesconstants for the seven standard colors: acRed, acYellow, acGreen, acCyan, acBlue,acMagenta, and acWhite In the DrawCircle example, after creating the circle, you couldadd the following code to change its color to blue:
Dim clrObj As AcadAcCmColorSet clrObj = myCircle.TrueColorclrObj.ColorMethod = acColorMethodByACIclrObj.ColorIndex = acBlue
myCircle.TrueColor = clrObjMost functions or properties that have a standard set of values will have corresponding con-stants defined
Here are two Excel examples, one using early binding and the other using late binding:
Sub XlsEarly()Dim objXls As New Excel.Application
‘Note that the application is not launched until a property ormethod is referenced
MsgBox “Application: “ & objXls.Name & “ Version: “ &
objXls.VersionobjXls.Visible = TrueobjXls.Quit
Set objXls = NothingEnd Sub
Sub XlsLate()Dim objXls As Object
‘CreateObject will launch the applicationSet objXls = CreateObject(“Excel.Application”)MsgBox “Application: “ & objXls.Name & “ Version: “ &
objXls.VersionobjXls.Visible = TrueobjXls.Quit
Set objXls = NothingEnd Sub
Trang 33Using functions
Functions are a type of procedure (like subroutines), except that they return a value
Here’s an example for those of you who are counting the days until January 1, 2007
(If you’re reading this after that date, you can change it to a later date.) Alternatively, itwill tell you how many days ago January 1, 2006 occurred (indicated by a negative value).Function DaysTil2007() As Integer ‘notice “As Integer” tells
‘the return type of ‘the functionDim dtToday As Date ‘holds todays dateDim dt2007 As Date ‘holds Jan 1, 2007dtToday = Now() ‘assign today’s datedt2007 = CDate(“1/1/2007”) ‘assign Jan 1, 2007DaysTil2007 = dt2007 - dtToday ‘calculate difference,
‘return value assigned ‘to function nameEnd Function ‘same as End Sub
To use this function, you must do something with the return value through an assignment, oruse it as a parameter to another procedure For example:
Public Sub Test2007()MsgBox “Days until year 2007: “ & DaysTil2007()End Sub
You can then run the Test2007 sub to open a message box that tells you how many days areleft until the year 2007
Debugging and Trapping Errors
As with all programming languages, there are techniques to help you find the errors thatinevitably crop up Here is a simple debugging technique to get you started:
1 Go to the code editor and to the procedure where you suspect the error resides.
2 Place the cursor on the first executable statement in the procedure, and choose
Debug ➪ Toggle Breakpoint (or press F9)
3 Begin stepping through each statement by pressing F8 (Step Into).
4 For simple variables (Integers, Doubles, and Strings), you can place the mouse cursor
over the variable, and it will display the current contents You can also add variables tothe Watch window (choose View ➪ Watch Window) or enter commands in the Immediatewindow (choose View ➪ Immediate Window) to verify your logic
5 When an error is located, choose Run ➪ Reset and make the correction You can also
use Reset at any time you want to halt the routine
6 The next time you run the procedure, your breakpoint is still set At this point, you can
either step through again and verify whether your changes are correct, or press F9 totoggle the breakpoint off and choose Run ➪ Run to run the routine normally
Trang 34Chapter 37 ✦ Programming with Visual Basic for Applications
Unexpected errors may occur For example, a file that you attempt to open may not exist,your system may run out of memory and not be able to insert that AutoCAD block into yourdrawing, or you may unintentionally write a routine that divides by 0 You can, and should,plan for some of these errors; for others, it may not be possible to do so VBA provides amechanism for catching errors and handling them gracefully, rather than burping all overyour screen or locking up your system
A simple framework to begin error trapping would be:
Sub MyRoutine()
‘declare variables
On Error GoTo ErrorHandler
‘rest of procedure goes hereExit Sub ‘Tells subroutine to exit ignoring the
‘ErrorHandler statementsErrorHandler:
MsgBox “Error “ & Err.Number & “ “ & Err.DescriptionResume Next
End SubThis simple error trapping will at least alert you to any errors that occur by providing anerror number and description This will give you the opportunity to begin handling specificerrors appropriately as required
The Active X and VBA Developer’s Guide has a good discussion on handling errors in the
“Developing Applications with VBA” section
Moving to Advanced Programming
The chapters in this part have reviewed the fundamentals of Visual LISP and VBA, and you’veseen the power that these languages provide for automating your work However, they arenot the only options for programming AutoCAD
ObjectARX applications share the same memory space as AutoCAD, and are many timesfaster than routines written in AutoLISP or VBA ObjectARX is based on C++ and enables full
object-oriented interfacing with AutoCAD An object-oriented interface enables the
program-mer to create an object in memory (such as an arc), modify its attributes, and then modifythe AutoCAD database
You can create custom objects that inherit properties from AutoCAD objects; that is, yourobject can assume all of the properties of a given object that is already in AutoCAD, and youcan add to it For example, you can inherit from a line so that your custom object has every-thing that the line does, and then you can add width to it if you want ObjectARX offers a variety of tools that are unavailable to AutoLISP programmers; however, ObjectARX involves
much greater development time than AutoLISP You can use managed wrapper classes within
ObjectARX to create NET applications as well AutoCAD 2007 requires the Visual C++ NETcompiler to compile and link applications for use with AutoCAD ObjectARX can be obtained
at the Autodesk Web site (www.objectarx.com)
Trang 35In this chapter, you learned some basic principles of Visual Basics for Applications as applied
to AutoCAD Specifically, I discussed:
✦ Working with the VBA development environment
✦ Understanding VBA objects, methods, and properties
✦ Principles of writing VBA code
✦ How to get user input
✦ How to create dialog boxes
✦ How to modify objects
✦ Methods of debugging and trapping errors
A Final Word
AutoCAD offers almost unlimited potential for the design and drawing of real-world objects
I hope that this book helps you to understand the world of AutoCAD and makes it easier foryou to create the professional drawings that you need to redesign the world and make it abetter place Although I cannot provide technical support for my readers, I would be happy
to hear your comments and suggestions at ellen@ellenfinkelstein.com Best wishes andenjoy!
Trang 36The three appendixes in Part VIII provide important additionalinformation Although these appendixes are especially usefulwhen you first start to use AutoCAD 2007 or AutoCAD LT 2007, theyoffer a great deal of information for ongoing use as well
Appendix A runs you through the process of installing and configuringAutoCAD and AutoCAD LT to suit your personal needs Many new fea-tures appear in the Options dialog box that I cover here Appendix Blists numerous additional resources, where you can find information
on AutoCAD and AutoCAD LT, including discussion groups, Web sites,and blogs Appendix C explains what is on the CD-ROM and how touse the files there
In This Part
Appendix A
Installing andConfiguring AutoCADand AutoCAD LT
Trang 38Installing and Configuring AutoCAD and AutoCAD LT
Installing AutoCAD and AutoCAD LT, once something to avoid aslong as possible, is now a breeze For all practical purposes, allthat you need to do is to put the CD-ROM into your CD-ROM driveand follow the instructions Nevertheless, I provide some helpful tipsand comments in this appendix As with all software that comes with
an installation program, you should close all other applicationsbefore starting, including antivirus software
In this appendix, I also cover many ways to configure AutoCAD andAutoCAD LT so that these programs function best for your circum-stances
Installing AutoCAD and AutoCAD LT
The installation process involves some preparation, the actual lation, and finally authorization
instal-Preparing to install
Before you install, make sure that your system meets the minimum,and preferably the recommended, requirements:
✦ Operating system: Windows 2000 SP3 or SP4, Windows XP
(Home, Professional, or Tablet PC), with SP (Service Pack) 1/2
✦ Processor speed: IV or better, 800 MHz minimum, but I would
recommend 2.0 GHz as a minimum For 3D work, 3.0 GHz is recommended
✦ RAM (memory): 512MB, but I would recommend 1GB Although
2GB is recommended for 3D work, 512MB is acceptable formost AutoCAD LT work
configurationsConfiguring AutoCADand AutoCAD LT withthe Options dialog boxConfiguring a plotter
Trang 40Appendix A ✦ Installing and Configuring AutoCAD and AutoCAD LT
• Stand-alone installation: One seat (location) with one serial number.
• Multi-seat stand-alone deployment: Multiple seats with one serial number You
use the Deployment Wizard to install The next screen provides the tools that youneed, including Autodesk CAD Manager tools that list Autodesk software on eachcomputer on a network
• Network deployment (AutoCAD only): Multiple seats on a network, using
net-work licenses You use the Deployment Wizard to install, and the Netnet-workLicense Manager to manage the licenses The next screen provides the tools thatyou need, including CAD Manager tools
In these steps, I clicked the stand-alone installation option
3 The Install screen provides links to all of the installation tasks and information that you
need, as shown in Figure A-1 Click Install
Some plotter manufacturers, such as Hewlett-Packard, offer a special driver that optimizesthe plotter for use with AutoCAD Check the manufacturer’s Web site for the latest driver
Figure A-1: The Install screen when you choose a stand-alone installation.
4 A message tells you that support components must be installed These components are
Microsoft NET Framework 2.0, Autodesk DWF Viewer, DirectX 9.0 Runtime, and theFlash player Click OK
5 The Welcome screen advises you to close applications Antivirus software can
espe-cially be a problem; you should disable it during installation Click Next
6 On the next screen, choose your country from the drop-down list of countries at the
top, and then read the software license agreement Click “I accept,” and then click Next
Note