Programming with Visual Basic for Applications

30
V isual Basic for Applications (VBA) is a programming language and envi- ronment that is included with many Microsoft applications, such as Word, Excel, PowerPoint, and Access. Since Release 14, VBA has been available with AutoCAD as well. VBA is ideally suited for situations in which you need to work with more than one application at a time. ActiveX, which I dis- cussed 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 chapter introduces you to VBA and shows how you can start to use this powerful language to customize AutoCAD. AutoCAD LT does not support VBA. This entire chapter applies to AutoCAD only. Visual Basic for Applications is a variation of Visual Basic. Visual Basic is not related to any specific application. Visual Basic code is compiled into an exe- cutable file that stands alone, unrelated to any specific document. VBA, on the other hand, is connected to its application and the document in which you cre- ated the code. VBA provides a simple way to customize AutoCAD, automate tasks, and program applications from within the application. VBA in AutoCAD works slightly differently from VBA in most other applications, in that VBA projects are stored in a separate file, with the DVB filename exten- sion, but can also be stored within the drawing file. AUTOCAD ONLY AUTOCAD ONLY BC1 IN THIS CHAPTER Understanding VBA and AutoCAD Writing VBA code Getting user input Creating dialog boxes Modifying objects Creating loops and conditions Debugging and trapping errors Programming with Visual Basic for Applications

Transcript of Programming with Visual Basic for Applications

Page 1: Programming with Visual Basic for Applications

Visual Basic for Applications (VBA) is a programming language and envi-ronment that is included with many Microsoft applications, such asWord, Excel, PowerPoint, and Access. Since Release 14, VBA has been

available with AutoCAD as well. VBA is ideally suited for situations in which youneed to work with more than one application at a time. ActiveX, which I dis-cussed in the last chapter in relation to Visual LISP, enables you to access objectsin other applications. However, you can also use VBA to program AutoCADalone. This chapter introduces you to VBA and shows how you can start to usethis powerful language to customize AutoCAD.

AutoCAD LT does not support VBA. This entire chapter appliesto AutoCAD only.

Visual Basic for Applications is a variation of Visual Basic. Visual Basic is notrelated to any specific application. Visual Basic code is compiled into an exe-cutable file that stands alone, unrelated to any specific document. VBA, on theother hand, is connected to its application and the document in which you cre-ated the code. VBA provides a simple way to customize AutoCAD, automatetasks, and program applications from within the application.

VBA in AutoCAD works slightly differently from VBA in most other applications,in that VBA projects are stored in a separate file, with the DVB filename exten-sion, but can also be stored within the drawing file.

AUTOCAD ONLYAUTOCAD ONLY

BC1

IN THIS CHAPTERUnderstanding VBA andAutoCAD

Writing VBA code

Getting user input

Creating dialog boxes

Modifying objects

Creating loops and conditions

Debugging and trapping errors

Programming with VisualBasic for Applications

120491 bc37.qxp 5/21/07 3:11 PM Page BC1

Page 2: Programming with Visual Basic for Applications

Starting to Work with VBAAfter you decide to program AutoCAD, the first step is to select a programming language to use.

VBA has the following advantages:

n VBA is faster than AutoLISP, even when AutoLISP is compiled.

n VBA is common to many other applications. If you’ve used VBA before, you can easily transferyour knowledge to using VBA in AutoCAD. You’re also more likely to find other programmerswho know VBA compared to AutoLISP.

n 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 lan-guage that you already know and use.

VBA programs are saved in projects. A project contains all of the parts that are needed to execute the func-tion of the program. You can use the VBA Manager to view your VBA projects. The VBA Manager alsoenables you to load, unload, save, and create VBA projects. To open the VBA Manager, choose Tools ➪Macro ➪ VBA Manager.

Opening the VBA environmentTo start working with VBA, you must open the VBA environment. VBA has its own interface, just like VisualLISP. To open VBA in AutoCAD, choose Tools ➪ Macro ➪ Visual Basic Editor (or type vbaide ↵). LikeVisual LISP, VBA has its own interface, called an integrated development environment, or IDE. AutoCAD dis-plays the VBA environment window.

VBA projects can contain modules. A module is a self-contained piece of programming code. A VBA projectcan have one or more modules.

To add a module, choose Insert ➪ Module, or click the drop-down list to the right of the second button onthe VBA IDE Standard toolbar. Then choose Module. AutoCAD opens a module text editor window so thatyou 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.1 shows the VBA IDE, including the text editor. If you don’tsee the Project Explorer or the Properties window, use the View menu of the VBA IDE to choose ProjectExplorer or Properties Window.

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 to

enlarge the text editor to its maximum size.

AutoCAD is still running in the background. You can return to it at any time by clicking its button on theWindows task bar, or by clicking View AutoCAD on the VBA IDE Standard toolbar.

TIPTIP

BC2

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC2

Page 3: Programming with Visual Basic for Applications

FIGURE 37.1

The VBA environment window.

Getting acquainted with VBAVBA enables you to easily retrieve, create, and manipulate objects. To get a list of objects, open the ObjectBrowser by clicking Object Browser on the Standard toolbar or choosing View ➪ Object Browser. Objectsare organized into libraries. All of the objects that you work with in AutoCAD are in the AutoCAD library.

