Instructor’s Guide - Cengage Learning · Instructor’s Guide Using Visual Basic with AutoCAD, 2...

24
1 Instructor’s 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. 2 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. 3 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. 4 AutoCAD R14 implemented VBA, with a preview edition implemented in R14.0 and a full version in R14.01. 5 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 AutoCAD’s memory and process space. 6 False. In AutoCAD 2000, you can access any command through the SendCommand method, but this was unavailable in R14. 7 False

Transcript of Instructor’s Guide - Cengage Learning · Instructor’s Guide Using Visual Basic with AutoCAD, 2...

1

Instructor’s GuideUsing Visual Basic with AutoCAD, 2nd Edition

Solutions to QuestionsChapter 11 Benefits of customizing AutoCAD: Time savings; cost savings; productivity gains;

improvement in CAD skills; improvement in overall technical skills. Other valid benefitscan be accepted at the discretion of the instructor.

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

3 Differences between VBA and Visual Basic: VBA is an in-process controller and workswithin 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 containsmore options for ActiveX controls.

4 AutoCAD R14 implemented VBA, with a preview edition implemented in R14.0 and a fullversion in R14.01.

5 AutoCAD VBA programs generally run faster than comparable programs developed inVisual Basic because VBA is an in-process controller, operating within the AutoCADenvironment and sharing AutoCAD’s memory and process space.

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

7 False

2

Chapter 21 Five main components that initially appear in the VBA: Title bar; Menu bar; Toolbar;

Project Explorer; and Properties window.

2 The Properties window lists the properties for selected objects, along with their currentsettings.

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

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

5 A macro is a program that contains a list of instructions you want performed by a particularapplication, such as AutoCAD. When you develop a program in VBA, you are by definitioncreating a macro.

6 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).

7 The primary way to load a project is to click on the Tools menu and select Macro and LoadProject. 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 directoryfor 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 theVBALOAD command.

8 True

3

Chapter 31 The Object Model.

2 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 orvisible.

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

4 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 (forfixed-length strings), Object, or Variant.

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

6 Three types of statements: Declaration; assignment; Executable

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

8 ThisDrawing is the object. ActiveLayer is the property, and layerObj is a variable thatcontains the value of the property.

9 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 * nMsgBox ("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 anyPointMe.HideanyPoint = 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 allowflexibility in building more complex message boxes.

4

Chapter 41 The two primary means of making decisions within a program are the If...Then block and

the Select Case structure.

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

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

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

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

6 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 ofstatements in a program. In general, arrays allow you to write programs that are moreflexible and less dependent on specific data.

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

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

9 Random access stores data in records much like folders in a file cabinet. Random access isused to read and write data to a file without closing it. It is also well suited to accessingdata saved in array format. To access data with sequential access, you have to step througha 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 Sub CommandButton1_Click() Dim x As Double Dim xsqr As Double For x = 1 To 5 xsqr = x ^ 2 MsgBox ("x= " & x & " x^2 = " & xsqr) Next xEnd 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)

5

x = x + 1 LoopEnd 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

6

Chapter 51 The ModelSpace and PaperSpace collections contain all of the graphical objects found in

the drawing's model and paper space.

2 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 berewritten more efficiently, such as by using looping techniques covered in Chapter 4. The efficiencyof 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 inthe 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)

7

' 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 Sub4

5 True

6 Code contains two errors: 1) The startPoint and endPoint variables are dimensioned asstrings, and 2) the variables are spelled incorrectly in the Set myObj line. Corrected codefollows:

Private Sub RunLine_Click()Dim startPoint(0 To 2) As DoubleDim endPoint(0 To 2) As DoubleDim myObj as AcadLinestartPoint(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 Sub7 StartPoint and EndPoint.

8 To append or prepend text to the primary dimension value, use a closed set of brackets (< >) to representthe 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) ZoomAllEnd Sub

8

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 ZoomAllEnd Sub

9

Chapter 61 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.

2 True

3 True

4 False

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

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

10

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 CloseEnd 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 = objNewLayerEnd Sub

11

Chapter 71 The EntityName property

2 The coordinate values are stored in an array of points (double-precision values). ForLightweightPolyline objects, the variant is an array of 2D points in the entity’s objectcoordinate system (OCS). For Polyline objects, the variant is an array of 3D points in theOCS, with the Z coordinate ignored. For 3DPolyline objects and all other objects, thevariant is an array of 3D points in the world coordinate system (WCS).

3 The Documents collection

4 Code follows:

Option ExplicitSub 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 = " & ArcLengthEnd Sub

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

Option ExplicitSub 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 = " & dblAreaEnd Sub6 False

7 True

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

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

10 There are two errors with this code fragment: 1) The object called objLine is dimensionedas 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 theline incorrectly uses the ArcLength property, which should be the Length property. Thecorrected code follows.

12

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

13

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

2 True

3 True

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

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

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

Option ExplicitDim objView As AcadViewDim objViewport As AcadViewportDim dblHeight As LongDim 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 ExplicitDim varLowerLeft As VariantDim varUpperRight As VariantPrivate Sub cmdZoomCtr_Click() varLowerLeft = ThisDrawing.Utility.GetPoint(Prompt:="Pick lower left

corner:")

14

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

ZoomWindow varLowerLeft, varUpperRightEnd 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.PlotToDeviceEnd Sub

10 The variable plotFileName should be declared as a string, as follows:

Dim plotFileName As String

15

Chapter 91 A well designed application should contain aesthetically pleasing interfaces with neatly

aligned controls, concise message boxes and output displays, logically arranged dialogboxes. Language should be clear, grammatically correct, and succinct. Dialog boxes shouldbe labeled with a brief phrase that describes the purpose of the dialog box. Applicationsshould be organized logically, perhaps aided by tools such as flowcharts. Error trappingtechniques, covered in more detail in Chapter 12, should be used to catch primary errors.

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

3 Multiple UserForms can be controlled by inserting a module. By including a module in yourproject, you can also run the program as a macro from the AutoCAD Tools menu or invokethe program using the VBARUN command.

4 A drawing that contains Xrefs always reflects the most current editing of each externallyreferenced file, since the reference is updated when the original drawing changes.. Thoughan Xref is displayed in the current drawing as a single object, it does not significantlyincrease the file size of the current drawing.

5 False

6 True

7 False

8 True

9 Code follows:

Option ExplicitSub 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 CloseEnd Sub

16

10 Code follows:

Option ExplicitSub 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) & " End

