Anda di halaman 1dari 24

Instructors Guide

Using Visual Basic with AutoCAD, 2 nd Edition


Solutions to Questions
Chapter 1
1

Benefits of customizing AutoCAD:


Time savings; cost savings; productivity gains;
improvement in CAD skills; improvement in overall technical skills. Other valid benefits
can be accepted at the discretion of the instructor.

Advantages of Visual Basic as a customization tool: graphical user interface (GUI) results
in less coding; includes language-independent components; produces familiar Windows
interface and appearance; enables faster application development; easier to debug. Other
valid advantages can be accepted at the discretion of the instructor.

Differences between VBA and Visual Basic: VBA is an in-process controller and works
within the AutoCAD environment. It is provided at no additional cost to AutoCAD users.
VB must be purchased separately, but allows creation of stand-alone EXE files and contains
more options for ActiveX controls.

AutoCAD R14 implemented VBA, with a preview edition implemented in R14.0 and a full
version in R14.01.

AutoCAD VBA programs generally run faster than comparable programs developed in
Visual Basic because VBA is an in-process controller, operating within the AutoCAD
environment and sharing AutoCADs memory and process space.

False. In AutoCAD 2000, you can access any command through the SendCommand method,
but this was unavailable in R14.

False

Chapter 2
1

Five main components that initially appear in the VBA: Title bar; Menu bar; Toolbar;
Project Explorer; and Properties window.

The Properties window lists the properties for selected objects, along with their current
settings.

Insert a UserForm in AutoCAD VBA by clicking on the Insert menu and selecting
UserForm.

To display the Code window at any time, click on the View menu and select Code, or
simply press [F7].

A macro is a program that contains a list of instructions you want performed by a particular
application, such as AutoCAD. When you develop a program in VBA, you are by definition
creating a macro.

You can run a program using any of the following methods:

Select Run Sub/UserForm from the Run menu in VBA.

Press [F5].

Click on the Run icon in the Toolbar.

Use the VBARUN command in AutoCAD.

Run the program as a Macro from the Tools menu in AutoCAD (covered in Chapter 6).

The primary way to load a project is to click on the Tools menu and select Macro and Load
Project. You can also load a VBA project automatically in two different ways:

You can name your project ACAD.DVB. When VBA is loaded it will look in the AutoCAD directory
for a project with this name and load it automatically as the default project.

Any project other than the default, ACAD.DVB, can be explicitly loaded at startup through the
VBALOAD command.

True

Chapter 3
1

The Object Model.

A property is an attribute, or characteristic, of an object that defines the object's size,


color, screen location, or some other aspect of its behavior, such as whether it is enabled or
visible.

A method is a function that performs an action on an object.

Variables can be declared as one of the following data types: Boolean, Byte, Integer, Long,
Currency, Single, Double, Date, String (for variable-length strings), String*length (for
fixed-length strings), Object, or Variant.

Variant data types allow you to contain virtually any kind of data in a variable. If you do
not specify a data type, the Variant data type is assigned by default. Visual Basic performs
the necessary conversions to work with a Variant variable.

Three types of statements: Declaration; assignment; Executable

Examples of events: clicking on a command button; changing text in a text box; opening an
AutoCAD drawing; Saving an AutoCAD drawing; executing an AutoCAD command.

ThisDrawing is the object. ActiveLayer is the property, and layerObj is a variable that
contains the value of the property.

Me is the object, and Hide is the method.

10 ThisDrawing is the object, while Utility is the property, and GetPoint is the method.
11 ListBox1 is the object, while Text is the property.
12 Code follows:

Private Sub CommandButton1_Click()


MsgBox ( Well done! )
End Sub
13 Code follows:

Private Sub CommandButton1_Click()


n = InputBox("number:")
nsqrd = n * n
MsgBox ("n = " & n & " n^2 = " & nsqrd)
End Sub
14 Actually two errors. Hide.Me should be Me.Hide, and parentheses needed around prompt.
Correct code follows:

Private Sub CommandButton1_Click()


Dim anyPoint
Me.Hide
anyPoint = ThisDrawing.Utility.GetPoint(prompt:="Pick a point:")
End Sub
15 Quotation marks and parentheses should be placed around the words Hi There as follows:

MsgBox ( Hi There )
Note: This example will still run without the parentheses, but parentheses are recommended to allow
flexibility in building more complex message boxes.

Chapter 4
1

The two primary means of making decisions within a program are the If...Then block and
the Select Case structure.

