Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Книги_AutoCad_2 / AutoCAD 2006 and AutoCAD LT 2006 Bible_2004г__.pdf
Скачиваний:
142
Добавлен:
09.04.2015
Размер:
17.83 Mб
Скачать

1120 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 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 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 that are 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 code 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 that they return a value. Here’s an example for those of you who are counting the days until January 1, 2006. (If you’re reading this after that date, you can change it to a later date.) Alternatively, it will tell you how many days ago January 1, 20046 occurred (indicated by a negative value).

Function DaysTil2006() As Integer

‘notice “As Integer” tells

‘the return type of

‘the function

Dim dtToday As Date

‘holds todays date

Dim dt2006 As Date

‘holds Jan 1, 2006

dtToday = Now()

‘assign today’s date

dt2006 = CDate(“1/1/2006”)

‘assign Jan 1, 2006

DaysTil2006 = dt2006 - dtToday

‘calculate difference,

‘return value assigned

‘to function name

End Function

‘same as End Sub

Chapter 37 Programming with Visual Basic for Applications 1121

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 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 can 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 file name extension) that can be imported from the Tools References menu in the VBA IDE. If the server is in the current list, make sure that 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

1122 Part VII Programming AutoCAD

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

Public Sub Test2006()

MsgBox “Days until year 2006: “ & DaysTil2006()

End Sub

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

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 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 to toggle the breakpoint off and choose Run Run to run the routine normally.

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 your drawing, 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 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:

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.

Chapter 37 Programming with Visual Basic for Applications 1123

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’ve seen the power that 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 object-oriented 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 of the properties of a given object that is already in AutoCAD, and you can add to it. For example, you can inherit from a line so that your custom object has everything 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. AutoCAD 2006 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).

Summary

In 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 for you to create the professional drawings that 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 ellen@ellenfinkelstein.com. Best wishes and enjoy!

 

 

 

Appendixes

The three appendixes in Part VIII provide important additional information. Although these appendixes are especially useful

when you first start to use AutoCAD 2006 or AutoCAD LT 2006, 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 lists numerous additional resources, and 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 to use the files there.

P A R T

VIII

In This Part

Appendix A

Installing and

Configuring AutoCAD

and AutoCAD LT

Appendix B

AutoCAD and

AutoCAD LT Resources

Appendix C

What’s on the CD-ROM

Соседние файлы в папке Книги_AutoCad_2