point: " & point2(0) & ", " & point2(1)) End If Next ent ThisDrawing.Application.Update ssetObj.Delete ssetObj.Delete CloseEnd Sub

11 The points need to be defined as follows:

point1(0) = 0: point1(1) = 0: point1(2) = 0point2(0) = 3: point2(1) = 4: point2(2) = 0

12 The variable myLayer should be dimensioned as a String, and the statement that assigns avalue 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 codefollows:

Dim myEntity as StringDim myLayer as StringDim myColor as IntegerFor Each ent In ObjSet

myEntity = ent.EntityNamemyLayer = ent.LayermyColor = ent.Color

Next

17

Chapter 101 a) SendCommand, SendKeys, DDE

b) SendKeys, DDE

c) DDE

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

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

4 The client initiates a conversation.

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

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

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

8 Embedding stores a copy of the source information in another document. The embeddedinformation is no longer associated with the original application. Linking creates areference between the source information and another document. If you change anAutoCAD drawing that is linked to another document, the image in the document will beupdated automatically.

9 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 asfollows:

Dim myDoc As AcadDocument

11 Code follows:

Sub LinkApp(Link As Control, Appname As String, Topic As String)Link.LinkMode = 0 ' 0 = NoneLink.LinkTopic = Appname + "|" + TopicLink.LinkMode = 2 ' 2= cold or manualEnd Sub

Private Sub CancelButton_Click() EndEnd Sub

Sub OKButton_Click() lblImport.LinkExecute "zoom w 0,0 100,100 " EndEnd Sub

Sub Form_Load() LinkApp lblImport, "AutoCAD.R14.DDE", "System"End Sub

18

Chapter 111 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 thequantities in spreadsheets as demonstrated in this chapter; listing drawing informationsuch as layers, colors, and other entity information; developing tables and charts forimporting into AutoCAD drawings; and creating AutoCAD entities based on data containedin spreadsheets.

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

3 Excel VBA includes a Workbook object that is analogous to the ActiveDocument object inAutoCAD.

4 Yes.

5 The AppActivate statement activates another application window from within a hostapplication.

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

Excel.Workbooks.Add

7 Code follows:

Public acadApp As ObjectPublic acadDoc As ObjectPublic mSpace As ObjectPrivate 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 IfEnd 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

19

Private Sub CommandButton2_Click() Unload MeEnd Sub

20

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

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

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

3 Word VBA includes a Document object that is analogous to the ActiveDocument object inAutoCAD.

4 Yes.

5 The AppActivate statement activates another application window from within a hostapplication.

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

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

7 Code follows:

Option ExplicitPublic acadApp As AcadApplicationPublic acadDoc As AcadDocumentPublic mSpace As AcadModelSpacePrivate 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 IfEnd 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 SubPrivate Sub CommandButton2_Click() Unload MeEnd Sub

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

21

few might include: extracting quantities from AutoCAD drawings and placing them indatabases 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.

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

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

4 DAO supports two different database environments, or workspaces:·Microsoft Jet, andODBCDirect.

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

6 False

7 True

8 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. Clickon the Query tab in Access, and select New. Highlight Simple Query Wizard and click onOK. 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 theAction. The macro can be converted to a module as demonstrated in Chapter 10, resultingin 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 ofdatabases—both Microsoft and non-Microsoft—as well as a common interface for both localand remote data access. This means you can use the same interface for Internet and intranetdata as you use for your local database. 2) An ADO interface can serve as an application-level 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 existingODBC data sources. 3) You connect to databases differently with DAO (OpenDatabasemethod) than with ADO (Open method).

22

Chapter 141 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 isrunning.

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

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

4 When a document contains one or more objects created in an application other than the onedisplaying it, the document is referred to as a compound document. The document’s nativedata and the linked or embedded objects can have entirely different file formats.

5 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 calleda Web browser. Examples include publishing drawings on the internet, providing homepages for sharing text and graphics with clients and colleagues, and embedding VisualScript applications to be run by anyone accessing a Web page with a VB-compatible Webbrowser such as Internet Explorer.

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

7 False

8 False. VB Script is a subset of VBA that is incorporated into Microsoft’s Internet Explorer.

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

<SCRIPT LANGUAGE="VBScript">Sub Counter

For c = 1 to 10Msgbox “ c”

Next cEnd SubCall Hello

10 The following AutoCAD VBA program opens Excel, places the name of the activeAutoCAD drawing in cell A1, and places the same information at the top of a Worddocument called DwgName.doc. (This document must be created prior to running theprogram.)

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

23

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 MeEnd Sub

24

Chapter 151 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 incorrectpunctuation is typed. Compile errors are identified during the compiling process andprevent the program from running. Run-time errors halt execution of a program after it hasstarted 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 anendless loop or an incorrect mathematical formula.

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

3 You can enter break mode in several ways:

Start the procedure in break mode by pressing [F8] (Step Into) at the beginning of theprocedure.

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.

4 Click on the View menu and select Toolbars and Debug.

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

6 True

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