To see the list of AutoCAD objects, click the <All Libraries> drop-down list and choose AutoCAD. You cansee 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.

Objects and collections of objectsIn the left pane, labeled Classes, you see the list of objects. In VBA, you can have both individual objectsand collections of objects. For example, AcadLayer would be the layer object, and AcadLayers would be thecollection of layers. The purpose of collections is to enable you to work with a group of objects. For exam-ple, to add a layer, you add it to the collection of layers; this is because the new layer is not related to anyexisting layer.

TIPTIP

BC3

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC3

Page 4: Programming with Visual Basic for Applications

FIGURE 37.2

You can use the Object Browser to see the AutoCAD library of objects.

Methods and propertiesWhat can you do with objects in VBA? First, objects can have properties. For example, you can set anellipse to the color red because one of the properties of the ellipse object is TrueColor. (Of course, all draw-ing 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 candelete (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 any object that youchoose in the Classes pane.

Investigating the hierarchy modelAlthough you might first think that an object in VBA is the same as an object in an AutoCAD drawing, thereis 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 paper space are also objects. Therefore, to specifyan object in your drawing, you need to specify the application, the drawing, and finally the object in thedrawing. To do this, VBA works with a hierarchy of objects. For example, the hierarchy makes it possible todistinguish 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 each part of the def-inition. You then add the desired method or properties after another period. For example, you can use thefollowing VBA code to add a circle:

Application.ActiveDocument.ModelSpace.AddCircle(center, radius)

BC4

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC4

Page 5: Programming with Visual Basic for Applications

A shortcut for Application.ActiveDocument is ThisDrawing, and so you can also use:

ThisDrawing.ModelSpace.AddCircle(center, radius)

In order to work with any object, you need to know where it fits in the hierarchy. The quickest way to seethe hierarchical structure from the VBA IDE is to choose any method or property in the Object Browser andto choose Help on the Object Browser’s toolbar. On the Contents tab, choose Object Model to see the listingin Figure 37.3.

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 Object

Model to see the hierarchical model shown in Figure 37.3, or double-click Objects to see the alphabeticalobject list.

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. AutoCADopens 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. Nowclick the Microsoft Visual Basic button to return to the VBA IDE.

NOTENOTE

BC5

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC5

Page 6: Programming with Visual Basic for Applications

4. Click Object Browser on the VBA IDE Standard toolbar. Click the <All Libraries> drop-down listand choose AutoCAD. If necessary, maximize the window by clicking the Maximize button at thetop-right corner of the window.

5. In the Classes pane, click AcadLine. You see the associated properties and methods in the rightpane.

6. In the right pane, which is labeled Members of AcadLine, click Delete. You see the following atthe bottom of the window:

Sub Delete()Member of AutoCAD.AcadLineDeletes a specified object

Sub indicates the start of a VBA subroutine. Methods are listed in this way.

7. 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 object

This indicates that Layer is a property of AcadLine. String refers to the data type, discussedlater in this chapter.

8. Click Help in the Object Browser window. You see the Help page for the Layer property.

9. On the Contents tab, double-click Objects and then click Line object. Scroll down to see all of theproperties 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 ofVBA code for creating a line.

12. Close Help by clicking the Close button at the top-right corner of each window. Leave the VBAIDE window open if you’re continuing on to the next exercise.

Accessing helpVBA offers several help features. You’ve already seen the Object Browser, which provides you with a list ofobjects as well as their properties and methods. To access help on an object, choose it in Object Browserand 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, and then edit it as you want.

For more general help, AutoCAD offers two systems:

n The ActiveX and VBA Reference is an alphabetical listing of objects, methods, properties, andevents.

n The ActiveX and VBA Developer’s Guide explains ActiveX automation concepts and techniques.

To access these reference guides, switch to AutoCAD and choose Help ➪ Additional Resources ➪Developer Help.

The Microsoft Visual Basic for Applications Help provides information on the general VBA environment.Click Help on the VBA IDE Menu Bar toolbar, or choose Help ➪ Microsoft Visual Basic Help. Here you see

BC6

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC6

Page 7: Programming with Visual Basic for Applications

help for other VBA-enabled applications that you may have. You can use this when you’re ready to writeVBA code that integrates more than one application.

After you start programming, you can get help on any expression by clicking it and pressing F1. For exam-ple, you can type AddLine and press F1 to access help on how to create a line.

FIGURE 37.4

The help page for the Center Property.

Writing VBA CodeNow that you’re familiar with the structure of VBA objects, methods, and properties, you’re ready to startwriting some code. As with any programming language, you need to learn syntax and understand variablesand when to use them. Luckily, AutoCAD’s VBA Help includes many examples to guide you along the way.After you write some code, you can use it in AutoCAD.

Table 37.1 lists the various components of VBA code. This table defines various terms that you can oftenuse when working with VBA.

BC7

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC7

Page 8: Programming with Visual Basic for Applications

TABLE 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 aproperty.

Project A set of forms and modules.

Module A set of subroutines, functions, and declarations that are usually related and comprise adistinct 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 youcreate 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 theirattributes (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 for you. With a textor code window displayed, choose Insert ➪ Procedure to open the Add Procedure dialog box shown inFigure 37.5.

In the Name text box, type in a name for the new procedure, and then choose the type of procedure thatyou want to create. Choose whether you want the scope to be Public or Private and then click OK. If a sub-routine (called sub for short) is declared Public, it is visible (can be called) from other modules or from theAutoCAD Macros dialog box. A sub that is declared Private is visible only within that module.

FIGURE 37.5

The Add Procedure dialog box.

BC8

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC8

Page 9: 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 syntaxTo start programming, you need an idea of how a VBA routine is put together. Here is a complete VBA rou-tine that draws a 3D box.

‘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 ‘lengthDim 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#dOrigin(2) = 0#

dLength = 5# ‘make a cube 5 by 5 by 5dWidth = 5#dHeight = 5#

‘create the box in modelspace of the current drawingSet myBox = ThisDrawing.ModelSpace.AddBox(dOrigin, dLength, dWidth,

dHeight)‘change the viewpoint to better see the box

ThisDrawing.SendCommand (“VPOINT 1,1,1 “)

End Sub

Here’s what the code means:

n Line 1: Any text starting with an apostrophe (‘) is a comment. Placing comments in your rou-tines helps you and others to understand what you’re doing.

n Line 2: Sub indicates the start of a procedure, which is a named, unified piece of code. You canhave several subroutines in a VBA project. A project is the file that you save, and it has a DVB file-name extension. Each project contains the components of your subroutines, dialog boxes, and soon. The next word is the name of the subroutine. Within the parentheses, you can add arguments,if any. Use an empty set of parentheses if there are no arguments. Declaring variables is discussedlater in this chapter.

n Line 3: Another comment describing the next few lines of code. It’s always a good idea to com-ment your code, indicate what is happening, and even write notes to yourself to remind you ofyour intent.

n Line 4: You can also declare variables using the Dim statement. Here dOrigin is used as thevariable for the center of the box. (0 To 2) means that the origin will have three parts to it, forthe X, Y, and Z coordinates. Double is a type of variable that is suitable for most coordinates.More about variable types later.

NOTENOTE

BC9

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC9

Page 10: Programming with Visual Basic for Applications

n Lines 5–7: Here you declare the dLength, dWidth, and dHeight variables, which will be usedas the length, width, and height of the box. These are declared as type Double, which is alsoindicated by the d prefix on the variable names. This isn’t required, but it’s a good idea to use anaming scheme for variables to help remind you of their type, especially as you get deeper intoprogramming or have to come back to some code after not seeing it for a while.

n Line 8: Here you declare a variable called myBox as an Acad3DSolid to refer to the new boxthat will be created. Acad3DSolid is a data type that is specific to AutoCAD, and suitable for(you guessed it) referencing a 3D solid in your drawing. You can find other AutoCAD data typesby looking in the Object Browser, or by looking at the Object Model as I explained earlier in thischapter.

n Lines 9–11: Here you specify the X, Y, and Z coordinates of the origin of the box. The values areassigned to the dOrigin variable. The pound sign (#) is used to indicate a double-precisionfloating-point value. Use of the # sign is not required here but is more accurate and more clearlyindicates your intentions. In some situations, rounding errors can occur when assigning numbersof one type to variables of another type, such as when you assign integers to doubles and doublesto integers.

n Lines 12–14: Set the length, width, and height of the box to 5.

n Line 15: Another comment.

n Line 16: Finally, you’re ready to actually do something. The Set statement is used to set a vari-able to an object. Here you set the variable myBox to an Acad3DSolid defined byAddBox(dOrigin, dLength, dWidth, dHeight). The AddBox method creates a new 3Dbox. You need to define its origin, length, width, and height by using the variables that you’vepreviously defined. The AddBox method is a member of ModelSpace, which is a member ofThisDrawing. You use ThisDrawing in VBA to access the current drawing. Because VBAwithin AutoCAD is automatically connected to AutoCAD, you don’t need to specify the applica-tion (that is, AutoCAD).

n Line 17: Not another comment! Ask yourself these questions: If I looked at this code without thecomments, would I have a harder time understanding it? What if there is a bug and I ask anotherprogrammer to find it? What if I am that programmer?

n Line 18: Here we send the VPOINT command to change the viewpoint. Otherwise, the box thatwe just created will simply look like a square viewed from the top. The space after the numbers1,1,1 and before the quotation mark is important; it signifies the end of the command. It’s likepressing the Enter key for this command.

n 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 “Accessinghelp” section earlier in this chapter. In the preceding VBA routine, you might want to click AddBox andpress F1 to find the syntax and elements that are required for creating a box. Then click Example to see anactual example of code for that statement.

Saving a VBA routineAs I mention earlier, the AutoCAD version of VBA saves VBA projects as separate files with a DVB file nameextension. However, when you run a routine, AutoCAD lists it in the format ModuleName:ProcedureName. If your project has only one module, you can give the module and the procedure the same name.However, most VBA routines have more than one module, with one module controlling the rest. By runningthe controlling module, you run the whole project.

BC10

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC10

Page 11: Programming with Visual Basic for Applications

To name a module, look in the Properties window. After you’ve created a module, the VBA IDE lists itsname property as Module1 by default. Double-click Module1 and type a new name. Notice that the modulename in the Project window also changes accordingly.

A module name (as well as the names of other forms and controls) must start with a letter andcan be up to 31 characters. Only letters, numbers, and the underscore character are allowed.

To save a project as a separate file, which includes all of the modules, click Save on the VBA IDE Standardtoolbar. VBA returns you to AutoCAD and opens the Save As dialog box. 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 2008 folder, or use anotherfolder that is in AutoCAD’s support file search path.

Loading a VBA routineBefore you run a VBA routine, it must be loaded. If you’re working on the routine and want to run it tocheck how it works — which you’ll do often — you don’t need to load the routine. However, if you want torun a routine that hasn’t been loaded, you need to use the VBALOAD command. When you choose Tools ➪Macro ➪ Load Project (or type vbaload ↵), AutoCAD opens the Open VBA Project dialog box. Navigate toyour 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 routineAfter you complete a subroutine, you can run it in AutoCAD. After all, that’s the reason for writing VBAcode in the first place. To run a VBA routine, choose Tools ➪ Macro ➪ Macros (or type vbarun ↵). In theMacros dialog box, choose the module that you want to run and click Run. AutoCAD runs the module,including other modules that may be controlled by the module that you run.

Using the Visual Basic EditorWhen you type code from scratch in the Visual Basic Editor, you immediately notice that Visual Basic color-codes your text as you go. The most common colors are:

Normal text Black

Syntax-error text Red

Comments Green

Keyword text Blue

Keywords include variable types and other words that Visual Basic recognizes, such as Dim and 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.

When you start to type a keyword that Visual Basic recognizes, you’ll often see a box pop up that enablesyou to choose from a list, or that helps you to complete the word. The editor also adds or removes spacesand capitalizes certain words for you to improve your syntax. If you make a syntax mistake, a small errormessage often appears as you work. In these ways, the Visual Basic Editor helps you to type accurate code.

TIPTIP

NOTENOTE

BC11

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC11

Page 12: Programming with Visual Basic for Applications

STEPS: Creating, Saving, and Running a VBA Program

1. Start a new drawing using the acad.dwt template. Choose Tools ➪ Macro ➪ Visual BasicEditor.

2. Choose Insert ➪ Module. VBA opens the module text editor. (If you’ve previously opened a mod-ule, Visual Basic may launch with a blank module already open. In that case, skip this step.)

3. Choose Insert ➪ Procedure. In the Name text box, type DrawTorus. The type should be Sub andthe 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 DoubleDim dRadius2 As DoubleDim myTorus As Acad3DSolid

‘set center of torus to 0,0,0dCenter(0) = 0#dCenter(1) = 0#dCenter(2) = 0#

dRadius1 = 10# ‘torus radiusdRadius2 = 2# ‘tube radius

‘insert the torusSet myTorus = ThisDrawing.ModelSpace.AddTorus(dCenter, dRadius1,

dRadius2)

‘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 Standardtoolbar. 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 theMacros dialog box, choose DrawTorus and click Run. VBA draws and shades the torus.

Don’t save your drawing.

Here’s an explanation of the routine that you just wrote and used. Note that blank lines are ignored.

n Line 1: Comment describing routine.

n Line 2: This is a public subroutine named DrawTorus with no parameters.

n Line 3: Comment indicating which variable declarations are next.

n Line 4: Declare the array to hold the X, Y, and Z coordinates for the center of the torus.

n Line 5: Declare the variable to hold the radius of the torus.

n Line 6: Declare the variable to hold the radius of the tube.

n Line 7: Declare the variable to hold the created 3D object.

BC12

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC12

Page 13: Programming with Visual Basic for Applications

n Line 8: Comment.

n Lines 9–11: Set the center to 0,0,0.

n Line 12: Set the torus radius to 10.0.

n Line 13: Set the tube radius to 2.0.

n Line 14: Comment.

n Line 15: Create the torus.

n Line 16: Comment.

n Line 17: Send commands to AutoCAD to set the viewpoint and set the visual style to Conceptualfor better viewing.

n Line 18: End of subroutine.

Understanding variablesA variable holds a value for later use in your program. In VBA, you don’t need to explicitly declare yourvariables in advance (as long as you don’t include Option Explicit, which I explain later). You use the Setstatement to set a variable to an object, as in the example here. This statement creates a variable, cir, andsets its value equal to the circle that the AddCircle method 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 vari-able can contain numbers, dates, or strings (of text).

However, declaring variables explicitly in advance has two advantages:

n You can specify the type of variable, which usually uses less memory than the default variant type.

n As you continue to enter code, VBA checks the variable’s spelling for you, thus reducing thechance for errors.

You declare variables using the Dim statement. Here’s an example:

Dim radius As Double

You can create three different levels of variables:

n A Public variable is available to all procedures in the project. It is shown as follows:

Public dRadius As Double

n A module-level variable is available to all of the procedures in the module. You create a module-level variable by placing the declaration (with the Dim statement) at the top of a module, in aDeclarations section. Another way to create a module-level variable is to use the Private state-ment. Examples are shown here:

Dim dNum3 as DoublePrivate dNum2 as Double

n A procedure-level variable is used only within a procedure. You can place the variable anywherewithin 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 be declared.Using Option Explicit is a way to force yourself to write your code more carefully. Declared variables areeasier to debug because they’re easier to find.

BC13

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC13

Page 14: Programming with Visual Basic for Applications

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 variablefor 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 thansingle variables. Most coordinates use this variable type. Three double variables create 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 isthe 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 punctuationcharacters.

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 usesthis type by default.

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 double

MsgBox “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 statementsAlthough a complete discussion of how to write VBA code is beyond the scope of this book, some generalprinciples will be helpful.

BC14

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC14

Page 15: Programming with Visual Basic for Applications

A statement in VBA is the most basic unit of code. It contains a complete instruction. There are three kindsof statements:

n A declaration names a variable, constant, or procedure, as in this example:

Dim dOrigin as Double

n An assignment assigns a value to a variable or constant. For example:

dOrigin = 0#

n An executable creates an action. For example, it can execute a method or function, or create aloop 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 thebasic components of the VBA language, choose Help ➪ Microsoft Visual Basic Help. From the Contents tab,double-click Visual Basic Language Reference, which lists terms that are part and parcel of VBA. Here aresome examples:

n Constants: Constants can be used anywhere in your code to provide a named value. For exam-ple, VBA offers color and date constants that you can use to specify colors and dates.

n Functions: VBA includes many functions that you’ll find familiar if you’ve used AutoLISP. Forexample, the ABS function returns the absolute value (without a plus or minus sign) of any num-ber. The DATE function returns the current system date.

n Keywords: Keywords are words that have a special meaning in VBA. They are often used as partsof VBA statements. For example, Else is a keyword that is used in the If...Then...Elsestatement. You’re already familiar with the Set keyword, which is used in the Set statement.

n Operators: VBA includes all of the usual arithmetic operations, such as +, –, *, /, and ^. You canalso use & to concatenate text strings. There are several logical operators, such as and, not, and or.

n Statements: Statements help you to create the flow of your code. You’re already familiar with theSet statement. Other statements are For Each...Next and If...Then...Else. These pro-vide looping capabilities in VBA.

Remember that you can also find a list of objects and their properties and methods in the Object Browser, asI explained earlier in this chapter.

Getting User InputThe examples shown in this chapter weren’t very useful, partly because the routines provided no way to getuser input for the properties of the objects that they drew. There are two main ways to get user input: on thecommand line and through a dialog box. In this section, I explain how to get user input on the commandline.

In order to use the user-input methods, you need to first use something called the Utility object. The Utilityobject belongs to the Document object and controls the methods that get user input. You can also useThisDrawing, as in the following example.

Dim iReturn as IntegeriReturn = ThisDrawing.Utility.GetInteger(“Enter an integer: “)

BC15

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC15

Page 16: Programming with Visual Basic for Applications

Here you set a variable called iReturn that is equal to the integer that the user types on the commandline. 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 textstring, 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/linefeed constant, atthe 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 AcadCircle

thePt = ThisDrawing.Utility.GetPoint(, vbCrLf & “Enter CenterPoint:”)theRadius = ThisDrawing.Utility.GetReal(“Enter radius: “)Set myCircle = ThisDrawing.ModelSpace.AddCircle(thePt, theRadius)

End Sub

Table 37.3 lists some commonly used methods for getting user input. If you know the GET functions inAutoLISP, you’ll be familiar with these methods.

TABLE 37.3

Common User-Input Methods

Method Syntax Description

GetEntity GetEntity Object, PickedPoint, Prompt The user selects an object (entity) by picking it.Returns the object in the first parameter and thepoint picked in the second parameter. The prompt isoptional. Example:ThisDrawing.Utility.GetEntity getObj,basePnt, “Select an object” where getObjhas been declared as an Object type variable.

GetInteger RetVal = GetInteger (Prompt) Any integer from –32,768 to +32,767 is valid. Theprompt is optional. Example: getInt =ThisDrawing.Utility.GetInteger(“Enter an integer: “)

GetPoint RetVal = GetPoint (Point, Prompt) Returns a variant (which contains a three-elementarray of doubles). The user can pick a point, or typein a coordinate. If the Point parameter (optional)is provided, AutoCAD draws a rubber band linefrom Point to the current crosshair position. Theprompt is also optional. Example: getPnt =ThisDrawing. Utility.GetPoint(,“Specify a point: “)

BC16

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC16

Page 17: Programming with Visual Basic for Applications

Method Syntax Description

GetReal RetVal = GetReal (Prompt) Gets any real (positive or negative) number. Theprompt is optional. Example: getaReal =ThisDrawing.Utility.GetReal(“Enter areal number: “)

GetString RetVal = GetString (HasSpaces, Prompt) The HasSpaces parameter specifies whether thestring can contain spaces. If the HasSpacesparameter is TRUE, the string can contain blanksand the user must press Enter to end input. IfHasSpaces is FALSE, either entering a blank orpressing Enter ends 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. Start 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 VisualBasic Editor.

3. Choose Insert ➪ Module and then choose Insert ➪ Procedure. Name it HappyFace and click OK.

4. At the cursor, type the following:

Dim prompt As String, prompt2 As StringDim cen As VariantDim 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 smile

dStart = 225 * pi / 180 ‘pi / 180 converts to radiansDEnd = 315 * pi / 180

BC17

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC17

Page 18: Programming with Visual Basic for Applications

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 / 2Set 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.dvb inyour AutoCAD Bible folder.

7. Return to your drawing and choose Tools ➪ Macro ➪ Macros. In the Macros dialog box, chooseHappyFace and click Run.

8. Respond to the prompts. HappyFace draws the circle with the center point and radius that youspecify.

You don’t need to save your drawing.

The previous example uses GetDistance rather than GetReal to enable the user to select the radius ofthe circle with the mouse. The center point that you previously selected feeds into the GetDistance func-tion. Also, there are calculations to convert degrees to radians. The location and size of the eyes and smileare relative to the center and radius.

Creating Dialog BoxesOne of the main characteristics of VBA is the ease with which you can create dialog boxes to get user input.Whenever you need input that is more complex than you can get using the Get methods, you should use adialog box. You can also use a dialog box to create a more professional look or for ease of use.

When working with a dialog box, you generally create the dialog box first and then attach code to the dia-log box buttons. You then use a second module to display the dialog box. Running the second module thencontrols the entire routine.

In VBA, a dialog box is called a user form. To create one, choose Insert ➪ UserForm. VBA creates a blankuser form that will become your dialog box. Simultaneously, the Toolbox toolbar appears. If this toolbarcovers up some other part of your screen, drag it to one side. Your screen should look like Figure 37.6.

Understanding the Toolbox toolbarThe Toolbox toolbar contains the tools that you need to create a dialog box. These are the familiar controls thatyou 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.

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 choose from

many more controls.

TIPTIP

BC18

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC18

Page 19: Programming with Visual Basic for Applications

FIGURE 37.6

The VBA IDE with a blank user form and the Toolbox toolbar.

TABLE 37.4

The Toolbox Toolbar Buttons

Button Description

Select Objects Enables the user to select objects

Label Creates a label on the dialog box

TextBox Enables the user to type in text

ComboBox Combines features of text and list boxes

ListBox Enables the user to choose from a list

CheckBox Creates a box that can be checked or unchecked

continued

BC19

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC19

Page 20: Programming with Visual Basic for Applications

TABLE 37.4 (continued)

Button Description

OptionButton Enables the user to choose one option from several possibilities (also called a radio button)

ToggleButton Creates an on/off switch

Frame Creates a box around a section of the dialog box

CommandButton Creates a button that executes a command, such as OK and Cancel buttons

TabStrip Creates tabs along the top of the dialog box

MultiPage Creates multiple pages

ScrollBar Creates a scroll bar

SpinButton Enables the user to specify a number

Image Inserts an image

Changing dialog box propertiesAfter you insert a user form, you should name it. Find the Name property in the Properties window, andchange it from UserForm1 (the default name) to any useful name that you want. You might find it useful touse the word frm in the name. For example, for a routine to draw a circle, you could call the user formfrmCircle.

Figure 37.7 shows the property box when you insert a user form. You can easily change the dialog box’sproperties in the property box.

One property that you’ll want to change is the Caption property of the dialog box. The dialog box shouldhave a caption that summarizes its purpose. When you type the new caption in the property box, the cap-tion on the dialog box changes at the same time.

Adding dialog box controlsOne of the more commonly used controls is the command button. A command button is a button that youclick in the dialog box to execute an action. The most familiar command buttons are the OK and Cancelbuttons.

Add a command buttonTo add a command button, click CommandButton on the Toolbox toolbar. Move your cursor over the dia-log box, and drag to create a button. Figure 37.8 shows a dialog box with a new command button. Theselection border and handles indicate that the button is a selected object. You can move the button by drag-ging it. You can resize the button by dragging one of the handles. Add all of the command buttons that youneed. Don’t forget to include at least a Cancel button. Many dialog boxes also have an OK button. If youknow in advance all of the controls that you’ll need, you can add them all at once.

There’s an art to laying out a dialog box so that it’s clear and easy to understand. After a while,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.

TIPTIP

BC20

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC20

Page 21: Programming with Visual Basic for Applications

FIGURE 37.7

When you insert a user form (dialog box), the Properties window lists all of its properties.

FIGURE 37.8

A dialog box with one selected command button.

Just as the dialog box has properties, each control on the dialog box has properties. When a control such asa command button is selected, you see its properties in the Properties window. You generally would changeat least the caption and the name of a command button. It’s a good idea to change the names to somethingmeaningful, rather than using the default name. For example, instead of CommandButton1, use a namesuch as cmdDrawBox or cmdOk.

BC21

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC21

Page 22: Programming with Visual Basic for Applications

Write the VBA Code for a command buttonAfter 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 lines already entered for you.Type the code that you want to attach to the button.

BC22

Programming AutoCADPart VII

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 the radiususing the VAL function. The VAL function returns a numerical value from a text string. Here you create a

text box that enables users to type in a radius. The VAL function converts the string in the text box to a numberand 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 caption toDraw 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 theform.

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 DoubleDim myCircle as AcadCircle

dCenter(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 anumber 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.

120491 bc37.qxp 5/21/07 3:11 PM Page BC22

Page 23: Programming with Visual Basic for Applications

VBA dialog boxes are modal by default, which means that they must be closed before AutoCAD can do any-thing further. To close a dialog box after your VBA code has run, use Unload Me at the end of a routine.

To run VBA code that is attached to a dialog box, you need to show the dialog box so that you can use it —click a command button, type in text, and so on. The VBA IDE creates private subroutines for each dialogbox control. To show the dialog box, start a new module and create code that looks like the code in thisexample:

Sub DrawArc()frmArc.ShowEnd Sub

FrmArc is the name of the user form in this example. Don’t forget to name the user form in the Propertieswindow. Also, remember to name the module, because the module name is what appears in the Macro dia-log box when you want to run the routine.

Add a labelA command button is quite simple. You just click it, and it performs. You can label its function right on thecommand button. However, most other controls require some more explanation. For example, if you wantthe user to type in text, you need a text box. However, a text box has no caption. Therefore, you need toadd instructions to the user. A dialog box may also need other instructions to clarify the purpose of the con-trols, which responses are required, and so on.

You add instructions with the Label tool on the Toolbox toolbar. Click Label and drag a rectangle on yourdialog box. Then type the label. You can resize or move the label as needed.

Add other dialog box controlsThe code for some of the dialog box controls can be quite complex. For example, to create a list box thatenables the user to choose from an existing list of options, you’d probably create the list of options inadvance. For help on creating dialog boxes, choose Help ➪ Microsoft Visual Basic Help. On the Contentstab, double-click Microsoft Forms Reference, and then Microsoft Forms Object Model Reference. Fromthere, you may want to double-click Objects, Collections, and Controls. You can double-click a control,such as the ListBox control, and then read more about it. The specific controls also offer hyperlinks toexamples that you can look at.

STEPS: Creating a Dialog Box with a Command Button

1. Start 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 VisualBasic Editor.

3. Choose Insert ➪ UserForm. If the Toolbox toolbar covers the user form or project window, drag itto the right.

4. With the user form active (click its title bar to make it active), change the Name property of theuser 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 formchange as you type.

6. Choose CommandButton on the Toolbox toolbar. (It’s the last button in the second row. If youdon’t see the Toolbox toolbar, click in the user form on the right side of your screen.) Move thecursor over the user form and drag to create a wide button across the upper center of the userform.

BC23

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC23

Page 24: Programming with Visual Basic for Applications

7. Change the Caption property of the button to Draw the Arc!. Change the Name property tocmdDrawArc.

8. Again, choose CommandButton on the Toolbox toolbar. Create a smaller button below the firstone near the right side of the user form.

9. Change the Caption property of the smaller button to Cancel. Change its Name property tocmdCancel. Your dialog box should look like the one in Figure 37.9.

FIGURE 37.9

A simple dialog box created in VBA.

10. Double-click the larger button. In the text editor, type the following code at the cursor’s currentlocation between the Private Sub and End Sub statements:

‘declare variablesDim startang As DoubleDim endang As DoubleDim ctr(0 To 2) As DoubleDim rad As DoubleDim 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 thecode for the second button. In the space below the start of the subroutine (Private SubcmdCancel_Click()), type Unload Me.

BC24

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC24

Page 25: Programming with Visual Basic for Applications

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, chooseDrawArc and click Run.

16. Click the large button. AutoCAD draws the arc.

Modifying ObjectsModifying objects is usually very easy. You need to know the name of the object. If you’ve created it, you setit equal to a variable, and then you can use that variable.

If you’ve created a circle named cir1, the following code changes its layer to “fixtures”, assuming that“fixtures” exists:

Cir1.layer = “fixtures”

To 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 not plottable.

Newlayer1.Plottable = False

The UPDATE command forces the changes to the current view. It updates the change to the screen so that youcan see it. For example, you can create a circle with the following code:

Set myCircle = ThisDrawing.ModelSpace.AddCircle(dCenter, cRadius)

This adds the circle to the current drawing’s database, but has not yet updated the view. If you do this froma dialog box, the view will not be updated until you exit the dialog box, unless you force an update with thefollowing code:

myCircle.Update

Using constantsConstants are names that are given to commonly used values. For instance, AutoCAD defines constants for theseven standard colors: acRed, acYellow, acGreen, acCyan, acBlue, acMagenta, and acWhite. In theDrawCircle example, after creating the circle, you could add the following code to change its color to blue:

Dim clrObj As AcadAcCmColorSet clrObj = myCircle.TrueColorclrObj.ColorMethod = acColorMethodByACIclrObj.ColorIndex = acBluemyCircle.TrueColor = clrObj

Most functions or properties that have a standard set of values will have corresponding constants defined.

BC25

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC25

Page 26: Programming with Visual Basic for Applications

BC26

Programming AutoCADPart VII

Accessing Other Applications

The true power of VBA comes when you can integrate other applications into your work. For the most 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 calledautomation. Automation requires a client and a server. The server is the application or component that pro-vides services to the client. The client is the application that makes use of these services. Many applicationscan perform as both Automation clients and Automation servers, including AutoCAD, Access, Excel, andWord. Most ActiveX controls are Automation servers. Any application that supports VBA can be anAutomation client.

In order for a client to properly communicate with a server, it must properly use the server’s object model orhierarchy. (The AutoCAD object hierarchy was discussed earlier in this chapter.) You can view a server’s objectmodel or hierarchy using the Object Browser. Most components have a Type Library file (most have a TLB orOLB filename extension) that can be imported from the Tools ➪ References menu in the VBA IDE. If the serveris in the current list, make sure that it’s checked. If it isn’t in the list, click Browse, locate its TLB file, and clickOpen. This will add it to the list of references and make it available to the Object Browser.

There are two approaches for creating instances of automation component objects: early binding and latebinding. With early binding, you use the VBA keyword New to reference the components type library atdesign time. With late binding, you declare a variable using the Object data type, and later useCreateObject or GetObject to create the specified type at runtime. Early binding offers several benefitsover late binding, including speed, syntax checking in the VBA editor, and online help. Some automationcomponents do not support early binding.

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 or method

is referencedMsgBox “Application: “ & objXls.Name & “ Version: “ & objXls.VersionobjXls.Visible = TrueobjXls.QuitSet objXls = Nothing

End 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.QuitSet objXls = Nothing

End Sub

120491 bc37.qxp 5/21/07 3:11 PM Page BC26

Page 27: Programming with Visual Basic for Applications

Using functionsFunctions are a type of procedure (like subroutines), except that they return a value. Here’s an example forthose of you who are counting the days until January 1, 2008. (If you’re reading this after that date, you canchange it to a later date.) Alternatively, it will tell you how many days ago January 1, 2008 occurred (indi-cated by a negative value).

Function DaysTil2008() As Integer ‘notice “As Integer” tells‘the return type of ‘the function

Dim dtToday As Date ‘holds today’s dateDim dt2008 As Date ‘holds Jan 1, 2008

dtToday = Now() ‘assign today’s datedt2008 = CDate(“1/1/2008”) ‘assign Jan 1, 2008DaysTil2008 = dt2008 - 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, or use it as aparameter to another procedure. For example:

Public Sub Test2008()MsgBox “Days until year 2008: “ & DaysTil2008()End Sub

You can then run the Test2008 sub to open a message box that tells you how many days are left until theyear 2008.

Debugging and Trapping ErrorsAs with all programming languages, there are techniques to help you find the errors that inevitably 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 ➪ ToggleBreakpoint (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 thevariable, and it will display the current contents. You can also add variables to the Watch window(choose View ➪ Watch Window) or enter commands in the Immediate window (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 atany 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 eitherstep through again and verify whether your changes are correct, or press F9 to toggle the break-point off and choose Run ➪ Run to run the routine normally.

BC27

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC27

Page 28: Programming with Visual Basic for Applications

Unexpected errors may occur. For example, a file that you attempt to open may not exist, your system mayrun out of memory and not be able to insert that AutoCAD block into your drawing, or you may uninten-tionally write a routine that divides by 0. You can, and should, plan for some of these errors; for others, itmay not be possible to do so. VBA provides a mechanism for catching errors and handling them gracefully,rather than burping all over your 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 statements

ErrorHandler:MsgBox “Error “ & Err.Number & “ “ & Err.Description

Resume NextEnd Sub

This simple error trapping will at least alert you to any errors that occur by providing an error number anddescription. This will give you the opportunity to begin handling specific errors appropriately as required.

The Active X and VBA Developer’s Guide has a good discussion on handling errors in the “DevelopingApplications with VBA” section.

Moving to Advanced ProgrammingThe chapters in this part have reviewed the fundamentals of Visual LISP and VBA, and you’ve seen thepower that these languages provide for automating your work. However, they are not the only options forprogramming AutoCAD.

ObjectARX applications share the same memory space as AutoCAD, and are many times faster than routineswritten in AutoLISP or VBA. ObjectARX is based on C++ and enables full object-oriented interfacing withAutoCAD. An object-oriented interface enables the programmer to create an object in memory (such as anarc), modify its attributes, and then modify the AutoCAD database.

You can create custom objects that inherit properties from AutoCAD objects; that is, your object can assumeall of the properties of a given object that is already in AutoCAD, and you can add to it. For example, youcan inherit from a line so that your custom object has everything that the line does, and then you can addwidth 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 wrapperclasses within ObjectARX to create .NET applications as well. AutoCAD 2008 requires the Visual C++ 2005(version 8.0) compiler to compile and link applications for use with AutoCAD. ObjectARX can be obtainedat the Autodesk Web site (www.objectarx.com).

BC28

Programming AutoCADPart VII

120491 bc37.qxp 5/21/07 3:11 PM Page BC28

Page 29: Programming with Visual Basic for Applications

SummaryIn this chapter, you learned some basic principles of Visual Basics for Applications as applied to AutoCAD.Specifically, I discussed:

n Working with the VBA development environment

n Understanding VBA objects, methods, and properties

n Principles of writing VBA code

n How to get user input

n How to create dialog boxes

n How to modify objects

n Methods of debugging and trapping errors

A Final WordAutoCAD offers almost unlimited potential for the design and drawing of real-world objects. I hope thatthis book helps you to understand the world of AutoCAD and makes it easier for you to create the profes-sional drawings that you need to redesign the world and make it a better place. Although I cannot providetechnical support for my readers, I would be happy to hear your comments and suggestions [email protected]. Best wishes and enjoy!

BC29

Programming with Visual Basic for Applications 37

120491 bc37.qxp 5/21/07 3:11 PM Page BC29

Page 30: Programming with Visual Basic for Applications

120491 bc37.qxp 5/21/07 3:11 PM Page BC30