575 Drawing an AutoCAD Line from Word... Combining the power of AutoCAD and Visual Basic providesendless opportunities for creating impressive customized applications ranging fromstreaml
Trang 1Mastering ™
San Francisco • Paris • Düsseldorf • Soest • London
Marion Cottingham
Trang 3AutoCAD VBA
Trang 5Mastering ™
San Francisco • Paris • Düsseldorf • Soest • London
Marion Cottingham
Trang 6Acquisitions and Developmental Editor: Raquel Baker
Editor: Carol Henry
Production Editor: Nathan Whiteside
Technical Editor: Steve Hansen
Book Designer: Franz Baumhackl
Electronic Publishing Specialist: Jill Niles
Proofreaders: Nancy Riddiough, Nanette Duffy, Laurie O’Connell, Emily Hsuan
Indexer: Ted Laux
CD Coordinator: Erica Yee
CD Technician: Kevin Ly
Cover Designer: Design Site
Cover Illustrator: Sergei Loobkoff, Design Site
Copyright © 2001 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501 World rights reserved The author created reusable code in this publication expressly for reuse by readers Sybex grants readers limited permission to reuse the code found in this publication or its accompanying CD-ROM so long as author is attributed in any application containing the reusabe code and the code itself is never distributed, posted online by electronic transmission, sold, or commercially exploited as a stand-alone product Aside from this specific exception concerning reusable code, no part of this publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photo- graph, magnetic, or other record, without the prior agreement and written permission of the publisher.
Library of Congress Card Number: 2001087093
ISBN: 0-7821-2871-8
SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc in the United States and/or other countries.
Mastering is a trademark of SYBEX Inc.
Screen reproductions produced with FullShot 99 FullShot 99 © 1991-1999 Inbit Incorporated All rights reserved FullShot is a trademark of Inbit Incorporated.
Internet screen shots using Microsoft Internet Explorer 5.5 reprinted by permission from Microsoft Corporation.
TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms
by following the capitalization style used by the manufacturer.
The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software whenever possible Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s) The author and the publisher make no representation or warranties of any kind with regard to the com- pleteness or accuracy of the contents herein and accept no liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages of any kind caused or alleged to be caused directly or indirectly from this book.
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Trang 7The media and/or any online materials accompanying this book
that are available now or in the future contain programs and/or text
files (the “Software”) to be used in connection with the book.
SYBEX hereby grants to you a license to use the Software, subject
to the terms that follow Your purchase, acceptance, or use of the
Software will constitute your acceptance of such terms.
The Software compilation is the property of SYBEX unless
other-wise indicated and is protected by copyright to SYBEX or other
copyright owner(s) as indicated in the media files (the “Owner(s)”).
You are hereby granted a single-user license to use the Software for
your personal, noncommercial use only You may not reproduce,
sell, distribute, publish, circulate, or commercially exploit the
Soft-ware, or any portion thereof, without the written consent of SYBEX
and the specific copyright owner(s) of any component software
included on this media.
In the event that the Software or components include specific
license requirements or end-user agreements, statements of
con-dition, disclaimers, limitations or warranties (“End-User License”),
those End-User Licenses supersede the terms and conditions herein
as to that particular Software component Your purchase,
accept-ance, or use of the Software will constitute your acceptance of such
End-User Licenses.
By purchase, use or acceptance of the Software you further agree to
comply with all export laws and regulations of the United States as
such laws and regulations may exist from time to time.
Reusable Code in This Book
The authors created reusable code in this publication expressly for
reuse for readers Sybex grants readers permission to reuse for any
purpose the code found in this publication or its accompanying
CD-ROM so long as all three authors are attributed in any
appli-cation containing the reusable code, and the code itself is never sold
or commercially exploited as a stand-alone product.
Software Support
Components of the supplemental Software and any offers
associ-ated with them may be supported by the specific Owner(s) of that
material but they are not supported by SYBEX Information
regard-ing any available support may be obtained from the Owner(s) usregard-ing
the information provided in the appropriate read.me files or listed
elsewhere on the media.
Should the manufacturer(s) or other Owner(s) cease to offer
sup-port or decline to honor any offer, SYBEX bears no responsibility.
This notice concerning support for the Software is provided for
your information only SYBEX is not the agent or principal of the
Owner(s), and SYBEX is in no way responsible for providing any
support for the Software, nor is it liable or responsible for any
sup-port provided, or not provided, by the Owner(s).
Warranty
SYBEX warrants the enclosed media to be free of physical defects
for a period of ninety (90) days after purchase The Software is not
available from SYBEX in any other form or media than that enclosed herein or posted to www.sybex.com If you discover a defect in the media during this warranty period, you may obtain a replacement of identical format at no charge by sending the defec- tive media, postage prepaid, with proof of purchase to:
SYBEX Inc.
Customer Service Department
1151 Marina Village Parkway Alameda, CA 94501 (510) 523-8233 Fax: (510) 523-2373 e-mail: info@sybex.com WEB: HTTP://WWW.SYBEX.COM After the 90-day period, you can obtain replacement media of iden- tical format by sending us the defective disk, proof of purchase, and
a check or money order for $10, payable to SYBEX.
Disclaimer
SYBEX makes no warranty or representation, either expressed or implied, with respect to the Software or its contents, quality, per- formance, merchantability, or fitness for a particular purpose In
no event will SYBEX, its distributors, or dealers be liable to you or any other party for direct, indirect, special, incidental, consequen- tial, or other damages arising out of the use of or inability to use the Software or its contents even if advised of the possibility of such damage In the event that the Software includes an online update feature, SYBEX further disclaims any obligation to provide this fea- ture for any specific duration other than the initial posting The exclusion of implied warranties is not permitted by some states Therefore, the above exclusion may not apply to you This warranty provides you with specific legal rights; there may be other rights that you may have that vary from state to state The pricing of the book with the Software by SYBEX reflects the allocation of risk and limitations on liability contained in this agreement of Terms and Conditions.
Shareware Distribution
This Software may contain various programs that are distributed
as shareware Copyright laws apply to both shareware and ordinary commercial software, and the copyright Owner(s) retains all rights.
If you try a shareware program and continue using it, you are expected to register it Individual programs differ on details of trial periods, registration, and payment Please observe the requirements stated in appropriate files.
Copy Protection
The Software in whole or in part may or may not be copy-protected
or encrypted However, in all cases, reselling or redistributing these files without authorization is expressly forbidden except as specif- ically provided for by the Owner(s) therein.
Software License Agreement: Terms and Conditions
Trang 9To all my students, past and present, who have inspired me more than they’ll ever know.
—Marion Cottingham
Trang 11I would like to thank all my supporters from the University of Western Australia,especially those from the Computer Science and Software Engineering department Inparticular, thanks to Dr Sandra Penrose for her helpful advice; Professor Barry Brady(Executive Dean of the Faculty of Engineering and Mathematical Sciences) for allow-ing me study leave to engage in the scholarly activity of writing this book; ProfessorAlan Robson (Deputy Vice-Chancellor) for his indirect support; and Colin Campbell-Fraser (Director of Public Affairs) for his encouragement
Thanks goes to everyone at Sybex who worked on this book, especially to theAssociate Publisher Cheryl Applewood for giving me the opportunity to write it, andDevelopment Editor Raquel Baker who kept me on track until the book went into itsproduction phase Thanks go to Production Editor Nathan Whiteside, who helped me
to keep to deadlines with his insatiable appetite for chapters He coordinated thewhole project and made the book happen on time
Thanks to the Editor Carol Henry for her excellent editing, enthusiasm, and gestions…from start to finish She truly made this a better read and kept me companyduring the twilight hours while I worked sixteen hours ahead of her hanging upsidedown at the other side of the world Thanks to the Technical Editor Steve Hansen forhis comments and expert advice that also have made this a better book
sug-Thanks to Manufacturing Specialist Steve Melville and to Electronic PublishingSpecialist Jill Niles, who put my words onto the printed page, and to Indexer Ted Laux,who has made all the material in the book easy to find
Finally, thanks to Autodesk for producing AutoCAD, which is such a powerfulsoftware package that is fun to use and has made defunct the phrase “and now back tothe drawing board!”
Trang 12Contents at a Glance
Introduction xxiii
Part 1 • VBA Macros and the Visual Basic Editor 1
Chapter 1 • Developing a Simple VBA Application 3
Chapter 2 • Creating VBA Macros 29
Chapter 3 • Quick Tour of the IDE 53
Chapter 4 • VBA Programming Concepts 79
Part 2 • Drawing Lines and Solid Areas Using VBA Macros 129
Chapter 5 • The AutoCAD Object Model 131
Chapter 6 • Macro-izing Line Drawing 167
Chapter 7 • Macro-izing Solid Areas 221
Part 3 • Reusability and Customization 267
Chapter 8 • Templates and Reusability 269
Chapter 9 • Creating Drawings with Text 305
Trang 13Chapter 10 • Debugging Your Code 355
Chapter 11 • Dimensioning Drawings from Your Own Menus and Toolbars 375
Chapter 12 • File Input and Output 419
Part 4 • 2D Drawing Techniques 447
Chapter 13 • Working with 2D Drawing Techniques 449
Chapter 14 • Grouping Objects 471
Part 5 • 3D Drawing Techniques 511
Chapter 15 • Creating and Drawing 3D Solids 513
Chapter 16 • ActiveX Controls 565
Chapter 17 • AutoCAD and the Internet 597
Appendix A • Object Models 619
Appendix B • ASCII Character Set 631
Index 637
CONTENTS AT A GLANCE xiii
Trang 14Introduction xxiii
Part 1 • VBA Macros and the Visual Basic Editor 1
Chapter 1 • Developing a Simple VBA Application 3
Advantages of Using VBA with AutoCAD 5
The AutoCAD VBA Environment 6
Creating UserForm Modules 7
Puttering around in the Toolbox 8
Developing Your First Application 14
Creating the GUI 14
Setting Captions in the Properties Window 17
The VBA Code Window 19
Running Your Application 24
Saving Your Application 25
Returning to AutoCAD 26
Summary 27
Chapter 2 • Creating VBA Macros 29
What Is a Macro? 31
ThisDrawing Object 31
Standard Modules 32
Creating a Macro to Add Text to a Drawing 34
Using the IDE’s Editing Features to Enter Code 34
Saving a Macro 41
Running a Macro 42
Using VBA’s Date and Time Functions 45
Updating Your DrawText Macro 45
Loading VBA Project Files 46
Loading a Project Manually 46
Loading a Project Each Time a Drawing Object Is Opened 48
Loading a Project When AutoCAD Starts Up 48
Canceling the Loading of a Project at Startup 50
Trang 15Starting an Application from a Macro 50
Summary 51
Chapter 3 • Quick Tour of the IDE 53
VBA IDE Components 55
Exploring the Menu Bar 56
Setting Your IDE Options 58
The IDE’s Toolbars 62
Printing UserForms 70
Overview of the Code Commands 71
Commands for Editing Code 71
Commands for Debugging Code 72
Commands for Running Code 73
Getting Help 74
Context-Sensitive Help 77
Summary 77
Chapter 4 • VBA Programming Concepts 79
How Code Instructs the Computer 81
Statements and Expressions 81
All about Variables 82
Declaring Variables Using the Dim Statement 84
To Declare or Not to Declare? 85
Handling Arrays of Variables 86
Creating an Array 87
Accessing Array Elements 87
All About Constants 89
Declaring Symbolic Constants 89
Viewing Built-in Constants in the Object Browser 90
Scope of Constants and Variables 94
Public vs Private 94
Scope at the Procedure Level 95
UserForm and Module-Level Scope 95
Static Statements and the Static Keyword 96
Defining Your Own Types 99
Using Conditions to Control Code Execution 100
If…Then…Block 100
If…Then…Else… 102
Select Case Statement 103
Trang 16Using Loops to Repeat Code 104
Repeating Code a Set Number of Times 105
Repeating Code an Unknown Number of Times 106
Overview of Objects, Properties, Methods, and Events 107
All about Objects 107
AutoCAD Drawing Objects 109
The Microsoft Forms Object Model 111
All about Properties 113
All about Methods 119
All about Events 120
Comparing VBA Programming Constructs 121
Macros 121
Procedures 122
Setting the Tab Order for Controls 125
Functions 126
Parameters and Arguments 127
Programs 127
Applications 128
Summary 128
Part 2 • Drawing Lines and Solid Areas Using VBA Macros 129
Chapter 5 • The AutoCAD Object Model 131
AutoCAD Application Object 133
AutoCAD Document Objects 134
Coding the Finding Name Application 136
Running an Application from a Macro 140
Loading Your Application 142
Communicating with Message Boxes 142
The MsgBox Function 142
Graphical Object Spaces 147
ModelSpace Collection 147
PaperSpace Collection 147
Block Objects 150
Adding Graphical Objects 150
Accessing Graphical Objects 152
Preferences Object 154
Sending Text to the AutoCAD Command Line 159
Trang 17VB’s String-Handling Functions 161
Summary 166
Chapter 6 • Macro-izing Line Drawing 167
Drawing a Line 169
A Control’s TabIndex and TabStop Properties 176
The With Statement 176
Setting Linetypes 177
Running Your Line Drawing Application 186
Highlighting a Line from a Macro 188
Highlighting and Coloring All Lines 192
Identifying Lines Selected by the User 198
Scales and Weights for Lines 200
Scaling Using a Transformation Matrix 206
Scaling a Line with Respect to the Origin 207
Scaling with Respect to a Fixed Point 210
Multiple Parallel Lines 214
Using Arc Objects 215
Lots of Arcs 217
Summary 219
Chapter 7 • Macro-izing Solid Areas 221
Drawing Circles 223
Drawing Filled Circles 225
Circle of Bricks Application 229
Drawing Freeform Shapes 236
Calculating Areas of Shapes 249
Filling with Inner and Outer Loops 250
Working with Input Boxes 258
Multiple-Line Prompts 259
Drawing a Range Top from a Macro 260
Summary 265
Part 3 • Reusability and Customization 267
Chapter 8 • Templates and Reusability 269
Templates for Reusability 271
Setting the Drawing Units 272
Setting Drawing Units from VBA Code 273
Trang 18All about Grids 278
Displaying Grid Points 278
Setting Grid Limits 280
Displaying the Whole Grid 281
Setting the Spacing for Grid Points 283
All about Snapping 285
Setting the Snap Spacing 285
Changing All the Environment Settings from a Macro 287
Creating the Floor Plan from a Macro 288
Creating a Template 292
Creating a New Drawing from a Template 293
Macros vs Templates 295
Working with a User Coordinate System 295
Creating a UCS from a Macro 296
Viewing the UCS Matrix 297
Toggling the USC Icon On and Off 300
Copying Objects Using a Macro 302
Summary 304
Chapter 9 • Creating Drawings with Text 305
Creating New Drawing Documents from a Macro 307
Creating Arrays of Objects 310
Polar Arrays 310
Rectangular Arrays 316
Setting Text Attributes 320
Setting Text Attributes in AutoCAD 320
Setting Text Attributes from a Macro 322
Formatting Text from a Macro 324
Formatting Numbers, Times, and Dates 340
Formatting Numbers 340
Formatting Times and Dates 341
Validating Input 342
Adding Text to Arrows 343
Summary 353
Chapter 10 • Debugging Your Code 355
Types of Errors 357
Logic Errors 357
Compiler Errors 359
Run-Time Errors 361
Trang 19Debug Menu Commands 362
Using Breakpoints 363
Stepping Through Code 365
Using the IDE’s Debugging Windows 366
The Immediate Window 366
The Watches Window 368
The Locals Window 369
Which Debugging Aid to Use? 372
The Call Stack 372
Summary 374
Chapter 11 • Dimensioning Drawings from Your Own Menus and Toolbars 375
AutoCAD’s Dimensioning Styles 377
Dimensioning Drawings from an Application 379
The Aligned Dimensioning Style 380
The Angular Dimensioning Style 381
The Diametric Dimensioning Style 382
The Ordinate Dimensioning Style 383
The Radial Dimensioning Style 384
The Rotated Dimensioning Style 386
The 3 Point Angular Dimensioning Style 386
A Dimensioning Application 387
Saving Your Dimension Styles 400
Using Your Own Dimension Style 403
Customizing Menu Commands 405
Creating a New Menu to Run Macros 406
Creating Your Own Toolbar 411
Adding Preprogrammed Toolbar Buttons 416
Summary 418
Chapter 12 • File Input and Output 419
Handling Drawing Files in Your Code 421
Creating a New Drawing from a Macro 421
Saving a Drawing to a File 425
Verifying That a File Exists 427
Copying Files 429
Displaying Open and Save As Dialog Boxes 430
Using the CommonDialog Control 432
Trang 20Writing Data to a File from Code 437
Input and Output Modes for Opening Files 441
The Application Path Property 442
Using the Input Statement to Read Data from a File 443
Closing Files 445
Summary 446
Part 4 • 2D Drawing Techniques 447
Chapter 13 • Working with 2D Drawing Techniques 449
Interactive Drawing Techniques for Precision 451
Changing Grid and Snap Angles 451
Controlling Polar Tracking 453
Drawing Splines 456
Adding and Loading Shapes 461
Loading and Adding Shapes from a Macro 462
Moving a Drawing Object from within Code 465
Summary 469
Chapter 14 • Grouping Objects 471
Collecting Objects into Layers 473
Creating Layers from the AutoCAD Window 473
Creating Layers from a Macro 474
Changing Settings in the Layer Properties Manager 483
The On, Freeze, and Lock Options 485
Locking and Unlocking Layers in Code 485
Freezing and Thawing Layers in Code 486
Turning Layers On and Off in Code 488
Accessing All Layers from a Macro 488
Grouping Objects into Blocks 490
Creating a Simple Block 490
Adding a Block to a Drawing 492
Referencing External Blocks 494
Moving Blocks 496
Using Selection Sets 496
Selection Modes 504
InitializeUserInput Method 504
Trang 21Using Groups 505
Creating a New Group 505
Accessing Individual Drawing Objects from a Group 509
Summary 509
Part 5 • 3D Drawing Techniques 511
Chapter 15 • Creating and Drawing 3D Solids 513
Creating 3D Solids 515
Creating a Box 521
Creating a Wedge 524
Creating a Sphere 526
Creating a Torus 529
Creating a Cone 532
Creating a Cylinder 535
Constructing Complex Solids 543
Determining Whether Two Solids Intersect 547
Grow Your Own Solids 547
Creating Solids by Extrusion 547
Creating Solids by Revolution 551
Chamfered and Filleted Edges 554
Chamfering and Filleting Edges from a Macro 554
Cross-Sectioning 3D Solids 560
Summary 564
Chapter 16 • ActiveX Controls 565
ActiveX and COM 567
Using AutoCAD with Other Applications 567
Dragging Objects into AutoCAD 567
Using ActiveX Controls in Macros 569
Exchange between AutoCAD and Excel 569
Saving Line Data to an Excel Spreadsheet 570
Drawing an AutoCAD Line from Excel 573
Exchange between AutoCAD and Word 575
Sending Data to Word from an AutoCAD Macro 575
Drawing an AutoCAD Line from Word 578
Trang 22Exchange between AutoCAD and a Database 580Saving Line Data in a Database 583Creating an Access Module from a VBA Macro 588Displaying Data in Access Forms 591Summary 596
Chapter 17 • AutoCAD and the Internet 597
URL Paths of Files on the Web 599Browsing the Web for Files 599Downloading a Web File Using Macros 600Getting the URL Using a Macro 601Launching the Browser from a Macro 603The Code for Getting a Web File 605The Code for Sending a File to the Web 606Putting It All Together 608Preparing Drawings for Publishing on the Web 609Adding Hyperlinks to a Drawing 614Adding Hyperlinks from the AutoCAD Window 615Adding Hyperlinks from a Macro 616Summary 618
Appendix A • Object Models 619
AutoCAD Object Model 621Microsoft Office Object Model 624Microsoft Excel Object Model 626Microsoft Access Object Model 628Microsoft Word Object Model 629
Appendix B • ASCII Character Set 631
Index 637
Trang 23Autodesk first included Microsoft’s Visual Basic for Applications (VBA) inAutoCAD Release 14 Combining the power of AutoCAD and Visual Basic providesendless opportunities for creating impressive customized applications ranging fromstreamlining the routine tasks you currently perform using AutoCAD to creatingdrawings in seconds that would normally take hours The book takes you step-by-stepthrough how to create macros to automate the routine tasks you currently do inAutoCAD It shows you how to create powerful Windows applications so that you canrun your macros at the click of a button You’ll quickly learn how much fun it is tobuild graphical user interfaces (GUIs) by simply dragging and dropping controls from
a toolbox to a UserForm—you already do much the same thing when you developdrawings using AutoCAD
The material in this book is compatible with AutoCAD 14, AutoCAD 2000, andAutoCAD 2000i
I’m sure you’ll enjoy developing code with all the pop-up help provided by theVisual Basic for Applications Integrated Development Environment (VBA IDE) Ifyou’re lucky enough to be using AutoCAD 2000i with its new updated Heidi® graphicsengine, you have access to its revolutionary Internet/intranet tools that enable you topublish drawings on the Web to speed up your design review process You’ll enjoy theimprovements to the Array interface that help you preview your results, and the exten-sion to the 3D Orbit feature that allows lights, materials, and textures support whileorbiting You’ll also find that you can now ask questions of the Help facility, rather thanhaving to guess at the name of a command, method, or property And you’ll also notice
an Active Assistant on display to provide additional help
If you are not using AutoCAD 2000i and would like more information about it, go
to Autodesk’s AutoCAD Product Center at the following URL Here you can get productinformation, view an interactive demonstration, or (in the United States and Canada)order a free demo CD
http://www3.autodesk.com/adsk/index/0,,303942-123112,00.html
Who Should Read This Book
This book assumes that the reader is already a casual user of AutoCAD and knows itsfundamentals (opening and closing drawing files, interactively creating drawings, and soforth) The material in this book extends this knowledge by showing how to perform the
Trang 24same tasks from VBA code, and how to enhance AutoCAD by customizing additionalinterfaces that make it easier to perform some tasks.
To the reader who wants to learn how to code macros in VBA, this book assumes
no prior knowledge of VBA or any other programming language It is the ideal bookfor AutoCAD users to learn how to write code to automate routine tasks This bookprovides you with the stepping stones needed to develop your very own macros andapplications that run inside AutoCAD
To the reader who has VBA programming experience from other applications,you’ll learn about the numerous objects and collections that AutoCAD has to offer andthe methods and properties these contain
Since most examples show how to perform a task first from the AutoCAD windowand then from VBA code, readers with no coding experience will quickly see the rela-tionships between how they perform a task in the AutoCAD window and the objectsthey need to use in code to perform the same task The reader with coding experiencewill quickly see the relationships of the objects they use in code, to the drawing objects,options, and settings required for the AutoCAD window
What You Can Do with VBA
Endless numbers of tasks are just waiting to be automated using VBA After you’vetaken the time to develop a macro or an application and have fully tested that it workscorrectly, the code is guaranteed to perform correctly and reliably every time you use
it Just think of the timesaving possibilities of running your code instead of goingthrough the same sequence of actions over and over again Using VBA, many tasks can
be completed with one or two mouse clicks—you can’t beat that Freeing up yourtime on the menial tasks lets you concentrate more on the complex tasks that requireyour artistic abilities
As you make your way through this book and become more experienced at gramming, you’ll get more and more ambitious and find lots of things that are suitablefor automating Just about any task that you do manually in AutoCAD can be auto-mated using VBA This book takes you by the hand and gently guides you deeper intothe “mysteries” of coding Because of the VBA IDE’s easy-to-use features, programmers
pro-no longer need to be gurus You’ll be amazed at just how quickly you start developingfull-blown Windows applications that run smoothly alongside AutoCAD
Trang 25What’s In This Book
This book takes you through the practical steps of creating powerful and time-savingVBA macros and applications The focus is on automation aimed at saving time,increasing productivity, and producing complex drawings at the click of a button Thebook is divided into five parts:
Part 1: VBA Macros and the Visual Basic Editor
Part 1 shows you how to develop your first application and takes you on a quick tour ofthe Visual Basic Editor You’ll also be introduced to some VBA programming conceptsthat you’ll find useful as a reference as you progress through the book
Chapter 1 provides step-by-step instructions for developing a simple applicationthat requires a GUI, containing controls from the VBA Toolbox that are coded torespond to a user’s actions
Chapter 2 shows you how to create macros that can run on their own or be used tostart an application You’ll learn to make the most of the IDE’s powerful editing features.Chapter 3 takes you on a quick tour of the IDE, showing you how to access its vari-ous windows You’ll also see how to display some of the toolbars, and how to make thebest use of the Help facility
Chapter 4 covers all the programming concepts you need for getting well way as an AutoCAD VBA programmer You’ll find it useful to have all this information
under-in one location rather than dispersed throughout the book—it’s much easier to comeback to later
Part 2: Drawing Lines and Solid Areas Using VBA Macros
Part 2 is your tutor for using objects from the AutoCAD Object Model—lines, circles,and freeform shapes—and how to fill areas with color
Chapter 5 shows the hierarchical structure of the AutoCAD Object Model You’ll seehow to access its objects from code You’ll work through what’s required to communicatewith users via message boxes, and learn how to send a command to the AutoCAD com-mand line from a macro
Chapter 6 covers drawing lines and setting their attributes (linetype, color, andthickness) from a macro You’ll also see how to scale drawing objects from a macro
Trang 26Chapter 7 demonstrates drawing circles and freeform shapes and filling them withcolor The points defining the freeform shapes are selected by the user, and the values ofthe coordinates are passed to a macro.
Part 3: Reusability and Customization
In Part 3, you’ll fashion an AutoCAD template and create a new drawing documentfrom code You’ll see how to design a new group of menu commands and toolbar but-tons in the AutoCAD window to run your macros, and how to read and write data to afile
Chapter 8 shows how to set the AutoCAD environment settings and make a plate drawing from a macro It compares macros and templates from the point of view
tem-of reusability, and introduces User Coordinate System (UCS) concepts applicable toAutoCAD VBA programming
Chapter 9 describes the process of creating a new drawing document from a macroand how to create polar and rectangular arrays You’ll also see how to display text from
a macro, and how to format numbers, dates, and times
Chapter 10 introduces you to the many debugging features found in the IDE Ittalks about various kinds of errors you may encounter You’ll see how you can watchthe values of variables change as the code is executed
In Chapter 11, you’ll add a new group of menu commands to the AutoCAD windowand create toolbar buttons for quick access to these new commands
Chapter 12 discusses how to transfer data to and from files, and how to add aCommon Dialog control to display the Windows Open and Save As dialog boxes
Part 4: 2D Drawing Techniques
Part 4 discusses interactive drawing techniques using the snap and grid features You’llsee how to group objects and set group attributes
Chapter 13 discusses interactive drawing techniques for increased precision,including grid and snap It tells you how to create and manipulate a spline curve, andhow to animate the movement of a drawing object
Chapter 14 demonstrates the grouping of objects into layers or blocks so that theycan be handled as single entities It shows how to freeze and thaw layers and how tolock and unlock them
Trang 27INTRODUCTION xxvii
Part 5: 3D Drawing Techniques
Part 5 describes the creation and drawing of 3D solids and how to view them from ferent angles using the 3D Orbit control
dif-In Chapter 15, you’ll create a range of primitive solids and combine them usingunion, intersection, and subtraction operators You’ll also see how to create solids usingextrusion and revolution, how to remove hidden lines, and how render solids with fullcolor—from your VBA macro
In Chapter 16, you’ll explore the exchange of data among other Microsoft tions, using objects from Excel, Access, and Word as examples
applica-Chapter 17 discusses AutoCAD 2000i’s latest Internet features You’ll see how tolaunch your Web browser from code, validate URL addresses, and open and save draw-ings on the Internet You’ll use the Publish to Web Wizard that creates the HTML filesfor your very own Web pages You’ll also see how to add hyperlinks to a drawing
This book also features two bonus chapters (18 and 19) on the CD, which extendyour skills in several areas See “What’s On the CD” later in this Introduction
Appendix B lists all the ASCII symbols in a handy, one-stop reference table foryour convenience
AutoCAD Versions Compatible with This Book
Readers using AutoCAD 14, 2000, 2000i, and even future versions of the program willall benefit from this book It is written to be as universally applicable as possible, sincethe VBA concepts and language hardly change between versions of AutoCAD Eachnew release brings new objects providing additional functionality For the most part,
Trang 28the new releases are upward-compatible, in that any macros written for one versionwill normally run without problems on a later release So the code in the listingsthroughout this book and on the CD will likely be happy to run without problems forseveral years to come.
The screenshots throughout this book were taken using AutoCAD 2000i
Conventions Used in This Book
This book uses a number of conventions to present information in as readable a format
as possible Tips and Warnings appear from time to time to call attention to specialhighlights
Tips provide extra information that will be helpful in completing the task at hand.
Warnings alert you to situations where particular care must be taken to avoid problems.
This book takes advantage of several font styles and conventions used for the
pro-gramming code Bold font in text indicates something that you type at the keyboard A
monospaced fontis used for code listings and code snippets, for URLs, and for names In code lines, a continuation arrow (↵) indicates that the code line wraps down
file-to the next line due file-to space limitations of the book When a continuation arrow ispresent, you do not have to add a line break if you are typing the code yourself
Have fun unlocking the power of VBA!
What’s On the CD-ROM
The accompanying CD contains all the numbered code listings you’ll find throughoutthis book With the CD, you can quickly access the code without having to enter ityourself from scratch Just transfer the code to the Visual Basic Editor, and then youcan run the macros and try out any changes you wish to make
Trang 29Also on the CD is Adobe Acrobat Reader, for your convenience in easily accessingthe bonus chapters, which are in PDF format.
Bonus Chapters
The CD also includes two bonus chapters with additional exercises to build your2D and 3D drawing skills
Chapter 18: Once you’ve learned the basics of 2D drawing techniques, you can
build on these skills with the exercises in Chapter 18, which demonstrate how toplot a drawing using the Plot Table Wizard, and how to change a Paper Space view-port from a macro You can also build your VBA skills with the exercise on how tochange a Paper Space viewport from a macro
Chapter 19: Exercises in this chapter build on the 3D drawing skills developed
in Part 5 They cover rendering and lighting effects, including using macros toaccomplish hidden-line removal, shading, and rendering of 3D solids You’ll seehow to control the level of smoothness at which a surface is rendered, and how tochange the lighting—all from macros
Trang 33Chapter 1
Developing a Simple VBA Application
Trang 34I n this chapter, you will learn how to create a simple VBA
appli-cation through a series of tutorials You will learn how to employ visual tools to create the graphical user interface, and write code
to execute simple commands You will also explore the basics of the Visual Basic environment by using its features to create practical code that you can reuse for repetitive tasks.
If you consider yourself an intermediate user of AutoCAD VBA and have already written some successful VBA code, you may want to skip this chapter—or even just skim over the entire Part I, depending
on your experience The material covered in Chapter 4,“VBA gramming Concepts,” will always be useful to you as a reference This chapter covers the following topics:
Pro-• Advantages of using VBA with AutoCAD
• The AutoCAD VBA environment
• Developing your first application
Trang 35Advantages of Using VBA with AutoCAD
Visual Basic for Applications (VBA) is a programming environment created by
Microsoft that is built into applications to automate operations It provides tools thatyou can drag and drop to build a graphical user interface (GUI), and a programminglanguage that you can use to interact with AutoCAD objects Using VBA with Auto-CAD allows you to customize your AutoCAD application in seemingly unlimited ways
In this book, you’ll see how simple it is to automate repetitive tasks With the timesaved, you’ll be free to concentrate on applying your artistic talents and engineeringskills to make your drawings more intricate
Once you start writing VBA code, you’ll quickly realize just how easy it is to accessobjects from the AutoCAD and VBA object libraries You’ll soon be able to call on thepower of these objects while gaining a deeper insight into AutoCAD’s features As youstart to see the benefits that VBA macros and applications can provide, you’ll want tospend your extra time customizing even more tasks Before you know it, you’ll have awhole library of reusable macros and applications at your fingertips!
A macro is a group of code statements, usually not very long or complicated, that is useful in automating
a repetitive task In your work at the computer, most likely you’ve used them already without realizing it.
An application is a program that has been created to perform a specific task This can be something very simple, such as prompting the user for their name and password, or something very substantial and complex such as AutoCAD itself.
Another not-so-obvious advantage of learning AutoCAD VBA is that your skillsare transferable to a growing number of other applications that have VBA capability.These applications include all those in the Microsoft Office family of applications, such
as Access, Word, and Excel, in addition to Microsoft Visual Basic itself and about twohundred other licensees
VBA interfaces with applications by communicating and controlling objectsthrough the application’s object libraries, rather than by having any special connection
to the application’s inner workings All you need to know are the names of the objectsinvolved, and you can access their functionality with VBA code You’ll find the objectnames meaningful and easy to remember, such as ThisDrawing (an object in Auto-CAD), ThisDocument (an object in Word), and ThisWorkbook (an object in Excel) Asyou enter the names of objects in your code, the editing features of VBA’s Integrated
ADVANTAGES OF USING VBA WITH AUTOCAD 5
Trang 36Development Environment (IDE) offer you drop-down lists of elements particular tothe type of object you’ve entered You’ll see how this works in Chapter 2.
You can use a macro to automate just about anything, but it is probably most tive to start with the tasks you have to do time and time again Why not think about thoseboring, uninspiring jobs you hate doing the most, and start with them! These are probablytasks that are time consuming and error prone, so implementing them in macros or appli-cations will not only increase your productivity but lift your spirits by removing some ofthe tedious tasks that make you yawn just by thinking about them (Such as adding all therequired bits and pieces of information for starting a new drawing; or perhaps you’vefound that you regularly draw the same items over and over again.)
produc-After you’ve successfully developed VBA code that works in the ways you want it
to, it’s guaranteed to perform correctly and reliably each time you run it Now there’s an
incentive to learn VBA! So let’s begin by examining the interface where you will writeyour code—the Visual Basic Editor
The AutoCAD VBA Environment
The Visual Basic Editor is the integrated environment in which you develop all your
VBA code As you can see from Figure 1.1, the IDE has its own graphical user interface.Its windows provide all the tools required for creating, editing, debugging, and runningyour macros and applications With this much functionality, the IDE is almost a stand-alone application, except that it can only be opened from the AutoCAD window anddoes not remain open after AutoCAD has been closed
The term VBA Editor is often used synonymously with the IDE even though the IDE provides more than just editing features.
The VBA IDE can be opened from the AutoCAD window in a variety of ways:
• Type vbaide next to the command prompt in the command line.
• Choose Tools ➜ Macro ➜ Visual Basic Editor
• Use the key-combination (shortcut) Alt+F11
In the examples throughout this book, I’ve used menu commands in instructions.Most commands can also be accessed through a toolbar button or a key-combination, sooccasionally I give an alternative access method as a reminder that there are other ways toinvoke commands The access method you use is up to your personal preference
Trang 37Figure 1.1 AutoCAD’s VBA environment
Chapter 3 takes you on a guided tour of the IDE and discusses some of its features
in more detail
Creating UserForm Modules
A module is just a container for VBA code, and a UserForm module is a window (or
dia-log box) that can be considered a powerful extension to the AutoCAD GUI You decidewhat controls to place on your UserForm in order to perform the tasks required byyour application You can place labels and text boxes in which users can enter the infor-mation that your program needs in order to run You can use option buttons and checkboxes to give users the chance to select the items they require In fact, just about anycontrol you’ve seen in the applications running under Windows is available for use inthe VBA IDE
Adding a UserForm Module to Your Application
To add a UserForm module to your application:
1 Start AutoCAD and choose Tools ➜ Macro ➜ Visual Basic Editor The VBA
IDE opens
2 Choose Insert ➜ UserForm UserForm1 appears, containing a title bar with a
Close button, as shown in Figure 1.2
Project Explorer window
Standard toolbar Menu bar Title bar
Properties window
Code window
THE AUTOCAD VBA ENVIRONMENT 7
Trang 38Figure 1.2 A brand-new UserForm
A UserForm is the only module that can be viewed from the IDE in two different ways:
• Graphically, by choosing View ➜ Object to open up the UserForm window(see Figure 1.2)
• With code, by choosing View ➜ Code to open up the Code window as shown here:
Opening the Code window displays the event procedure that will run if the
User-Form is clicked There are many events to choose from, but double-clicking any controlautomatically displays the primary event that you’ll most likely want to respond to.You’ll see how to access the other events later in this chapter, in the section “CodingEvent Procedures.”
Puttering Around in the Toolbox
VBA provides a set of common controls in a Toolbox window (see Figure 1.3) You cansimply drag and drop individual controls onto a UserForm to develop GUI features foryour application
Trang 39Figure 1.3 Controls in the standard Toolbox
If the Toolbox isn’t on display, select the Toolbox command from the View menu
or click the Toolbox icon (shown in the margin) at the end of the Standard toolbar
Both of these actions will be available for selection only when a UserForm has beenadded to a project and it is being viewed in its graphical form rather than as a Codewindow To view a UserForm graphically, simply choose View ➜ Object
These controls are all available for you to drag and drop onto your UserForm,making AutoCAD VBA a powerful visual programming system that’s extremely effi-cient at quickly developing the GUI for a project—you can virtually design your wholeGUI using only the mouse!
You will recognize most of the controls in the Toolbox because you have alreadyexperienced using them in other applications Following are brief descriptions of whateach control does:
Select Objects The Select Objects control is used to resize and move a control
after it has been drawn on a UserForm If you’ve double-clicked another control toinsert multiple instances of it on the UserForm without returning to the Toolbox,you can click the Select Objects control to stop
Label The Label control displays text that you’ve assigned to its Caption property at
design time or in code A Label control is often used to display information or indicate
to a user what data should be entered into a TextBox control The text displayed by theLabel control is strictly read-only and cannot be changed by the user during run time
TextBox The TextBox control allows users to input textual information during
run time It is common practice to assign the empty string (””) to this control’sText property to initialize it or to clear out any data that’s no longer required
Select Objects TextBox ListBox OptionButton Frame TabStrip ScrollBar
CheckBox ComboBox Label
Image
CommandButton MultiPage SpinButton ToggleButton
THE AUTOCAD VBA ENVIRONMENT 9
Trang 40ComboBox The ComboBox control combines the functionality of the TextBox
control with that of the ListBox control to provide the user with the option of ing text into the TextBox, or clicking the down-arrow button and selecting an itemfrom a drop-down list When an item is selected from the list, it is automatically dis-played in the text box at the top of the ComboBox You can set the Style property ofthis control in order to restrict the user to selecting an item from the ListBox Thiseliminates the need to test whether the user has entered a valid value
enter-ListBox The enter-ListBox control enables the user to select one or more items from a list.
If there are too many items to be displayed at once, a scroll bar will automaticallyappear Even so, this control generally takes up more space than a ComboBox control,which needs only the same amount of space on the UserForm as a TextBox control
CheckBox The CheckBox control enables the user to “check” (select) zero or
more boxes from a group of CheckBoxes This control is often used to indicatewhether items are true or false, or to answer yes or no to questions CheckBoxes aresimilar in function to OptionButtons, except that they allow more than one item to
be selected at the same time
OptionButton OptionButton controls are used in groups of options to allow
selection of one option from the group When only one group of OptionButtons isrequired, it can be placed directly onto the UserForm When there is more thanone group, Frame controls (described just below) are used to separate groups, toenable one OptionButton per group to be selected You determine the Option-Button that will be the default selection If the user selects another OptionButtonfrom the same group, the old one is automatically deselected
ToggleButton The ToggleButton control toggles between on or off, true or false,
and yes or no When clicked, its appearance changes to match its value; it togglesbetween a raised button appearance (off) to a pushed-in appearance (on) The Pic-ture property of this control allows you to display a selection of options to the user
in a graphical way
Frame The Frame control allows a UserForm to be divided into areas where you
can group other controls, such as OptionButtons and CheckBoxes The Framecontrol and the controls inside it then behave collectively as a single entity Whenyou move the Frame, all the controls inside it move, too; when you disable theFrame, all its controls become disabled Frames are typically used to create groups
of OptionButtons on a UserForm, so that an option from each group can beselected rather than just a single option