Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Autocad 2005 And Autocad LT 2005 Bible (2004).pdf
Скачиваний:
92
Добавлен:
17.08.2013
Размер:
32.22 Mб
Скачать

1072 Part VII Programming AutoCAD

Modifying Objects

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

If you’ve created a circle named cir1, the following code changes its layer to “fixtures”, assuming “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”)

To set the new layer’s color, use the Color property. This code sets the color to red, using the red color constant. Constants are discussed in the next section.

Newlayer1.Color = acRed

The update command forces the changes to the current view. It updates the change to the screen so you can 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 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 given to commonly used values. For instance, AutoCAD defines constants for the seven standard colors: acRed, acYellow, acGreen, acCyan, acBlue, acMagenta, and acWhite. In the DrawCircle example, after creating the circle you could add the following to change its color to blue:

myCircle.Color = acBlue

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

Using functions

Functions are a type of procedure (like subroutines) except they return a value. Here’s an example for those of you who are counting the days until January 1, 2005. (If you’re reading this after that date, you can change it to a later date.) Or it will tell you how many days ago January 1, 2004 occurred (indicated by a negative value).

Function DaysTil2005() As Integer

‘notice “As Integer” tells

‘the return type of

‘the function

Dim dtToday As Date

‘holds todays date

Dim dt2005 As Date

‘holds Jan 1, 2005

dtToday = Now()

‘assign today’s date

dt2005 = CDate(“1/1/2005”)

‘assign Jan 1, 2005

Chapter 37 Programming with Visual Basic for Applications 1073

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 you may find helpful to explain the process.

The technology enabling 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 component that provides services to the client. The client is the application that makes use of these services. Many applications can perform as both Automation clients and Automation servers including AutoCAD, Access, Excel, and Word. Most ActiveX controls are Automation servers. Any application that supports VBA has the capability to be an Automation client.

In order for a client to properly communicate with a server, it must properly use the server’s object 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 components have a Type Library file (most have a TLB or OLB filename extension) that can be imported from the Tools References menu in the VBA IDE. If the server is in the current list, make sure it’s checked. If it isn’t in the list, click Browse, locate its TLB file, and click Open. 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 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 binding offers several benefits over late binding, including speed, syntax checking in the VBA editor, and online help. Some automation components 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 referenced

MsgBox “Application: “ & objXls.Name & “ Version: “ & objXls.Version

objXls.Visible = True objXls.Quit

Set objXls = Nothing End Sub

Sub XlsLate()

Dim objXls As Object

‘ CreateObject will launch the application

Set objXls = CreateObject(“Excel.Application”)

MsgBox “Application: “ & objXls.Name & “ Version: “ & objXls.Version

objXls.Visible = True objXls.Quit

Set objXls = Nothing End Sub

1074 Part VII Programming AutoCAD

DaysTil2005 = dt2005 - dtToday ‘calculate difference,

‘return value assigned

‘to function

name

End Function

‘same as End

Sub

To use this function you must do something with the return value via an assignment or use it as a parameter to another procedure. For example:

Public Sub Test2005()

MsgBox “Days until year 2005: “ & DaysTil2005()

End Sub

You can then run the Test2005 sub to open a message box that tells you how many days are left until the year 2005.

Debugging and Trapping Errors

As 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 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 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 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 if your changes are correct or press F9 to toggle the breakpoint off and choose Run Run to run the routine normally.

Unexpected errors occur. A file you attempt to open doesn’t exist, your system runs out of memory and can’t insert that AutoCAD block into your drawing, or you unintentionally write a routine that divides by 0. Some of these errors you can and should plan for; others maybe not. 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 here

Exit Sub

Tells subroutine to exit ignoring the

 

ErrorHandler statements

ErrorHandler:

 

 

Chapter 37 Programming with Visual Basic for Applications 1075

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

Resume Next

End Sub

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

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’ve seen the power these languages provide for automating your work. However, they are not the only options for programming AutoCAD.

ObjectARX applications share the same memory space as AutoCAD and are many times faster than routines written in AutoLISP or VBA. ObjectARX is based on C++ and enables full objectoriented interfacing with AutoCAD. An object-oriented interface enables the programmer to create an object in memory (such as an arc), 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 assume all the properties of a given object already in AutoCAD, and you can add to it. For example, you can inherit from a line so your custom object has everything 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. ObjectARX involves much greater development time than AutoLISP. AutoCAD 2005 requires the Visual C++ .NET compiler to compile and link applications for use with AutoCAD. ObjectARX can be obtained at the Autodesk Web site (www.autodesk.com).

A Final Word

AutoCAD offers almost unlimited potential for the design and drawing of real-world objects. I hope this book helps you understand the world of AutoCAD and makes it easier for you to create the professional drawings you need to redesign the world and make it a better place. Although I cannot provide technical support for my readers, I would be happy to hear your comments and suggestions at ellenfinkl@bigfoot.com. Good luck and enjoy!

 

 

 

Appendixes

The two appendixes in Part VIII provide important additional information. These appendixes are especially useful when you first

start to use AutoCAD 2005 or AutoCAD LT 2005, but they offer a great deal of information for ongoing use as well.

Appendix A runs you through the process of installing and configuring AutoCAD and AutoCAD LT to suit your personal needs. Appendix B explains what is on the CD-ROM and how to use the files there.

Note The CD-ROM contains two bonus chapters that were originally designed as appendixes (but we ran out of space). Bonus Chapter 1 lists and briefly describes all the new and changed commands and system variables. Bonus Chapter 2 contains a roundup of AutoCAD and AutoCAD LT resources, including discussion groups and Web sites.

P A R T

VIII

In This Part

Appendix A

Installing and

Configuring AutoCAD

and AutoCAD LT

Appendix B

What’s on the CD-ROM