An If...Then block executes one block of statements if the If statement is true, and branches
out of the loop if the If statement is false. An If...Then...Else block executes one block if
the condition is true, and executes a second block of statements if the condition is false.

A Select Case structure can evaluate multiple expressions within a single block. It is a
more efficient alternative to nested blocks.

A DoWhile loop repeats a block of statements while a condition is true. A Do Until loop
repeats a block of statements until a condition is true

For...Next loops are preferable to Do loops when you know exactly how many times you
need to execute the statements in the loop.

Arrays provide a way to keep track of changing values associated with a particular variable.
They can also reduce the number of variables in your program and reduce the number of
statements in a program. In general, arrays allow you to write programs that are more
flexible and less dependent on specific data.

The Redim statement allocates the proper amount of storage space for the array.

The three types of file access are sequential, random, and binary.

Random access stores data in records much like folders in a file cabinet. Random access is
used to read and write data to a file without closing it. It is also well suited to accessing
data saved in array format. To access data with sequential access, you have to step through
a file from the beginning, no matter where it is located.

10 The vast majority of the Win32 API functions can be found in three files: KERNEL32.DLL,
USER32.DLL, and GDI32.DLL
11 False
12 False
13 True
14 Last line should be Next x, not Next y.
15 Code follows:

Private
Dim
Dim
For

Sub CommandButton1_Click()
x As Double
xsqr As Double
x = 1 To 5
xsqr = x ^ 2
MsgBox ("x= " & x & " x^2 = " & xsqr)
Next x
End Sub

16 Code follows:

Private Sub CommandButton1_Click()


