AutoCAD 2002 isn't just the world's #1 design and drafting tool: it's a powerful, programmable platform for automating complex design tasks, integrating design data with enterprise information systems, and solving a wide range of technical and business problems. The key to all that power is VBA scripting -- and the key to VBA scripting is AutoCAD 2002 VBA User Handbook. This book ties together AutoCAD's key tools and VBA's capabilities as never before, showing how AutoCAD and VBA work together in the real world -- and helping professionals create real-world applications more rapidly than they ever thought possible. Jeffrey E. Clark begins with a tour of AutoCAD's Interactive Development Environment, then helps AutoCAD professionals master the fundamentals of Automation, COM, and object-oriented programming. Go "under the hood" with the DXF format to understand the structure of AutoCAD's drawing database; master the AutoCAD object model, and discover how to automate 2D and 3D graphic objects, external references, entities, modeled solids, dimensions, and events. Learn how to use VBA to control PaperSpace, Viewports, and plotting; and how to extend AutoCAD to communicate with other applications and across the Internet. The book also includes a start-to-finish case study application that integrates an AutoCAD drawing with a Microsoft Access database.
© 2002 Prentice Hall PTR
Upper Saddle River, NJ 07458
This file contains a complete listing of all the code for the book. The list below is organized by chapter and example number, except for the first section, which describes a number of supplemental files that are used by the various procedures throughout the book. The files in A2K2_Vba.zip are cross-referenced by example number with the chapter listings that follow.
This software may be freely copied and used so long as this disclaimer, together with the above copyright notice, are included in all copies and any accompanying documentation. These example programs are made available "as-is" without any explicit or implied warranty. Neither the author nor publisher warrant that these programs are error free or will operate without interruption.
Readers are invited to contact the author by email at email@example.com. We regret that we cannot provide direct support for the programs listed herein, but will make an effort to respond intelligently to any questions you may have.
Jeffrey E. Clark
March 7, 2003
These files should be unzipped and installed in a directory named A2K2_VBA on your C:\ drive. Many of the code examples in 'VBA for AutoCAD 2002, Writing AutoCAD Macros' are set up to reference files in this folder or to create output files here. Setting up these files in the C:\A2K2_VBA folder will enablethese procedures to execute properly without modification.
The exanple numbers in this section designate the specific procedures in each chapter that refer to these files.
Example 1-2 IUnknown.vb (Microsoft VB.NET version, Chapter 01Ex02.bas, references
C:\A2K2_VBA\IUnknown.xls, creates C:\A2K2_VBA\IUnknown.dwg)
Example 1-2 IUnknown.xls
Example 3-5,6 AllocationPlan07.dxf
Example 8-8 Chair.dwg
Example 8-11,12 Xref_New.dwg
Example 8-12 XrefDemo.dwg
Example 9-26 FullerPoints.txt
Example 9-33 RasterFile.jpg
Example 15,17 AllocationPlan02.lyr
Example 15,17 BatchPlot.dir
Example 17 BatchPlot.dvb (functionally identical to Chapter15Ex07-19.dvb)
Example 17 FacilityProgram.mdb (Microsoft Access 2002 database format)
Example 17 FacilityProject.dvb (functionally identical to Chapter19.dvb except that it uses DAO 3.6)
Example 17 Relative.dvb (functionally identical Chapter14.dvb)
Example 17-2 (The addPopup and addToobar procedures in Chapter17.dvb load Relative.dvb, BatchPlot.dvb,and FacilityProject.dvb.)
Example 17-4 BatchPlot16.bmp, BatchPlot32.bmp,Facility16.bmp, Facility32.bmp,Relative16.bmp, Relative32.bmp (These are the icons for the toobars that the addToolbar procedure creates)
Example 17-7 creates testMNS.mns
Example 18-10 creates FacilityData.csv
Example 18-10 XData2csv.dvb
Example 18-7 creates FacilityData.txt
Example 18-10 AllocationPlan02.dwg
Example 19-4 FacilityProgram_old.mdb (Microsoft Access 2000 database format)
Example 20-2 AllocationPlan06-Model.dwf, AllocationPlan07-Model.dwf
Chapter 1 Taking Control of AutoCAD
Example 1-2. Visual Basic Automation (VB Version 6.0, references C:\A2K2_VBA\IUnknown.xls, creates C:\A2K2_VBA\IUnknown.dwg)
Chapter 3 DXF: Key to the Drawing Structure
Example 3-4. GetSubclass
Example 3-5,6. DXFsearch (references C:\A2K2_VBA\AllocationPlan07.dxf)
Example 3-8. C:CF ChngFont.lsp (AutoLisp)
Example 3-9 ChngFont (VBA)
Chapter 5 Documents and the User Interface
Example 5-1. DocumentNew
Example 5-2. DocumentOpen (references C:\Documents\anExistingDrawing.dwg)
Example 5-3. DocumentSave
DocumentSaveAs (references C:\Documents\Test12DXF.dxf)
Example 5-4. DocumentClose
Example 5-5. DocumentCloseAll (ApplicationQuit_Doesnt, ApplicationQuit)
Example 5-6. DocumentActive
Example 5-7. DocumentLoaded
Example 5-8a. ApplicationWindowState
Example 5-8b. DocumentWindowState
Example 5-9a. ApplicationWindowSize
Example 5-9b. DrawingWindowSize DrawingZoomAll, DrawingZoomWindow, DrawingZoomPickWindow, DrawingZoomScaled
Example 5-10. DrawingAddView
Example 5-11. ViewportAdd
Example 5-12. ViewportDelete
Example 5-13. ViewportIterate
Example 5-14. SetGridSpacing, SetSnapSpacing
Example 5-15. SetSnapAngle
Example 5-16. SetSnapBase
Example 5-17. DrawingAddHyperlinks
Chapter 6 Collections and Objects
Example 6-1. ToggleProjectFilePath (references C:\A2K2_VBA\)
Example 6-2. CheckVariables
Example 6-3. Handle2Object
Example 6-4. ActiveLayer
Example 6-5. Database
Example 6-6. SetLimits
Example 6-7. OSnapMode
Example 6-8. AcadDocument_SelectionChanged
Example 6-9. GetExtDictionary
Example 6-10. HasExtDictionary
Example 6-11. OwnerID
Example 6-12. AddLayer
Example 6-13. SaveLstate
Example 6-14. RestoreLstate
Example 6-15. Linetypes
Example 6-16. AddTextStyle
Example 6-17. AddUCS
Chapter 7 Utility Objects
Example 7-1. Populate
Example 7-2. SSmethods
Example 7-3. SelectOnScreen
Example 7-4. SelSetGet
Example 7-5. SelSetMove
Example 7-6. SelSetDelete
Example 7-7. SelSetFilter
Example 7-8. Groups
Example 7-9. InitializeUserInput
Example 7-10. GetAngle
Example 7-11. GetCorner
Example 7-12. GetDistamce
Example 7-13. GetEntity
Example 7-14. GetInteger
Example 7-15. GetKeyword
Example 7-16. GetOrientation
Example 7-17. GetReal
Example 7-18. GetString
Example 7-19. GetSubEntity
Example 7-20. AngleFromXAxis
Example 7-21. AngletoReal
Example 7-22. AngletoString
Example 7-23. CreateTypedArray
Example 7-24. DistancetoReal
Example 7-25. PolarPoint
Example 7-26. RealtoString
Example 7-27. TranslateCoordinates
Example 7-28. GetWebFile
Chapter 8 Blocks and External References
Example 8-1. AddInsert
Example 8-3. ListBlocks
Example 8-4. BlockTypes
Example 8-5. ListBlkRefs
Example 8-6. MakeAttribBlock
Example 8-8. AddMInsertBlock (references C:\A2K2_VBA\Chair.dwg)
Example 8-10. CopyObjects
Example 8-11. XRefDemo (references C:\A2K2_VBA\Xref_New.dwg)
You should open a new drawing before you run the code in Example 8-11. When you execute the XRefDemo procedure a base plan is attached (at point 0,0,0) referencing the XRef_New.dwg. Then it is unloaded, reloaded, and finally detached.
Example 8-12. XRefRedefine (references C:\A2K2_VBA\Xref_New.dwg)
Example 8-13. XRefRename
You need to open the C:\A2K2_VBA\Xref_Demo.dwg before executing the XRefRedefine procedure. When you do so you will NOT see the base plan; all four partition plans will look similar to the top two plans in Figure 8-4. If you zoom in on the lower left corner of any of the plans you will see the following text:
This is because the base plan was named Xref_Old when the external references were originally defined. You can see this if you invoke the Xref Manager dialog box. The base plan is now named Xref_New however, and AutoCAD cannot find the original reference drawing.
When you run XRefRedefine, a temporary reference to the Xref to be redefined is made at point 0,0,0 using XRef_New.dwg. XRefRedefine calls the XRefRename procedure, which searches the drawing database for each instance of the old XRef name (they are contained in BlockReference objects), and replaces it with the new XRef definition at the existing coordinates. Finally the temporary reference to the new XRef is deleted and the old XRef is detached. You can verify this by once again looking at the XRef Manager.
If you plan on running the XRefRedefine procedure more than once, use undo to get back to where you started brfore doing so. In any case do not save XRef_Demo.dwg with the new XRefs or else you won't be able to run the procedure again without changing some parameters.
Chapter 9 Entities
Example 9-1. Add3DFace
Example 9-3. Add3DPoly
Example 9-5. AddArc
Example 9-7. AddArc2
Example 9-8. AddCircleTan
Example 9-11. AddEllipse
Example 9-12. AddHatch
Example 9-14. AddLightWeightPolyline
Example 9-15. AddLine
Example 9-18. AddMLine
Example 9-21. AddMText
Example 9-23. AddPoint
Example 9-26. AddPolyfaceMesh (references C:\A2K2_VBA\FullerPoints.txt)
Example 9-28. Add3Dmesh
Example 9-29. AddPolygonMesh
Example 9-31. AddPolyline
Example 9-33. AddRaster (references C:\A2K2_VBA\RasterFile.jpg)
Example 9-35. AddRay
Example 9-37. EditRay
Example 9-38. AddRegion
Example 9-40. AddShape
Example 9-42. AddSolid, AddSolid2
Example 9-44. AddSpline, AddSpline2
Example 9-46. AddText
Example 9-48. AddTrace, AddTrace_Doesnt
Example 9-50. AddXLine
Example 9-29 PolygonMesh (Microsoft Excel VBA)
Chapter 10 Solids
Example 10-1. AddBox
Example 10-3. AddCone
Example 10-4. AddCylinder
Example 10-5. AddEllipticalCone
Example 10-6. AddEllipticalCylinder
Example 10-7. AddExtrudedSolid
Example 10-8. AddExtrudedSolidAlongPath
Example 10-9. AddRevolvedSolid
Example 10-10. AddSphere
Example 10-11. AddTorus
Example 10-12. AddWedge
Example 10-14. SliceSolid
Example 10-15. MassProperties
Chapter 11 Dimensions
Example 11-2. AddDim3PointAngular
Example 11-3. EditDim3PointAngular
Example 11-4. AddDimAligned
Example 11-7. AddDimAngular
Example 11-8. AddDimDiametric
Example 11-10. AddDimOrdinate
Example 11-12. AddDimRadial
Example 11-14. AddDimRotated
Example 11-16. AddLeader1
Example 11-17. AddLeader2
Example 11-19. AddTolerance
Example 11-20. AddToleranceVars
Example 11-21. PrimaryUnitsPrecision
Chapter 12 Editing
Example 12-1. ArrayPolar
Example 12-2. ArrayRectangular
Example 12-3. Copy
Example 12-4. Explode
Example 12-5. GetBoundingBox
Example 12-6. IntersectWith
Example 12-7. Mirror
Example 12-8. Mirror3D
Example 12-9. Move
Example 12-10. Offset
Example 12-11. Rotate
Example 12-12. Rotate3D
Example 12-13. ScaleEntity
Example 12-15. TransformBy
Example 12-16. UndoMarks
Example 12-17. Area
Example 12-18. Coordinate
Example 12-19. Coordinates
Example 12-20. InsertionPoint
Example 12-21. Normal
Example 12-22. Rotation
Example 12-23. Thickness
Example 12-24. SendCommand
Add3DPoly, AddHatch, Boole,
AddEllipse, AddLine, AddText
Chapter 13 AutoCAD Events
Example 13-1. appAcad_EndSave
Example 13-2. CloseAllDrawings
Example 13-3. AcadDocument_Activate, AcadDocument_BeginClose
Example 13-4. AcadDocument_WindowChanged, AcadDocument_WindowMovedOrResized
Example 13-5. object_Modified
Example 13-6. CreateLine
Example 13-7. appAcad_EndCommand
Example 13-8. EventCascade
Chapter 14 Forms and Controls
Chapter14.dvb <The Relative Utility>
Example 14-1. declarations
Example 14-2. Relative
Example 14-3. RelativeMove, RelativeCopy
Example 14-4. RelativeLine
Example 14-5. RelativePline
Example 14-6. Rel_Dist
Example 14-7. D2R, R2D functions SSetDelete
Example 14-8. UserForm_Activate
Example 14-9. UserForm_Initialize
Example 14-10. tglRetainValues_Click
Example 14-11. cmdSetBasePoint_Click, cmdReset_Click, cmdOK_Click, cmdCancel_Click
Example 14-12. txtAngle_Change, txtAngle_AfterUpdate, txtDistanceH_Change, txtDistanceH_AfterUpdate
Example 14-13. txtDistanceX_Change, txtDistanceX_AfterUpdate, txtDistanceY_Change, txtDistanceY_AfterUpdate
Example 14-14. Angl_Set, Dist_Set
Example 14-15. Tile_Set
Chapter 15 Plotting
Example 15-1. PlotConfigurations
Example 15-2. ModelType
Example 15-3. EditPlotConfig
Example 15-4. CopyFrom
Example 15-5. QueryPrintMedia
Example 15-6. PlotDeviceData
Example 15-7. cmdReselectFiles_Click, cmdOK_Click, cmdCancel_Click
Example 15-8,9,10. UserForm_Activate
Example 15-11,12,13. ProcessDrawings (BatchPlot Module)
Example 15-14. declarations, PlotDocs
Chapter 16 Preferences
ILproperty, ILsetvar, AppPref
Chapter 17 Menus
Example 17-1. ListPopBar
Example 17-2. addPopup (references C:\A2K2_VBA\...loads Relative.csv, BatchPlot.csv, FacilityProject.csv)
Example 17-3. delPopup
Example 17-4. addToolbar (references C:\A2K2_VBA\...Relative16.bmp, Relative32.bmp, BatchPlot16.bmp, BatchPlot32.bmp, Facility16.bmp, Facility32.bmp loads Relative.csv, BatchPlot.csv, FacilityProject.csv)
Example 17-5. addFlyout
Example 17-6. delToolbar
Example 17-7. SaveMenuGrp (creates C:\A2K2_VBA\testMNS.mns)
Chapter 18 Extensibility
Example 18-1. XDataMake
Example 18-2. XDataView
Example 18-7. exportXData (creates C:\A2K2_VBA\FacilityData.txt)
Example 18-8. RegAppDelete
Example 18-9. newSub
Example 18-10. importXData (Microsoft Excel VBA)
(references C:\A2K2_VBA\XData2csv.dvb, C:\A2K2_VBA\AllocationPlan02.dwg creates C:\A2K2_VBA\FacilityData.csv)
The importXData Excel procedure in Example 18-10 accomplishes very much the same thing as the exportXData procedure in Example 18-7, only it does it from Excel rather than in AutoCAD. ImportXData first launches a hidden AutoCAD process, then loads the XData2csv.dvb procedure. The AllocationPlan02.dwg is opened and the extended entity data in the drawing are extracted to a CSV file, which is then opened automatically in Excel.
Chapter 19 The Facility Project
Example 19-3. declarations
Example 19-4. UserForm_Initialize (uses DAO 3.5, references C:\A2K2_VBA\FacilityProgram_old.mdb)
Example 19-5. cboGroup_Change
Example 19-6. lstDepartment_AfterUpdate
Example 19-7,8. cmdAllocate_Click
Example 19-9. cmdSuspend_Click, cmdExit_Click (FacilityProject Module)
The CatPlineDate procedure is a variation of Examples 18-3 through 18-6 (CatalogXData), which writes selected text data within the area polylines to a table named "Allocation" in the Access database. This table must exist in the database or a 3011 run-time error will result. Running this procedure more than once with the same data will produce a 3022 run-time error, indicating an attempt to create duplicate keys.
FacilityProgram.mdb (Microsoft Access VBA)
Example 19-1. Form_ProgramDrillDown Class Module
Example 19-2. Form_ProgramDetail Class Module
Chapter 20 The DWF Object Model
Example 20-2. Locate (references C:\A2K2_VBA\...AllocationPlan06-Model.dwf, AllocationPlan07-Model.dwf)
Example 20-3. Output, GetOpenFile, inStream
Example 20-4. chMode
Example 20-5,6. UserForm_Activate
Example 20-7. chkLayersOn_AfterUpdate, lstLayers_Click, lstLayers_DblClick, cmdListLayers_Click
Example 20-8. lstLinks_Click, cmdListLinks_Click
Example 20-9. lstViews_Click, cmdListViews_Click
Example 20-10. chkBackground_AfterUpdate, cmdOK_Click
Example 20-11. CoordConv
Example 20-12. PrintSet
Example 20-13. Merge
SortAsc (Microsoft Excel VBA)
Appendix A System Variables
Example A-1. ScriptVariables
Appendix D DXF Formatting Utility
Example D-1. Dxf2xl (Microsoft Excel VBA)
(NOTE: Each chapter concludes with Summing Up.)
I. THE AUTOCAD VBA ENVIRONMENT.1. Taking Control of AutoCAD.
Components and Automation. The Foundation. A High-Level View. Details. Creating a Drawing with Visual Basic. Setting Available References. Writing the Procedure. More About Components. AutoCAD Inheritance. Method, Property, and Event Matrices.2. The VBA Environment.
Creating and Editing Your Macros. Design Windows. Debugging Windows. Managing and Running Your Macros. VBA Manager. Open VBA Project. Macros Dialog. AutoCAD Command Line.3. DXF: Key to the Drawing Structure.
DXF Format. Objects and Classes. Fixed Group Codes. Variable Group Codes. Subclass Markers. Looking at Your Drawing with VBA. GetSubclass Reads a DWG File. DXFsearch Reads a DXF File. AutoLISP and VBA. Advantages of VBA. VBA Utility.4. Elements of the Object Model.
Automation Interfaces. Application Object. Documents Collection. ModelSpace and PaperSpace. Table Collections. Object Collections. Document Object and Entities. Preferences Object. Custom Menus and Toolbars. MenuBar Collection. MenuGroups Collection.
II. USING THE AUTOCAD OBJECT MODEL.5. Documents and the User Interface.
Methods and Properties. File Management. Creating a Drawing File. Opening, Saving, and Closing a Drawing. Wblock. Exporting and Importing Files. Other File Management Tools. User Interface. Windows. Zooming. Named Views. Viewports. Hyperlinks. AutoCAD Enums. Method, Property, and Event Matrices.6. Collections and Objects.
Application Object. Methods. Properties. Document Object. Methods. Properties. Collections. Managing Collections. Methods. Properties. Table Collections. Layers. LayerStateManager. Linetypes. Registered Applications. TextStyles. User Coordinate Systems. Method, Property, and Event Matrices.7. Utility Objects.
SelectionSets, Filters, and Groups. SelectionSets. Filters. Groups. Utility Object. Data Acquisition. Data Conversion. Internet Access. Dictionaries and the Xrecord. Method, Property, and Event Matrices. @CHAPTER 8. Blocks and External References.
Blocks. Accessing Block Objects. Accessing Block References. Attributes and Attribute References. Properties. Block with Data. MinsertBlock. Properties. Database. CopyObjects Method. Database Properties. External References. Methods. Redefining Xrefs. Layouts. Method, Property, and Event Matrices.9. Entities.
Common Methods and Properties. Definitions. 3Dface. Methods. Property. 3Dpoly. Method. Properties. Arc. Properties. Circle. Properties. Ellipse. Properties. Hatch. Methods. Properties. LightWeightPolyline. Methods. Properties. Line. Properties. Mline. Properties. Mtext. Properties. Point. PolyfaceMesh. Properties. PolygonMesh (3DMesh). Method. Properties. Polyline. Methods. Properties. Raster. Method. Properties. Ray. Properties. Region. Method. Properties. Shape. Method. Properties. Solid. Spline. Methods. Properties. Text. Properties. Trace. XLine. Properties. Entity Methods, Properties, and Events.10. Solids.
Box. Cone. Cylinder. EllipticalCone. EllipticalCylinder. ExtrudedSolid. ExtrudedSolidAlongPath. RevolvedSolid. Sphere. Torus. Wedge. Solid Editing Methods. Mass Properties.11. Dimensions.
Concepts. Dimension Style Manager. Dimension Variables, Styles, and Overrides. Associativity. Dimension Types. Dim3PointAngular. DimAligned. DimAngular. DimDiametric. DimOrdinate. DimRadial. DimRotated. Leader. Tolerance. Dimensioning Properties. Lines and Arrows. Text. Fit. Primary Units. Alternate Units. Tolerances. Other Dimensioning Properties. Orphan DimVars. Dimension Methods, Properties, and Events.12. Editing.
Editing Methods. Array. Copy. Explode. GetBoundingBox. IntersectWith. Mirror. Move. Offset. Rotate. ScaleEntity. TransformBy. Undo. Information Properties. Accessing the Command Line. Related Methods, Properties, and Procedures.13. AutoCAD Events.
Application Events. Application-Level Events. Document Events. AcadDocument Event Handlers. Document-Level Events. Object Events. Event Handler Caveats.14. Forms and Controls.
Command Events. Form Events. Tab Order. The Relative Utility. Relative Module. frmRelative Form. Control Methods and Properties.15. PaperSpace and Plotting.
Plotting Interface. Plot Style Tables. Plotter Configurations. PaperSpace Layouts. System Settings. PlotConfiguration and Layout Objects. PlotConfigurations. Layouts. Common Methods and Properties. PaperSpace Viewports. Methods. Properties. Plot Object. Methods. Properties. BatchPlot. FrmPlotFiles. BatchPlot. Plotting Methods and Properties.16. Preferences.
Programming Style. Files. Methods. Properties. Display. Display Performance. Display Resolution. Layout Elements. Window Elements. Open and Save. External References. File Safety Precautions. File Open and Save. ObjectARX Applications. Plotting (Output). Default Plot Settings for New Drawings. Default Style Behavior for New Drawings. General Plot Options. System. Database Connect Options. General Options. User Preferences. AutoCAD DesignCenter. Hyperlink. Lineweight Settings. Object Sorting Properties. Priority for Coordinate Data Entry. Windows Standard Behavior. Drafting. AutoSnap. AutoTrack. Selection. Grips. Selection Modes and Pickbox. Profiles. Methods. Preferences Methods, Properties, and Events.17. Menus.
Custom Menus and Toolbars. Looking at the Menu Structure. Methods. Properties. Popup Menus. Toolbars. Saving Your Customizations. Method and Property Matrices.
III. COMMUNICATING WITH OTHER APPLICATIONS AND THE INTERNET.18. Extensibility.
Extended Entity Data. Methods. Working with Polylines and XData. VBA Interface. Methods. Properties. Running VBA Remotely. Zero Document State. ARX Applications. Methods.19. The Facility Project.
Microsoft Access Database. Tables, Keys, and Integrity Constraints. Designing the User Dialog. Developing the Queries behind the Dialog. AutoCAD/Access Interface. cboGroup_Change. 1stDepartment_AfterUpdate. 1stProgDetail_Click. Space Allocation.20. The DWF Object Model.
Drawing Web Format. File Structure. Opcodes. Logical Coordinates. Excel Reader Application. XLocate. XLdwf. Whip! Object Reference. General Methods and Properties. Other Collections and Objects. Intrinsic Whip! Events. Whip! Methods and Properties.Appendices.
Data management has been a central focus of mine throughout most of my 30-plus-year career. As an architect engaged mostly in working with business managers, helping them define their project needs (Should I build, lease, expand, or what? ... And how much do I need?), I needed a computer early on. I began using BASIC in 1970, on a timesharing network, to manage the data I collected and to produce reports.
Thus began my involvement with the BASIC language. I have used many dialects, from the line-numbered, Beginners All-purpose Symbolic Instruction Code that came out of Dartmouth University around 1960, to the modern versions of VB and VBA. These are now among the favored languages for communicating with relational databases such as Oracle, SQL Server, and the like, and for creating content for the Internet.
BASIC was so-named because, as an interpreted language, it was easy to learn by incrementally developing a program, entering a few lines of code at a time, and then testing the result. At the time, however, many professional programmers thought it to be something of a toy. Mr. Gates, on the other hand, was a strong supporter of the language, introducing three levels of BASIC with the first IBM PC in 1981. Cassette BASIC was hardwired into the machines' ROM, and you could only save files to a cassette tape. (I never actually did that!)
The disk and advanced levels were built into Microsoft's first version of its operating system: MS-DOS 1.0. A BASIC compiler (BASCOM) was introduced shortly thereafter, which produced executable programs in .EXE format.
Late in the 1980s, QuickBasic was introduced with the first Interactive Development Environment (IDE) for DOS. This was followed in 1991 by Visual Basic 1.0, in both DOS and Windows versions. Visual Basic (VB) continues its growth in popularity.
Microsoft Word and Excel were the first components of Microsoft Office, and each had its own internal functionality for creating macros, essentially scripts that allowed certain procedures to be automated within the application. Visual Basic for Applications (VBA) was first introduced in Excel in 1993. With the addition of Access, PowerPoint, and other products to the mix, VBA now provides an object-oriented programming environment common to all the Office components. This not only allows the creation of macros within each of the applications, but macros that allow Access, for example, to actually start up and communicate with Excel.
AutoCAD is and always has been a database program. Underlying its graphic interface are lists within lists that define the entities that make up your drawing. During its evolution into a fully Windows-compatible product, many new data-oriented features were added.
Initially conceived as a drafting package and written by engineers, AutoCAD was designed with an accessible data structure that allows both the manipulation of its graphic entities as well as the attachment and extraction of textual and numeric data. Attribute extraction using AutoLISP was at first the only means of manipulating the data within the drawing, and this method was widely used in the DOS days of the mid-1980s, when I began using the application. The AutoCAD SQL Extension (ASE), introduced with Release 12 in the early 90s, provided a rudimentary interface to databases such as DBASE and PARADOX.
AutoCAD was recast in object-oriented C++ with Release 13 and the introduction of the AutoCAD Runtime Extension (ARX). Using ARX requires a programmer capable of creating DLLs using C++, which the average AutoCAD user is not. About the same time, however, AutoCAD users began experimenting with programs written in Visual Basic 3.0 using Dynamic Data Exchange (DDE). Curiously, support for a more robust connection between VB and AutoCAD had been provided in Release 12, but was dropped in Release 13. Autodesk added support for Microsoft's ActiveX Automation interface standard to Release 14, first allowing VBA access to AutoCAD objects.
Autodesk initially released AutoCAD 2000 in the spring of 1999, fully incorporating VBA. Further enhancements focusing on Internet functionality were a feature of the 2000i release in the summer of 2000. The development environment has a look and feel identical to that of any Microsoft Office component. With this convergence, the ability to write AutoCAD macros and communicate with other VBA-enabled applications is now fully accessible to the user.
Now, with the release of AutoCAD 2002, Autodesk has adopted a policy of regular releases, incorporating "technology extensions" in the form of incremental upgrades. The extensions added over each period of time will be incorporated into the latest modular release.
AutoCAD 2002 is the flagship product of Autodesk, which, according to the company's web page "is the world's leading supplier of PC design software and digital content creation." Since its initial release in 1982, well over two million copies of AutoCAD have been shipped. There are nearly 1000 Autodesk Training Centers worldwide, and over one million students are trained on Autodesk products each year.
Eighty five percent of the companies in the Fortune 500 are Autodesk customers, and the firm's products are available in 19 languages. There are, according to Autodesk, over 200 user groups worldwide, along with almost 3000 registered developers.
There are also countless unregistered developers who have no formal relationship with Autodesk. They produce add-ons and customizations both for sale and for their own and their companies' use. The CAD Manager who needs to convert the layers of several hundred drawings received from another consultant is a potential AutoCAD developer. The Facility Manager who needs to link drawing attributes representing occupied and available areas to an Excel spreadsheet can now use VBA to accomplish this.
Automation using VBA allows the user to work on the AutoCAD side, or the Excel side, or in some other application, whichever he or she is more comfortable with. I have routinely used VBA to write SQL scripts to populate database tables, as well accessing and modifying drawings in AutoCAD. I used to do many of these things in AutoLISP, which was the only act in town for 15 years.
This book is for the AutoCAD and Office user who has problems to solve. Users who are already programmers can use it to familiarize themselves with the AutoCAD object model. Users who are not programmers will be able to get started by studying the book's examples.
My paramount goal, more than just presenting the components of VBA, is to tie together the disparate elements of AutoCAD with which you must be reasonably comfortable in order to use VBA effectively. The AutoCAD documentation treats, in unrelated discussions, many of those features that need to work in concert to get a job done. Understanding the DXF file representation, for example, together with some of the basic syntax of AutoLISP as it relates to the underlying database structure, provides the keys to unlocking the AutoCAD drawing and manipulating its data. It is the purpose of this book to provide those necessary links.
VBA for AutoCAD 2002: Writing AutoCAD Macros is divided into three major sections:
There are four appendices containing additional reference material as well as some supplemental utilities and examples. Part Two, Using the AutoCAD Object Model, is by far the longest section, in which the application's numerous collections and objects will be discussed in detail.
The following outline gives you an overview of what you can expect to see in each chapter.
Chapter 1, Taking Control of AutoCAD, introduces you to some of the concepts of Automation and Microsoft's Component Object Model (COM). In it we will talk about what we mean by object-oriented programming; its tripartite foundation of encapsulation, inheritance, and polymorphism; and define such terms as class, interface, and binding. We will look at a programming example that reads data from an Excel worksheet and creates an AutoCAD drawing with it, without either application being visible, in 30 lines of code. Finally, we will introduce a system that we will use to chart all of AutoCAD's methods, properties, and events, categorizing them in a concise reference format that will be used throughout the book.
Chapter 2, The VBA Environment, shows you how to use the Interactive Development Environment (IDE); how to create, edit, and save VBA projects; and differentiates between global and embedded projects.
Chapter 3, DXF: Key to the Drawing Structure, goes into some necessary detail about DXF that will add to your understanding of the drawing database. Subclass markers, which are the reflection of AutoCAD's internal object structure, are introduced. We will develop two small VBA projects. One lets you look at selected DXF entity data within an AutoCAD drawing (DWG) file, and the other searches for specified entities in a DXF file. At the end of the chapters we will look at two tiny procedures that do the same thing, one in VBA and one in AutoLISP. You can decide for yourself which is the more accessible of the two languages.
Chapter 4, Elements of the Object Model, introduces the AutoCAD object model. We will talk a little more about Automation interfaces, but will concentrate on taking a high-level view of the collections and objects that VBA offers within AutoCAD.
Chapter 5, Documents and the User Interface, begins our top-down examination of the object model in detail. In the first part of the chapter we will talk about file management: creating, opening, saving, closing, importing, and exporting drawings. Then we will turn our attention to the user interface, discussing how to control your display and how to handle views and viewports.
Chapter 6, Collections and Objects, continues our traversal of the object model with a discussion of the Application and Document objects. We will discuss such document-related functions as layer management and then look at how to manage Collections and access the data within the Objects they contain.
Chapter 7, Utility Objects, concludes our introduction of the AutoCAD object model. In this chapter we will concentrate on functions related to creating and editing drawing data, such as Selection Sets: How to select entities in the drawing in order to do something to them. The utility object includes methods for acquiring and converting the formats of data and accessing the Internet.
Chapter 8, Blocks and External References, prefaces Chapters 9-11, which deal with the AutoCAD graphic objects, or entities, both two- and three-dimensional. Blocks are complete AutoCAD drawings that have been inserted into other drawings, as symbols in many instances. We discuss Attributes in this chapter, which provide one of the means by which alphanumeric data can be stored and accessed in AutoCAD drawings.
External References, which are similar to blocks, exist when other drawings are not actually inserted, but references to them are created so that changes appear automatically when the referenced drawings are updated. In Chapter 8 we will create procedures to rename and redefine XRefs, as they are called, while preserving their insertion instances.
Chapter 9, Entities, covers all 23 basic AutoCAD Entities exclusive of the modeled solids and dimensions. We will dwell at some length upon some of the more interesting ones such as the Multiline, seeing how it is constructed and how to create multiline styles using DXF representation. Both kinds of meshes are treated in detail. We will create a Polyface Mesh from a data table stored in a text file and a Polygon Mesh using an Excel VBA macro and a point matrix stored in a worksheet.
Chapter 10, Solids, covers the 11 three-dimensional entities in the domain of AutoCAD's solid modeler. In addition to constructing them, we will concentrate on the methods for editing them, creating compound objects using Boolean functions, making sections, and slicing. Finally, we will discuss their mass properties, such as moment of inertia, and what these properties mean.
Chapter 11, Dimensions, covers the seven basic dimension types together with the Leader and Tolerance objects. We begin this chapter with a discussion of dimension styles and how to manage them. Creating and using special symbols with the tolerance object for annotation purposes is also covered. The remainder of the chapter is devoted to the dimensioning properties, which are categorized according to AutoCAD's dimension style manager. Each property is defined, along with its corresponding system variable.
Chapter 12, Editing, extends our vocabulary of methods for changing and manipulating AutoCAD objects, such as Copy, Move, and the like. We will spend some time on a subject that is often glossed over, the use of geometric transformation matrices. We will develop a procedure that uses the TransformBy method to dynamically zoom and scale a three-dimensional object.
Chapter 13, Events, deals with AutoCAD's "inflection points," which occur whenever there is a change of state in the application itself, the drawing you are working on, or an entity. You can write VBA subroutines called event handlers that automatically execute whenever the event to which they are connected occurs.
Chapter 14, Forms and Controls, covers the principal user interface with VBA programs. Forms are containers for dialog box controls such as command buttons, list boxes, and the like, through which the user directs the program. After introducing the standard toolbox and some tips for using it, we will spend the balance of the chapter developing a utility application to discover how to integrate the form interface with many of the entity creation and editing functions we have been discussing. The utility application, called Relative, copies or moves selected entities relative to an existing location, using a dialog box. Relative also draws lines and polylines relative to a specified start point.
Chapter 15, PaperSpace and Plotting, will discuss Viewports along with the Plot Configuration and Layout objects, two alternative means of formatting drawings. PaperSpace is AutoCAD's environment intended for setting up drawings to print. We will look at the methods for detecting plotter and media characteristics in order to produce the desired output.
We will develop a plotting application called BatchPlot, which will format (in paper space) and plot multiple drawings with your desired layer settings. You specify the drawings to be printed using either Visual Basic's common dialog box or a list contained in a text file.
Chapter 16, Preferences, deals with parts of the AutoCAD object model that control characteristics of the application itself, its environment, and the means of manipulating it, rather than the drawing itself. These are of two types, preferences stored in the registry, corresponding to the tabs on the AutoCAD's dialog box for user options, plus user options stored in the drawing that can be accessed from other applications without the use of AutoCAD itself.
Chapter 17, Menus, gives you the means of altering AutoCAD's main menu, toolbars, and other menus using VBA.
Chapter 18, Extensibility, will demonstrate how you can use VBA to communicate with other applications. It covers extended entity data in detail, introducing some concepts and test data that will be used more extensively in Chapter 19's project.
This chapter also covers working in a zero document state, the VBA interface itself, and a brief section on ARX application handling.
Chapter 19, The Facility Project, ties together much of the material presented throughout the book into an application that links an AutoCAD drawing to a Microsoft Access database. The facility project (FP) uses Microsoft's Data Access Objects (DAO) object model to integrate AutoCAD with Access, in order to track area allocation in an office layout.
Chapter 20, The DWF Object Model, will go beyond AutoCAD, using and give you an understanding of how to use this additional functionality in querying and displaying drawings in DWF format over the Internet. AutoCAD's Whip! viewer, which is freely downloadable for displaying drawings in a browser, also has a VBA programming interface.
We will develop an Excel-based procedure that locates a specified floor drawing and room based on a row selection in a worksheet.
Appendix A, System Variables: A dictionary of the AutoCAD system variables, other than those pertaining to dimensions covered in Chapter 11.
Appendix B, Enums: A listing of AutoCAD's enumerated variables, defined integer constants used in developing VBA macros.
Appendix C, Object Inheritance: A chart of AutoCAD's COM interface hierarchy.
Appendix D, DXF Reference: A selection of the basic graphical entities as they are represented in DXF format. An Excel VBA application is included that will read your DXF files and list the various sections in a conveniently readable format.