Dim x As Double
Dim xsqr As Double
x = 1
Do While x <= 5
xsqr = x ^ 2
MsgBox ("x= " & x & "
x^2 = " & xsqr)

x = x + 1
Loop
End Sub
17 Code follows:

Private Sub CommandButton1_Click()


Dim x As Double
Dim xsqr As Double
Open "SQDOFILE" For Output As #1 ' Open file for output.
x = 1
Do While x <= 5
xsqr = x ^ 2
MsgBox ("x= " & x & "
x^2 = " & xsqr)
Print #1, x, xsqr
x = x + 1
Loop
Close #1
' Close file.
End Sub
18 Code follows:

Private Sub CommandButton1_Click()


Dim x As Double
Dim xsqr As Double
Open "SQDORAND" For Random As 1 Len = 16 ' Open file for output.
x = 1
Do While x <= 5
xsqr = x ^ 2
MsgBox ("x= " & x & "
x^2 = " & xsqr)
Put 1, x, xsqr
x = x + 1
Loop
Close 1
' Close file.
End Sub

Chapter 5
1

The ModelSpace and PaperSpace collections contain all of the graphical objects found in
the drawing's model and paper space.

Code follows:

Private Sub CommandButton1_Click()


Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
Dim myObj As AcadLine
startPoint(0) = 0#
startPoint(1) = 0#
startPoint(2) = 0#
endPoint(0) = 4#
endPoint(1) = 4#
endPoint(2) = 0#
Set myObj = ThisDrawing.ModelSpace.AddLine(startPoint, endPoint)
startPoint(0) = 4#
startPoint(1) = 4#
startPoint(2) = 0#
endPoint(0) = 10#
endPoint(1) = 3#
endPoint(2) = 0#
Set myObj = ThisDrawing.ModelSpace.AddLine(startPoint, endPoint)
ThisDrawing.Regen (acAllViewports)
End Sub
Note: Instead of redefining the second startPoint as the first endPoint, this program could also be
rewritten more efficiently, such as by using looping techniques covered in Chapter 4. The efficiency
of using looping should be emphasized, particularly when more than two line segments are involved.
3

Several solutions exist, depending on whether the user wants a fixed number of vertices in
the polyline, or a variable number. Code for the latter case follows:

Option Explicit
Sub AddPolylineUser_Example()
Dim strPrompt As String
Dim varPoint As Variant
Dim objMyPline As AcadPolyline
Dim dblStrPnt(0 To 2) As Double
Dim varVertList(0 To 5) As Double
Dim intNoPnts As Integer
strPrompt = "Pick the start point:"
On Error Resume Next
Do
varPoint = Empty
varPoint = ThisDrawing.Utility.GetPoint(Prompt:=strPrompt)
If IsEmpty(varPoint) Then Exit Do
If intNoPnts = 0 Then
varVertList(0) = varPoint(0)
varVertList(1) = varPoint(1)
varVertList(2) = varPoint(2)
intNoPnts = intNoPnts + 1
strPrompt = "Pick the next point."
ElseIf intNoPnts = 1 Then
' Define next vertex
varVertList(3) = varPoint(0)
varVertList(4) = varPoint(1)
varVertList(5) = varPoint(2)

' Create the entity in model space


Set objMyPline = ThisDrawing.ModelSpace.AddPolyline(varVertList)
ThisDrawing.Application.Update
intNoPnts = intNoPnts + 1
Else
dblStrPnt(0) = varPoint(0)
dblStrPnt(1) = varPoint(1)
dblStrPnt(2) = varPoint(2)
intNoPnts = intNoPnts + 1
' Append polyline w/ additional vertex
objMyPline.AppendVertex dblStrPnt
ThisDrawing.Application.Update
End If
Loop While Val(varPoint(0))
End Sub
4
5

True

Code contains two errors: 1) The startPoint and endPoint variables are dimensioned as
strings, and 2) the variables are spelled incorrectly in the Set myObj line. Corrected code
follows:

Private Sub RunLine_Click()


Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
Dim myObj as AcadLine
startPoint(0) = 1#
startPoint(1) = 3#
startPoint(2) = 0#
endPoint(0) = 2#
endPoint(1) = 3#
endPoint(2) = 0#
Set myObj = ThisDrawing.ModelSpace.AddLine(startPoint, endPoint)
End Sub
7
StartPoint and EndPoint.
8
To append or prepend text to the primary dimension value, use a closed set of brackets (< >) to represent
the value.
9
Code follows:
Option Explicit

Sub DimensionRadial_Example()
Dim dimObj As AcadDimRadial
Dim centerPoint(0 To 2) As Double
Dim chordPoint(0 To 2) As Double
Dim dblLen As Double
' Define the dimension
centerPoint(0) = 4#: centerPoint(1) = 2#: centerPoint(2) = 0#
chordPoint(0) = 5#: chordPoint(1) = 5#: chordPoint(2) = 0#
dblLen = 3
' Create an aligned dimension object in model space
Set dimObj = ThisDrawing.ModelSpace.AddDimRadial(centerPoint,
chordPoint, dblLen)
ZoomAll
End Sub

10
Code follows:
Sub AddTextCenter_Example()
Dim dblHeight As Double
Dim strPhrase As String
Dim objMyText As AcadText
Dim dblStartPoint(0 To 2) As Double
dblStartPoint(0) = 2: dblStartPoint(1) = 2: dblStartPoint(2) = 0
dblHeight = 1.5
strPhrase = "Testing 1, 2, 3..."
Set objMyText = ThisDrawing.ModelSpace.AddText(strPhrase,
dblStartPoint, dblHeight)
objMyText.Update
ZoomAll
MsgBox "Click OK to change text properties."
objMyText.Alignment = acAlignmentCenter
objMyText.height = 1
objMyText.Color = acRed
objMyText.Update
ZoomAll
End Sub

Chapter 6
1

Any of the following collection objects are acceptable answers: Documents, Dictionaries,
DimStyles, Groups, Hyperlinks, Layers, Layouts, Linetypes, PlotConfigurations,
RegisteredApps, SelectionSets, TextStyles, UCSs, Views, Viewports, MenuBar,
PopupMenu, MenuGruops, Toolbar, Toolbars.

True

True

False

There are two errors in the statement myObj.Length = 4. First of all, the Length property is
read-only and cannot be re-assigned in this manner. Also, myObj has not been declared as
an object. The correct object is objMyLine.

Code follows:

Option Explicit
Sub NewLayer_Example()
Dim objNewLayer As AcadLayer
Dim objMyLine As AcadLine
Dim dblStart(0 To 2) As Double
Dim dblEnd(0 To 2) As Double
dblStart(0) = 0
dblStart(1) = 0
dblStart(2) = 0
dblEnd(0) = 3
dblEnd(1) = 2
dblEnd(2) = 0
Set objNewLayer = ThisDrawing.Layers.Add("BestLayer")
Set objMyLine = ThisDrawing.ModelSpace.AddLine(dblStart, dblEnd)
objMyLine.Layer = "BestLayer"
objMyLine.Update
'objNewLayer.LayerOn = Not (objNewLayer.LayerOn)
End Sub
7

Code follows:

Option Explicit
Sub SelectSetNew_Example()
Dim objSset As AcadSelectionSet
Dim intMode As Integer
Dim dblPoint1, dblPoint2
Dim objEnt As Object
Dim intCount As Integer
' Create the selection set
Set objSset = ThisDrawing.SelectionSets.Add("SSTest")
' Add all entities that lie within a crossing area
' selected by the user
intMode = acSelectionSetCrossing
dblPoint1 = ThisDrawing.Utility.GetPoint(Prompt:="Select first corner
point:")
dblPoint2 = ThisDrawing.Utility.GetCorner(dblPoint1, "Select second
corner point:")
objSset.Select intMode, dblPoint1, dblPoint2
intCount = 0
' Step through selection set and count entities.

For Each objEnt In objSset


intCount = intCount + 1
Next objEnt
MsgBox (intCount & " objects were added to the selection set.")
ThisDrawing.SelectionSets.Item("SSTest").Delete
ThisDrawing.Application.Update
Close
End Sub
8

Code follows:

Option Explicit
Sub MoveLayer_Example()
Dim objNewLayer As AcadLayer
Dim objMyLine As AcadLine
Dim objEntity As AcadEntity
Dim intCount As Integer
Set objNewLayer = ThisDrawing.Layers.Add("BackupLayer")
intCount = 0
For Each objEntity In ThisDrawing.ModelSpace
If objEntity.Layer = ThisDrawing.ActiveLayer.Name Then
objEntity.Layer = "BackupLayer"
intCount = intCount + 1
End If
Next
MsgBox (intCount & " objects have been moved from layer " &
ThisDrawing.ActiveLayer.Name & " to BackupLayer.")
ThisDrawing.ActiveLayer = objNewLayer
End Sub

10

Chapter 7
1

The EntityName property

The coordinate values are stored in an array of points (double-precision values). For
LightweightPolyline objects, the variant is an array of 2D points in the entitys object
coordinate system (OCS). For Polyline objects, the variant is an array of 3D points in the
OCS, with the Z coordinate ignored. For 3DPolyline objects and all other objects, the
variant is an array of 3D points in the world coordinate system (WCS).

The Documents collection

Code follows:

Option Explicit
Sub ArcLength()
Dim objArc As AcadArc
Dim ArcLength As Double
Dim dblRad As Double
Dim dblAng As Double
Dim varPoint As Variant
ThisDrawing.Utility.GetEntity objArc, varPoint, "Select an arc: "
dblRad = objArc.Radius
dblAng = objArc.TotalAngle
' Works for ACAD2000 only; R14 requires StartAngle & EndAngle
ArcLength = dblAng * dblRad
MsgBox "Arc length = " & ArcLength
End Sub
5

This example is easier than it may first appear. By declaring the object generically as
AcadEntity in AutoCAD 2000 (or as Object in R14), the Area property and the same code
can be applied to arcs, circles, and ellipses. Code follows:

Option Explicit
Sub ArcArea()
Dim objArc As AcadEntity
Dim dblArea As Double
Dim varPoint As Variant
ThisDrawing.Utility.GetEntity objArc, varPoint, "Select an arc, circle,
or ellipse: "
dblArea = objArc.Area
MsgBox "Area = " & dblArea
End Sub
6 False
7

True

The Dictionary object in VBA is a mechanism for storing and retrieving objects with
associated string keywords. A dictionary can contain any type of object, including other
dictionaries. The Dictionary object is somewhat similar to a collection, as it is used to
contain information about other objects. Each Dictionary object is part of the Dictionaries
collection object.

Examples of extended entity data might include: tracking entities created with certain
routines; storing certain data about entities when they are created.

10 There are two errors with this code fragment: 1) The object called objLine is dimensioned
as AcadLine, but the the statement that creates the object uses the AddPolyline method,
which should be the AddLine method. 2) The statement that determines the length of the
line incorrectly uses the ArcLength property, which should be the Length property. The
corrected code follows.

11

Sub Ex()
Dim objLine As AcadLine
Dim varStartPt As Variant, varEndPt As Variant
varStartPt = ThisDrawing.Utility.GetPoint(, "Pick start point.")
varEndPt = ThisDrawing.Utility.GetPoint(, "Pick end point.")
Set objLine = ThisDrawing.ModelSpace.AddLine(varStartPt, varEndPt)
objLine.Update
MsgBox "Length = " & objLine.Length
End Sub

12

Chapter 8
1

False. The View object is a member of the Views collection.

True

True

In AutoCAD, a layout is a paper space environment that simulates a sheet of paper and
provides a predictable plotting setup. In VBA, the content of a standard AutoCAD layout is
broken out into two separate objects: the Layout object containing the visual properties and
plot settings, and the Block object containing the geometry.

The Plot object controls how a drawing is sent to a plotter, printer, or file. It also includes
a PlotConfiguration object for controlling plotter settings.

Numerous solutions exist, but the following code uses input boxes for portability. For a
more user-friendly version, students might consider developing a UserForm for this
problem.

Option Explicit
Dim objView As AcadView
Dim objViewport As AcadViewport
Dim dblHeight As Long
Dim dblWidth As Long
Sub Example_SetView()
' This example creates a new view and allows the width and height to be
changed.
' It then changes the active viewport to
' the newly created view.
' Create a new view
Set objView = ThisDrawing.Views.Add("TESTVIEW")
' Set the view characteristics
dblHeight = InputBox("Current height: " & objView.Height & " Current
width: " & objView.Width & vbCrLf & "New height:", , objView.Height)
objView.Height = dblHeight
dblWidth = InputBox("Current height: " & objView.Height & " Current
width: " & objView.Width & vbCrLf & "New width:", , objView.Width)
objView.Width = dblWidth
' Get the current active viewport
Set objViewport = ThisDrawing.ActiveViewport
MsgBox "Change to the saved view.", , "SetView Example"
' Set the view in the viewport
objViewport.SetView objView
ThisDrawing.ActiveViewport = objViewport
ThisDrawing.Regen True
End Sub
7

Code follows:

Option Explicit
Dim varLowerLeft As Variant
Dim varUpperRight As Variant
Private Sub cmdZoomCtr_Click()
varLowerLeft = ThisDrawing.Utility.GetPoint(Prompt:="Pick lower left
corner:")

13

varUpperRight = ThisDrawing.Utility.GetPoint(Prompt:="Pick upper right


corner:")
ZoomWindow varLowerLeft, varUpperRight
End Sub
8

Code follows:

Private Sub cmdPlotToFileEx()


ThisDrawing.ActiveLayout.PlotType = acDisplay
ThisDrawing.Plot.PlotToFile ("MYPLOT.PLT")
End Sub
9

Code follows:

Private Sub cmdPlotToFileEx()


ThisDrawing.ActiveLayout.StandardScale = ac1_4in_1ft
ThisDrawing.Plot.PlotToDevice
End Sub
10 The variable plotFileName should be declared as a string, as follows:

Dim plotFileName As String

14

Chapter 9
1

A well designed application should contain aesthetically pleasing interfaces with neatly
aligned controls, concise message boxes and output displays, logically arranged dialog
boxes. Language should be clear, grammatically correct, and succinct. Dialog boxes should
be labeled with a brief phrase that describes the purpose of the dialog box. Applications
should be organized logically, perhaps aided by tools such as flowcharts. Error trapping
techniques, covered in more detail in Chapter 12, should be used to catch primary errors.

Pseudocode is a hybrid between common English statements and actual programming code
that can help identify major steps in a program. Some programmers use pseudocode to
develop an outline prior to typing code.

Multiple UserForms can be controlled by inserting a module. By including a module in your


project, you can also run the program as a macro from the AutoCAD Tools menu or invoke
the program using the VBARUN command.

A drawing that contains Xrefs always reflects the most current editing of each externally
referenced file, since the reference is updated when the original drawing changes.. Though
an Xref is displayed in the current drawing as a single object, it does not significantly
increase the file size of the current drawing.

False

True

False

True

Code follows:

Option Explicit
Sub CommandButton1_Click()
Dim ssetObj As AcadSelectionSet
Dim mode As Integer
Dim point1(0 To 2) As Double, point2(0 To 2) As Double
Dim ent As Object
Dim entLayer As String
' Create the selection set
Set ssetObj = ThisDrawing.SelectionSets.Add("TEST_SSET")
' Add all entities to the selection set.
mode = acSelectionSetAll
ssetObj.Select mode
point1(0) = 0: point1(1) = 0: point1(2) = 0
point2(0) = 2: point2(1) = 0: point2(2) = 0
Me.hide
' Step through selection set and move each entity
For Each ent In ssetObj
entLayer = ent.Layer
If entLayer = "0" Then
ent.Move point1, point2
MsgBox ("Moving the following entity: " & ent.EntityName)
End If
Next ent
ThisDrawing.Application.Update
ssetObj.Delete
Close
End Sub

15

10 Code follows:

Option Explicit
Sub CommandButton1_Click()
Dim ssetObj As AcadSelectionSet
Dim mode As Integer
Dim point1 As Variant, point2 As Variant
Dim ent As Object
Dim entLayer As String
' Create the selection set
Set ssetObj = ThisDrawing.SelectionSets.Add("TEST_SSET")
' Add all entities to the selection set.
mode = acSelectionSetAll
ssetObj.Select mode
Me.hide
' Step through selection set and move each entity
For Each ent In ssetObj
If ent.EntityType = acLine Then
point1 = ent.startPoint
point2 = ent.endPoint
MsgBox ("Start point: " & point1(0) & ", " & point1(1) & "
point: " & point2(0) & ", " & point2(1))
End If
Next ent
ThisDrawing.Application.Update
ssetObj.Delete
ssetObj.Delete
Close
End Sub

End

11 The points need to be defined as follows:

point1(0) = 0: point1(1) = 0: point1(2) = 0


point2(0) = 3: point2(1) = 4: point2(2) = 0
12 The variable myLayer should be dimensioned as a String, and the statement that assigns a
value to myColor needs a period. Also, while the code fragment is not a complete program,
a Next statement is required to match up with the For Each statement. Corrected code
follows:

Dim
Dim
Dim
For

myEntity as String
myLayer as String
myColor as Integer
Each ent In ObjSet
myEntity = ent.EntityName
myLayer = ent.Layer
myColor = ent.Color
Next

16

Chapter 10
1

a) SendCommand, SendKeys, DDE


b) SendKeys, DDE
c) DDE

Dynamic Data Exchange (DDE) is the mechanism that allows two applications to talk to
each other by continuously exchanging data. It can be considered as a means of automating
the Windows clipboard, where graphics and text data can be placed for exchange between
various Windows applications. Instead of simply passing information from one application
to another, object linking and embedding (OLE) allows information to be presented in the
same way as it would appear in the original application.

In a DDE conversation, the server is the application being contacted for information.

The client initiates a conversation.

Only one DDE topic--System--is available in AutoCAD.

Strings can be sent via AutoLISP to execute commands using variables instead of constants
for the command parameters.

The LinkExecute method is used to send keystrokes to AutoCAD versions R14 and older. In
AutoCAD 2000, the SendCommand can be used.

Embedding stores a copy of the source information in another document. The embedded
information is no longer associated with the original application. Linking creates a
reference between the source information and another document. If you change an
AutoCAD drawing that is linked to another document, the image in the document will be
updated automatically.

An OLE object is inserted in a VB form by using the OLE control in the Toolbox.

10 The ThisDrawing object can only be used in VBA. In VB, the third line should appear as
follows:

Dim myDoc As AcadDocument


11 Code follows:

Sub LinkApp(Link As Control, Appname As String, Topic As String)


Link.LinkMode = 0 ' 0 = None
Link.LinkTopic = Appname + "|" + Topic
Link.LinkMode = 2 ' 2= cold or manual
End Sub
Private Sub CancelButton_Click()
End
End Sub
Sub OKButton_Click()
lblImport.LinkExecute "zoom w 0,0 100,100 "
End
End Sub
Sub Form_Load()
LinkApp lblImport, "AutoCAD.R14.DDE", "System"
End Sub

17

Chapter 11
1

A wide variety of examples can be given on using AutoCAD with spreadsheet applications.
A few might include: extracting quantities from AutoCAD drawings and placing the
quantities in spreadsheets as demonstrated in this chapter; listing drawing information
such as layers, colors, and other entity information; developing tables and charts for
importing into AutoCAD drawings; and creating AutoCAD entities based on data contained
in spreadsheets.

The EntityType property is defined by the type of entity, such as line, arc, or block. Each
entity in AutoCAD has a unique constant value. For example, if the object is a line, the
EntityType value will be 19 (acLine).The EntityName property specifies the name of an
entity, and is equivalent to the class name of the object. It is particularly useful for
querying blocks and custom objects that might not have an EntityType property assigned.
The ObjectName property in AutoCAD 2000 is generally equivalent to the AutoCAD class
name of the object.

Excel VBA includes a Workbook object that is analogous to the ActiveDocument object in
AutoCAD.

Yes.

The AppActivate statement activates another application window from within a host
application.

The Add method is used with Workbooks, and not Sheets. The corrected line follows:

Excel.Workbooks.Add

Code follows:

Public acadApp As Object


Public acadDoc As Object
Public mSpace As Object
Private Sub UserForm_Initialize()
On Error Resume Next
Set acadApp = GetObject(, "AutoCAD.Application")
If Err Then
Err.Clear
MsgBox ("AutoCAD is not running...")
End
Else
Set acadDoc = acadApp.ActiveDocument
Set mSpace = acadDoc.ModelSpace
End If
End Sub
Private Sub CommandButton1_Click()
Dim TextObj As AcadText
Dim StartPt(0 To 2) As Double
Dim Answer As Double
StartPt(0) = 0
StartPt(1) = 0
StartPt(2) = 0
AppActivate acadApp.Caption
Answer = Cells(3, 2).Value + Cells(4, 2).Value
Set TextObj = mSpace.AddText(Answer, StartPt, 2)
End Sub

18

Private Sub CommandButton2_Click()


Unload Me
End Sub

19

Chapter 12
1

A wide variety of examples can be given on using AutoCAD with word-processing


applications. A few might include: extracting quantities from AutoCAD drawings and
placing them in reports or other documents; listing drawing information such as layers,
colors, and other entity information; creating notes and other textual information for
importing into AutoCAD drawings; and creating AutoCAD entities based on data contained
in word-processing documents.

To extract text from a drawing, you work with the TextString property of the Text object.

Word VBA includes a Document object that is analogous to the ActiveDocument object in
AutoCAD.

Yes.

The AppActivate statement activates another application window from within a host
application.

The Bold statement requires a value of True. The corrected code follows:

.Selection.Range.Bold = True ' Boldface the area value.


7

Code follows:

Option Explicit
Public acadApp As AcadApplication
Public acadDoc As AcadDocument
Public mSpace As AcadModelSpace
Private Sub UserForm_initialize()
On Error Resume Next
Set acadApp = GetObject(, "AutoCAD.Application")
If Err Then
Err.Clear
MsgBox ("AutoCAD is not running...")
End
Else
Set acadDoc = acadApp.ActiveDocument
Set mSpace = acadDoc.ModelSpace
End If
End Sub
Private Sub CommandButton1_Click()
Dim StartPt(0 To 2) As Double
Dim TextObj As AcadText
Dim WordSel As String
AppActivate acadApp.Caption
StartPt(0) = 0#
StartPt(1) = 0#
StartPt(2) = 0#
Selection.MoveRight Unit:=wdWord, Count:=2, Extend:=wdExtend
WordSel = Selection.Text
Set TextObj = mSpace.AddText(WordSel, StartPt, 2)
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub

Chapter 13
1

A wide variety of examples can be given on using AutoCAD with database applications. A

20

few might include: extracting quantities from AutoCAD drawings and placing them in
databases as demonstrated in this chapter; listing drawing information such as layers,
colors, and other entity information; creating tables for importing into AutoCAD drawings;
and creating AutoCAD entities based on data contained in database documents.
2

A record contains all the information about one particular item.

This is not as clear as with Word or Excel, but the Database object is roughly equivalent to
the AutoCAD ActiveDocument object. The OpenDatabase method opens a specified
database in a Workspace object and returns a reference to the Database object that
represents it, as follows:

Set database = workspace.OpenDatabase (dbname, options, read-only, connect)


4

DAO supports two different database environments, or workspaces:Microsoft Jet, and


ODBCDirect.

Set db = OpenDatabase("C:\My Documents\BigList.mdb")

False

True

A period is needed in the second statement as follows:

DoCmd.GoToRecord , "", acFirst


9

To find all employees hired after January 1, 1998, the easiest way is to use a query. Click
on the Query tab in Access, and select New. Highlight Simple Query Wizard and click on
OK. Select Hire_Date as the field, and click on Next. Name the query and provide
>1/1/98 as the criteria. You can then go to the Macros tab and select OpenQuery as the
Action. The macro can be converted to a module as demonstrated in Chapter 10, resulting
in the following line of code:

DoCmd.OpenQuery "Hire Date Query", acNormal, acEdit


As an alternate, an SQL query can be written to find records with Hire_Date > 01/01/98,
but this is considerably more cumbersome, and beyond the scope of this book.
10 Some possible answers (there are others): 1) ADO offers better integration with a variety of
databasesboth Microsoft and non-Microsoftas well as a common interface for both local
and remote data access. This means you can use the same interface for Internet and intranet
data as you use for your local database. 2) An ADO interface can serve as an applicationlevel interface to any OLE data provider, including relational and nonrelational databases,
email and file systems, text and graphics, and custom business objects, as well as existing
ODBC data sources. 3) You connect to databases differently with DAO (OpenDatabase
method) than with ADO (Open method).

21

Chapter 14
1

To start an EXE file from AutoLISP, you can: use the AutoCAD SHELL command to
shell out of AutoCAD into another application; use the AutoLISP STARTAPP command,
or create external AutoCAD commands to invoke other programs while AutoCAD is
running.

Visual LISP provides the following features not included within AutoLISP:
a) event-driven programming using reactors;
b) access to the AutoCAD object model via ActiveX Automation;
c) a complete integrated development environment (IDE) similar to the VBA IDE;
d) debugging capabilities.

A reactor is an object attached to an AutoCAD drawing object so that AutoCAD can notify
your application when certain events occur.

When a document contains one or more objects created in an application other than the one
displaying it, the document is referred to as a compound document. The documents native
data and the linked or embedded objects can have entirely different file formats.

Hypertext markup language (HTML) is used to publish documents on the World Wide Web.
It is a system of marking up documents that can then be viewed with special software called
a Web browser. Examples include publishing drawings on the internet, providing home
pages for sharing text and graphics with clients and colleagues, and embedding Visual
Script applications to be run by anyone accessing a Web page with a VB-compatible Web
browser such as Internet Explorer.

Drawing Web Format (DWF) is a special format that can be used to publish drawings on
the World Wide Web. Drawing files saved in DWF format can be viewed by anyone with the
WHIP! plug-in. Examples for using DWF include: allowing clients, colleagues,
subcontractors, and others to view drawings without editing capabilities.

False

False. VB Script is a subset of VBA that is incorporated into Microsofts Internet Explorer.

The VB Script portion of the code is improperly identified as a remark statement, and the
variable c in the MsgBox statement needs quotations marks, as follows:

<SCRIPT LANGUAGE="VBScript">
Sub Counter
For c = 1 to 10
Msgbox c
Next c
End Sub
Call Hello
10 The following AutoCAD VBA program opens Excel, places the name of the active
AutoCAD drawing in cell A1, and places the same information at the top of a Word
document called DwgName.doc. (This document must be created prior to running the
program.)

Private
Dim
Dim
Dim
Dim
Dim

Sub CommandButton1_Click()
Excel As Object
excelSheet As Object
WdApp As Object
WdDoc As Object
dwgname As String

22

On Error Resume Next


' Load Excel
Set Excel = GetObject(, "Excel.Application")
If Err <> 0 Then
Err.Clear
Set Excel = CreateObject("Excel.Application")
If Err <> 0 Then
MsgBox "Could not load Excel.", vbExclamation
End
End If
End If
On Error GoTo 0
Excel.Visible = True
Excel.Workbooks.Add
Excel.Sheets("Sheet1").Select
Set excelSheet = Excel.ActiveWorkbook.Sheets("Sheet1")
dwgname = ThisDrawing.Name
excelSheet.Cells(1, 1).Value = dwgname
' Start / Load Word
On Error Resume Next
Set WdApp = GetObject(, "Word.Application")
If Err <> 0 Then
Err.Clear
Set WdApp = CreateObject("Word.Application")
If Err <> 0 Then
MsgBox "Could not load Word.", vbExclamation
End
End If
End If
On Error GoTo 0
WdApp.Visible = True
Set WdDoc = WdApp.Documents.Open("c:\My Documents\DwgName.doc")
With WdApp
.Selection.TypeText Text:=dwgname
End With
Unload Me
End Sub

23

Chapter 15
1

Errors in VBA generally fall into one of four categories: syntax, compile, run-time, and
logic. Syntax errors occur when a keyword is misspelled or missing, or incorrect
punctuation is typed. Compile errors are identified during the compiling process and
prevent the program from running. Run-time errors halt execution of a program after it has
started running. They generally occur when VBA encounters a statement it cannot process,
such as a division by zero. Logic errors indicate a problem with program logic such as an
endless loop or an incorrect mathematical formula.

You can sometimes step through a procedure and use other debugging techniques discussed
in this chapter to pin down logic errors.

You can enter break mode in several ways:


Start the procedure in break mode by pressing [F8] (Step Into) at the beginning of the
procedure.
Set a breakpoint on a specific line of code.
Place a Stop statement in your code to temporarily halt execution.
Press Ctrl + Break while a procedure is running.
Click on the Debug button from a run-time error dialog box.

Click on the View menu and select Toolbars and Debug.

Press [F8] or select Step Into from the Debug menu.

True

False. An On Error statement is used at the beginning of a procedure.

24

Anda mungkin juga menyukai