• No results found

AutoCAD VBA Programming Tools and Techniques

N/A
N/A
Protected

Academic year: 2021

Share "AutoCAD VBA Programming Tools and Techniques"

Copied!
433
0
0

Loading.... (view fulltext now)

Full text

(1)

cover

next page >

title : author : publisher : isbn10 | asin : print isbn13 : ebook isbn13 : language : subject publication date : lcc : ddc : subject :

(2)

AutoCAD VBA Programming Tools and Techniques

John Gibb and Bill Kramer

(3)

< previous page

page_ii

next page >

Page ii

Disclaimer:

This netLibrary eBook does not include the ancillary media that was packaged with the original printed version of the book.

Published by Miller Freeman Books

55 Hawthorne, Suite 600, San Francisco, CA 94105

Copyright © 1999 by John Gibb and Bill Kramer. All rights reserved. No part of this book covered by copyrights hereon may be reproduced or copied in any manner whatsoever without written permission, except in the case of brief quotations embodied in articles and reviews. For information contact the publishers.

Distributed to the book trade in the U.S. and Canada by

Publishers Group West, 1700 Fourth Street, Berkeley, CA 94710 Cover Art: Robert Ward

Cover Design: The Visual Group

Interior Design and Composition: Brad Greene Library of Congress Cataloging-in-Publication Data Gibb, John W.

AutoCAD VBA programming: tools and techniques / by John Gibb and Bill Kramer. p. cm

ISBN 0-87930-574-6 (alk.paper)

1. Computer graphics. 2. AutoCAD. 3. Microsoft Visual Basic for applications. I. Kramer, Bill, 1958. II. Title

T385.G5217 1999

620'.0042'02855369dc21 99-43360

CIP Printed in the United States of America

99 00 01 02 03 04 5 4 3 2 1

(4)

Dedication

My Dad always taught me to look at things in a different way. That has helped me all through my programming career and as a consequence, I'd like to dedicate this work to his memory. I will always feel his presence. Bill Kramer

I wish to dedicate this book to the memory of my friend John Keith and my cousin Christopher Etheridge. Thanks to John for his humor and cre- ative talent and Christopher for his youthful enthusiasm. Both left us much too soon.

John Gibb

(5)

< previous page

page_iv

next page >

Page iv

Acknowledgments

I would like to thank my girlfriend Margaret, her sons Brian and Bob and my mother for their unwavering support despite my frequent lapses of memory during the writing of the book. Sometimes focus is good for writing but hard on the ones you love. Thanks for your patience.

I would also like to thank Application Developers, Andy Baron and Mike Gunderloy for the use of their command line material as the basis for the command line workaround material. A special thanks to Bob Verdun and my colleagues at CFI for their patience during the time it took to write this book.

2042015b45d2b5416108e486be44e8bc.

gif

JOHN GIBB

My heartfelt thanks go to my family and friends for continuing to put up with my eccentric hobbies and interests. Without their support I would not be able to do many of the things I enjoy doing including the writing of books and articles about computer programming. I'd also like to thank the readers of books like this since it is because of them I must learn more and am ever challenged to come up with new ideas. You all have no idea how much energy and contagious enthusiasm that provides!

2042015b45d2b5416108e486be44e8bc.

gif

BILL KRAMER

(6)

Preface

Search though you may, you won't find two more qualified people to co-author a book on VBA and AutoCAD than Bill Kramer and John Gibb. Both have written several books plumbing the depths of programming as a science and an art. Both have explored AutoCAD and AutoLISP since their inception and both are much sought-after programmer-consultants by a wide range of science and engineering firms.

When issue No. 1 of CADENCE was published in 1986, Bill Kramer launched a column titled ''AutoLISP Concepts," that over the years has transformed into his current "Programmer's Toolbox" and that stands as the longest running column in CADENCE's 14-year history. With the advent of VBA capabilities in AutoCAD Release 14, Kramer expanded his "how to" programming tutorials to include frequent explorations of the intricacies of Visual Basic for Applications. John Gibb, too, has been a frequent contributor to CADENCE and both have helped countless

programmers boost their knowledge of AutoCAD, AutoLISP and VBA through courses at Autodesk University, among other venues.

A graduate of Ohio State University's College of Engineering where he studied computer science and astronomy,

Kramer first "got into" computers with a DEC PDP-8 in 1975 teaching himself assembler code. He programmed his first microcomputer, a Z-80-based system with 32K RAM and two 160K disk drives, using BASIC and assembler languages. In 1985

(7)

< previous page

page_vi

next page >

Page vi

he launched Kramer Consulting and began developing applications for general CAD systems and AutoCAD in particular, including an NC programming system called NC-AUTO-CODE that he has supported ever since its first customer ship in 1986. Kramer has taught AutoCAD as an adjunct professor at Franklin University for several years and frequently offers sold-out classes in programming through Autodesk University.

As an Autodesk certified instructor, John Gibb has himself spent a fair amount of time sharing his vast programming knowledge with students at the Moraine Valley Autodesk Training Center. With a background in topology and utility mapping, space planning and facilities management systems, he has devoted 12 of his 15 years as a programmer to AutoCAD-related applications. An author of three books and numerous journal articles related to AutoCAD, Gibb is currently a senior applications developer with Computerized Facility Integration.

Gibb and Kramer share a keen ability to comprehend the black art of programming science and render it palatable. Both are noted for their sense of humor. But you can tell them apart in a crowd. Bill is the tall onea former basketball player and current eclipse chaser who almost doesn't need a telescope to practice his craft. John's the one with the pony tail. As a team, Gibb and Kramer bring unparalleled programming knowledge and experience to customizing AutoCAD with VBA. Updated to include capabilities introduced with AutoCAD 2000, this book is destined to become a de facto standard for AutoCAD programmers. Although aimed at those with advanced-intermediate and expert-level ability, there is much here as well for others who are new to programming science who would like to use VBA to maximize their AutoCAD productivity.

As authors, lecturers and consultants, Gibb and Kramer are best of class. They are also decent human beings. Read this bookyou won't be sorry you did. And when you attend the next Autodesk University, take a class with them, or just stop them in the hallway to chat. They'll love it and likely keep you just a bit longer than you may have planned. But when you're done, you'll be all the richer for it.

2042015b45d2b5416108e486be44e8bc.

gif

ARNIE WILLIAMS, EDITOR IN CHIEF,

CADENCE MAGAZINE

(8)

Table of Contents

Introduction xiii

Chapter 1

The AutoCAD VBA Environment

1

2042015b45d2b5416108e486be44e8bc. gif AutoCAD Programming Solutions

1

2042015b45d2b5416108e486be44e8bc. gif How AutoLISP Differs from VBA

3

2042015b45d2b5416108e486be44e8bc. gif Visual BASIC versus Visual BASIC for Applications

7

2042015b45d2b5416108e486be44e8bc. gif Essential VBA Vocabulary and Concepts

8

2042015b45d2b5416108e486be44e8bc. gif Getting Comfortable with the IDE

12

2042015b45d2b5416108e486be44e8bc. gif Starting the VBA IDE

13

2042015b45d2b5416108e486be44e8bc. gif What's in the IDE?

14

2042015b45d2b5416108e486be44e8bc. gif Developing Applications with VBA inside AutoCad

17

Chapter 2

VBA Application Jump-Start

20

2042015b45d2b5416108e486be44e8bc. gif Description of the Application

20

2042015b45d2b5416108e486be44e8bc. gif Start Your IDE

21

2042015b45d2b5416108e486be44e8bc. gif Design the Form

21

2042015b45d2b5416108e486be44e8bc. gif First Lines of Program Code

23

2042015b45d2b5416108e486be44e8bc. gif Form Properties

(9)

2042015b45d2b5416108e486be44e8bc. gif Add a List Box Control

25

2042015b45d2b5416108e486be44e8bc. gif Programming the Starting Sequence

26

2042015b45d2b5416108e486be44e8bc. gif Global Variable Declarations

27

2042015b45d2b5416108e486be44e8bc. gif Counting Blocks Macro

28

2042015b45d2b5416108e486be44e8bc. gif Test Run the Main Macro

33

2042015b45d2b5416108e486be44e8bc. gif List Box Reactor Function

34

2042015b45d2b5416108e486be44e8bc. gif Test the Program

37

2042015b45d2b5416108e486be44e8bc. gif Final Test

38

Chapter 3

Understanding the AutoCAD Object-Oriented Database

39

2042015b45d2b5416108e486be44e8bc. gif Object-Oriented Programming Introduction

39

2042015b45d2b5416108e486be44e8bc. gif What's an Object?

41

2042015b45d2b5416108e486be44e8bc. gif The Management Features of Objects

42

2042015b45d2b5416108e486be44e8bc. gif Object Concept Example

43

2042015b45d2b5416108e486be44e8bc. gif Computer Science Description of Objects

46

2042015b45d2b5416108e486be44e8bc. gif How Objects Are Stored in a Computer

47

2042015b45d2b5416108e486be44e8bc. gif About Creating New Objects

49

2042015b45d2b5416108e486be44e8bc. gif The AutoCAD Object Tree

(10)

gif The Block Collection Object

2042015b45d2b5416108e486be44e8bc. gif Entity Objects

54

2042015b45d2b5416108e486be44e8bc. gif Learning about Objects in VBA

56

(11)

< previous page

page_viii

next page >

Page viii

Chapter 4

The AutoCAD Object Model

59

2042015b45d2b5416108e486be44e8bc. gif Methods, Properties, and Events

59

2042015b45d2b5416108e486be44e8bc. gif Exploration of the AutoCAD Object Tree

60

2042015b45d2b5416108e486be44e8bc. gif Getting to the Application Object

61

2042015b45d2b5416108e486be44e8bc. gif The Application Object

62

2042015b45d2b5416108e486be44e8bc. gif Accessing the Document Object in VB

66

2042015b45d2b5416108e486be44e8bc. gif The Documents Collection

67

2042015b45d2b5416108e486be44e8bc. gif Document Object Methods

70

2042015b45d2b5416108e486be44e8bc. gif Document Object Properties

71

2042015b45d2b5416108e486be44e8bc. gif Document Object Events

74

2042015b45d2b5416108e486be44e8bc. gif Event Programming Example

77

2042015b45d2b5416108e486be44e8bc. gif Utility Object Functions

78

2042015b45d2b5416108e486be44e8bc. gif Collections of Objects

83

2042015b45d2b5416108e486be44e8bc. gif Entity Objects

85

2042015b45d2b5416108e486be44e8bc. gif Curved Entity Objects

89

2042015b45d2b5416108e486be44e8bc. gif Text Entity Objects

(12)

Working with Entity Collection Objects

2042015b45d2b5416108e486be44e8bc. gif The Collection Object

102

2042015b45d2b5416108e486be44e8bc. gif Selection Sets Collection

103

2042015b45d2b5416108e486be44e8bc. gif Building a Collection of Entity Objects

104

2042015b45d2b5416108e486be44e8bc. gif Accessing Selection Set Members

106

2042015b45d2b5416108e486be44e8bc. gif More Selection Set Methods and Properties

107

2042015b45d2b5416108e486be44e8bc. gif Selection Set Collection Iterations

108

2042015b45d2b5416108e486be44e8bc. gif ModelSpace and PaperSpace Collections

111

2042015b45d2b5416108e486be44e8bc. gif Even More Selection Set Methods

112

2042015b45d2b5416108e486be44e8bc. gif Filtering the Selection Set

117

2042015b45d2b5416108e486be44e8bc. gif Refining the Filters Numeric Tests

120

2042015b45d2b5416108e486be44e8bc. gif String Tests in Filters

123

2042015b45d2b5416108e486be44e8bc. gif Combining Multiple Tests

124

2042015b45d2b5416108e486be44e8bc. gif Selection Set Maintenance Issues

128

2042015b45d2b5416108e486be44e8bc. gif Working with Collections

130

Chapter 6 Drawing Tables

131

2042015b45d2b5416108e486be44e8bc. gif AutoCAD Drawing Tables

(13)

2042015b45d2b5416108e486be44e8bc. gif Tables Are Collections

132

2042015b45d2b5416108e486be44e8bc. gif The Dictionary Collection

133

(14)

2042015b45d2b5416108e486be44e8bc. gif The DimStyles Collection

134

2042015b45d2b5416108e486be44e8bc. gif The Groups Collection

136

2042015b45d2b5416108e486be44e8bc. gif Groups versus Dictionaries

138

2042015b45d2b5416108e486be44e8bc. gif The Layer Collection

139

2042015b45d2b5416108e486be44e8bc. gif The Linetypes Collection

142

2042015b45d2b5416108e486be44e8bc. gif The Registered Apps Collection

143

2042015b45d2b5416108e486be44e8bc. gif The Text Styles Collection

143

2042015b45d2b5416108e486be44e8bc. gif The UCS Collection

145

2042015b45d2b5416108e486be44e8bc. gif The Views Collection

147

2042015b45d2b5416108e486be44e8bc. gif The View Ports Collection

148

2042015b45d2b5416108e486be44e8bc. gif View Port Object

150

2042015b45d2b5416108e486be44e8bc. gif The Paper Space View Port Object

152

2042015b45d2b5416108e486be44e8bc. gif The Blocks Collection

154

2042015b45d2b5416108e486be44e8bc. gif Creating a New Block Definition

155

2042015b45d2b5416108e486be44e8bc. gif Reading a Block Definition

156

2042015b45d2b5416108e486be44e8bc. gif Working with Attribute Objects in a Block

162

Chapter 7

Working with Other Applications

(15)

2042015b45d2b5416108e486be44e8bc. gif Object Models

167

2042015b45d2b5416108e486be44e8bc. gif Interface to Microsoft Excel

169

2042015b45d2b5416108e486be44e8bc. gif Excel Application 1Simple Database

170

2042015b45d2b5416108e486be44e8bc. gif Link to Excel

171

2042015b45d2b5416108e486be44e8bc. gif Variable Declarations

172

2042015b45d2b5416108e486be44e8bc. gif Excel Linkage Function

173

2042015b45d2b5416108e486be44e8bc. gif Closing the Workbook

175

2042015b45d2b5416108e486be44e8bc. gif Searching the Worksheet

176

2042015b45d2b5416108e486be44e8bc. gif Another Example Interface to Microsoft Excel

179

2042015b45d2b5416108e486be44e8bc. gif Using Handles

184

2042015b45d2b5416108e486be44e8bc. gif Object ID versus Handle

186

2042015b45d2b5416108e486be44e8bc. gif Linking with Other Applications

187

2042015b45d2b5416108e486be44e8bc. gif Storing Data in AutoCAD

188

2042015b45d2b5416108e486be44e8bc. gif Dictionary Object

188

2042015b45d2b5416108e486be44e8bc. gif Xrecord Objects

189

2042015b45d2b5416108e486be44e8bc. gif Accessing a Dictionary

189

2042015b45d2b5416108e486be44e8bc. gif Xrecord Contents

(16)

gif Extended Data

2042015b45d2b5416108e486be44e8bc. gif Simple Xdata Example

196

(17)

< previous page

page_x

next page >

Page x

Chapter 8

Managing Multiple Projects

201

2042015b45d2b5416108e486be44e8bc. gif Putting Complete Applications Together

201

2042015b45d2b5416108e486be44e8bc. gif Loading Projects to Run

204

2042015b45d2b5416108e486be44e8bc. gif Embedded Projects

205

2042015b45d2b5416108e486be44e8bc. gif Projects on Disk

205

2042015b45d2b5416108e486be44e8bc. gif Re-Using Code

207

2042015b45d2b5416108e486be44e8bc. gif Running a Macro from Another Project

208

2042015b45d2b5416108e486be44e8bc. gif Sharing Data between Projects

210

2042015b45d2b5416108e486be44e8bc. gif Late and Early Binding in VBA

211

2042015b45d2b5416108e486be44e8bc. gif Multiple Projects in Release 14

212

Chapter 9

API Calls from VBA

214

2042015b45d2b5416108e486be44e8bc. gif What's an API?

214

2042015b45d2b5416108e486be44e8bc. gif The API Viewer

216

2042015b45d2b5416108e486be44e8bc. gif INI File Calls

217

2042015b45d2b5416108e486be44e8bc. gif How the PrivateProfileString APIs Work

218

2042015b45d2b5416108e486be44e8bc. gif Registry Calls

(18)

gif System Calls

2042015b45d2b5416108e486be44e8bc. gif Computer Name

232

2042015b45d2b5416108e486be44e8bc. gif User's Login Name

232

2042015b45d2b5416108e486be44e8bc. gif System and Local Time

233

2042015b45d2b5416108e486be44e8bc. gif The Windows Temporary Directory

234

2042015b45d2b5416108e486be44e8bc. gif System Environmental Variable

234

2042015b45d2b5416108e486be44e8bc. gif Free Disk Space

235

2042015b45d2b5416108e486be44e8bc. gif Conclusion

236

Chapter 10

VBA Toolbox Routines

237

2042015b45d2b5416108e486be44e8bc. gif Definition of Terms

238

2042015b45d2b5416108e486be44e8bc. gif Toolbox Overview

238

2042015b45d2b5416108e486be44e8bc. gif Acquiring Data Items from a Data String

239

2042015b45d2b5416108e486be44e8bc. gif Add Back Slashes Result to a Path String

240

2042015b45d2b5416108e486be44e8bc. gif Add Trailing Back Slash to a String Path

241

2042015b45d2b5416108e486be44e8bc. gif Convert an Object's Entity Type to English

242

2042015b45d2b5416108e486be44e8bc.

gif Count the Number of Occurrences of a Delimiter in a String

243

2042015b45d2b5416108e486be44e8bc. gif Create a Directory Path

(19)

2042015b45d2b5416108e486be44e8bc. gif Determine the Tense of a Word

245

2042015b45d2b5416108e486be44e8bc. gif Display a Fatal Error Message

246

(20)

2042015b45d2b5416108e486be44e8bc. gif Find a File

247

2042015b45d2b5416108e486be44e8bc. gif Find a Line in a List Box Control

248

2042015b45d2b5416108e486be44e8bc. gif Find an Application Window

249

2042015b45d2b5416108e486be44e8bc. gif Format a Point in a String

250

2042015b45d2b5416108e486be44e8bc. gif Get the Current View's Corner Points

251

2042015b45d2b5416108e486be44e8bc. gif Get the Extension from a String

252

2042015b45d2b5416108e486be44e8bc. gif Get the Left Substring from a String

253

2042015b45d2b5416108e486be44e8bc. gif Get the Path from a String

254

2042015b45d2b5416108e486be44e8bc. gif Get the Right Substring from a String

255

2042015b45d2b5416108e486be44e8bc. gif Pad a String with Spaces

256

2042015b45d2b5416108e486be44e8bc. gif Remove a String's Null Terminator

257

2042015b45d2b5416108e486be44e8bc.

gif Replace All Requested Characters in a String with Another Character

258

2042015b45d2b5416108e486be44e8bc. gif Retrieve the System's Windows Directory

259

2042015b45d2b5416108e486be44e8bc. gif Show a Progress Spinner

260

2042015b45d2b5416108e486be44e8bc. gif Strip an Extension from a String

262

2042015b45d2b5416108e486be44e8bc. gif Strip the Path from a String

263

2042015b45d2b5416108e486be44e8bc. gif Verify a Control Exists on a Form

(21)

2042015b45d2b5416108e486be44e8bc. gif Verify a File's Existence

265

2042015b45d2b5416108e486be44e8bc. gif Verify a Listbox Item Exists

266

Chapter 11 VB versus VBA

267

2042015b45d2b5416108e486be44e8bc. gif Quick Comparison of VB and VBA

268

2042015b45d2b5416108e486be44e8bc. gif Which Language for Which Situation?

272

2042015b45d2b5416108e486be44e8bc. gif Differences at the System Level

273

2042015b45d2b5416108e486be44e8bc. gif Porting Issues from VB to VBA

273

2042015b45d2b5416108e486be44e8bc. gif Porting Issues from VBA to VB

274

2042015b45d2b5416108e486be44e8bc.

gif Attaching Your VB Application to the AutoCAD Object Model

274

2042015b45d2b5416108e486be44e8bc. gif VB and VBA Help

276

2042015b45d2b5416108e486be44e8bc. gif VB and VBA Help Conclusion

287

Chapter 12 Gotcha's and Tips

288

2042015b45d2b5416108e486be44e8bc. gif Divergent Data Type Comparison

289

2042015b45d2b5416108e486be44e8bc. gif Using Control Keys to Maneuver in VBA

291

2042015b45d2b5416108e486be44e8bc. gif Class Modules in VBA

293

2042015b45d2b5416108e486be44e8bc. gif The Special Character for Date and Format

295

2042015b45d2b5416108e486be44e8bc. gif Named and Optional Arguments

(22)

gif Collections and Procedures

(23)

< previous page

page_xii

next page >

Page xii

2042015b45d2b5416108e486be44e8bc. gif Short Circuit Evaluation

302

2042015b45d2b5416108e486be44e8bc.

gif Accessing Objects on the Same Level as Your Current Object

303

2042015b45d2b5416108e486be44e8bc. gif Listbox Columns

305

2042015b45d2b5416108e486be44e8bc. gif Multiselect in a Listbox

308

2042015b45d2b5416108e486be44e8bc. gif Variable Name Shortcuts

309

2042015b45d2b5416108e486be44e8bc. gif Command Line Workaround

309

2042015b45d2b5416108e486be44e8bc. gif Passing Forms and Controls as Parameters

311

2042015b45d2b5416108e486be44e8bc. gif Multipage Form Controls

312 2042015b45d2b5416108e486be44e8bc. gif Conclusion 312 Chapter 13 Programming Style 313 2042015b45d2b5416108e486be44e8bc. gif Commenting Your Code

314

2042015b45d2b5416108e486be44e8bc. gif Keeping Code Concise and Simple

316

2042015b45d2b5416108e486be44e8bc. gif Proper Use of Subroutines and Functions

318

2042015b45d2b5416108e486be44e8bc. gif Scope, Precedence, and Life of Variables

319

2042015b45d2b5416108e486be44e8bc. gif Error Trapping

322

2042015b45d2b5416108e486be44e8bc.

gif Do You Need to Change Your Programming Style for VBA?

(24)

gif Conclusion

Chapter 14

Class Modules and Objects

331

2042015b45d2b5416108e486be44e8bc. gif Not All Objects Are Equal

331

2042015b45d2b5416108e486be44e8bc. gif The VBA Class Module

332

2042015b45d2b5416108e486be44e8bc. gif Objects Example 1: Extended Data Manipulations

334

2042015b45d2b5416108e486be44e8bc. gif Making a Class Module

335 2042015b45d2b5416108e486be44e8bc. gif Properties 337 2042015b45d2b5416108e486be44e8bc. gif Methods 341 2042015b45d2b5416108e486be44e8bc. gif The Extended Data Example Project

345

2042015b45d2b5416108e486be44e8bc. gif Extended Data Object Conclusion

348

2042015b45d2b5416108e486be44e8bc. gif Objects Example 2: Hole Chart

349

2042015b45d2b5416108e486be44e8bc. gif An Object in an Object

350

2042015b45d2b5416108e486be44e8bc. gif The Inner Object

352

2042015b45d2b5416108e486be44e8bc. gif The Hole Charting Example Project

355

2042015b45d2b5416108e486be44e8bc. gif Hole Chart Application Conclusion

357

2042015b45d2b5416108e486be44e8bc. gif Creating Your Own Object

357

(25)

< previous page

page_xiii

next page >

Page xiii

Introduction

Why another book about VBA? John and I first started talking about writing a book together some time ago. As programmers and teachers of others how to program, we found that we had many similar experiences. One of which is that you can never have enough examples of how to do various things. Both of us used books written by others as well as ourselves as sources for examples in both writing new code as well as teaching others to program. Another thing we felt that many books provided was a variable perspective on how to get the job done. That is, different ways to think about how to solve problems with programs and obtain improved productivity.

And while we were discussing the merits of books and the logistics of writing one together, an opportunity was presented by Miller Freeman Inc to author one about VBA Visual Basic for Applications. Both of us had extensive experience in BASIC and programming in general thus we thought it would be fun to put one together. We were right. It was fun and we both learned a lot from each other along the way. And to increase the amount of pleasure, we switched systems along the way. We started working with VBA in AutoCAD Release 14 and ended up in AutoCAD 2000 by the time we finished. The book is written for both versions however there are features in the newer AutoCAD VBA that will not

(26)

work in the earlier one. We tried to point those out when we reworked the chapters after getting the newer AutoCAD release.

Writing a book about a subject as broad as VBA means that we jumped around a little here and there between chapters. We tried to build on knowledge learned from earlier chapters as the book progresses but at times it may seem like we shifted subjects in an extreme manner. That was so we could fill in more of the foundation of knowledge needed for the next step. The following paragraphs demonstrate this fact as they briefly explain the chapters in the book.

In chapter 1, we start with a basic introduction of what VBA is and how it fits into AutoCAD. Because many readers of this book are new to VBA, we wanted to get the terms defined that make up the ''VBA Talk". We also wanted to help clarify the differences between VBA, AutoLISP, and Visual BASIC from Microsoft.

Chapter 2 jumps feet first into a simple project. This chapter was intended for those readers who prefer to take a look around the software first and then learn more about the details. The VBA environment is explored in a hands-on fashion to provide a feel for what it is like to write programs using this tool.

From our experiences in teaching VBA, both of us have learned that it is important to understand what objects are all about and how they relate to programming. Although simple in concept, object-oriented-programming is a new notion to many just learning VBA and other newer programming systems. In chapter 3 we introduce objects and how the AutoCAD object database is connected together. This chapter serves as a foundation for further details into the objects VBA programmers manipulate.

Chapter 4 drills into the AutoCAD object looking at the way everything is connected and introducing the main features found in the model. In chapter 5 we take a detailed look at manipulating collections of objects such as selection sets or groups of entities in a drawing. Chapter 6 explores the tables found in the drawing such as layers, line types,

dictionaries, and so forth. These chapters combine to provide a look at

(27)

< previous page

page_xv

next page >

Page xv

the entire AutoCAD VBA object system and how you work with it from a general point view.

Many books about VBA finish after explaining the object model, but since this book is focused towards AutoCAD application developers we wanted to go further into some of the areas students have wanted to see.

In chapter 7 there is a discussion about how to interface with other automation servers such as Microsoft Excel.

Examples are provided that show how easy it is to interface with these other tools in the computer system. We also look at extended data and how one can use that feature of AutoCAD's customization to yield tremendous benefits.

Project management for programming is important and chapter 8 provides information about how to work with more than one project at a time to save time in the development effort. And while on the subject of saving time, chapter 9 shows how to make use of the tools provided in the Windows environment itself. Virtually all of the time saving, operator friendly, aspects of Windows of that you want to use are available through the Windows API library. The only problem is that you have to find them and this chapter shows you how to do just that.

A list of samples, examples, and useful utilities is found in chapter 10 where John provides a long list of routines from his personal toolbox. John's earlier books on AutoLISP contained many of these utilities and he translated them to VBA making them available with this work.

In chapter 11 we took a more serious look at VB versus VBA. They are not the same, but they share a lot of the same attributes. For programmers looking to export their knowledge of VBA to VB this chapter serves as a guiding light to what can be done. At the same time, those programmers experienced with VB but wanting to learn about VBA will find useful information in this chapter as well. And as long as we are talking about experienced, we chose to share some of our experiences in chapter 12 where we investigate several possible pitfalls and provide tips we have learned along our journey. That leads into chapter 13 with a discussion of programming style to make your programs easier to read and work with in the future.

(28)

In the last chapter we look at creating your own objects through two examples. Most beginner VBA programmers do not venture this far and that's why we saved it for the last chapter. If you are serious about doing wonderful things with AutoCAD VBA, then defining your own objects is a very powerful tool to use. And the best way to explain it is to show two useful examples.

You should not think of this book as your only reference for VBA, there is an extensive help library included in the system. This book will help you understand that help library even better by having a strong foundation of VBA know-how behind you. In addition, the attached CD has more examples and even more information about other aspects of the AutoCAD system such as plotting.

We hope you are able to learn about VBA and enjoy it as much as we do through this book. The fun of getting the computer to do something special that you programmed is tremendous. It is also contagious as you learn new tricks and tidbits along the way. Keep on programmin'!

2042015b45d2b5416108e486be44e8bc.

gif

BILL KRAMER AND JOHN GIBB, NOVEMBER 1999

(29)

< previous page

page_1

next page >

Page 1

Chapter One

The AutoCAD VBA Environment

Intended for programmers new to Visual BASIC for Applications (VBA), this chapter explores how VBA relates to other programming solutions inside AutoCAD. We will present a comparison of VBA, Visual LISP, and AutoLISP for readers familiar with the AutoLISP language and associated methods of AutoCAD customization. We will also

introduce the various components of the VBA programming environment and give an explanation of how to start VBA inside AutoCAD.

AutoCAD Programming Solutions

AutoCAD is one of the most open architecture-designed CAD/CAE/CAM systems with a large variety of programming options on the market. The base AutoCAD package (not AutoCAD LT, but regular AutoCAD) comes with five

interpretive programming languages that can be used to customize the system. There are also libraries for use with other programming systems that will create new objects and interfaces with the system.

The five programming languages found inside AutoCAD are as follows:

a script file option containing AutoCAD commands that are played into AutoCAD in the order typed in the file;

(30)

a menu programming system that allows users to select commands with optional user input. a menu statement language containing variables and elementary logic called DIESEL. a complete language system based on the LISP language;

a complete language system that is an implementation of the BASIC language.

All of these programming options are provided with the standard AutoCAD package. They are not all provided with AutoCAD LTonly scripts, menus, and DIESEL can be found in that environment.

The LISP-based language called AutoLISP (and Visual LISP) allows you to develop new commands that you can easily integrate into menus. This permits the operator to incorporate advanced program logic of his or her own design into the custom menu system. The operator may also enter these new commands at the command line. AutoLISP has been available to AutoCAD developers for a number of years and contains multiple options for accomplishing the various tasks involved. Input options for AutoLISP include the command line as well as a dialog boxbased interface. The dialog box interface must be programmed in a separate text file called a Dialog Control Language (DCL) file. The DCL file structure is simple to work with and does not provide as complete control over the dialog box layout as found in the Visual Developer Environments from Microsoft and other developers.

AutoCAD 2000 enhances AutoLISP considerably in the form of Visual LISP. Visual LISP provides greatly enhanced routines for accessing the drawing system. It also provides a vehicle for distributing applications in a compiled format that runs up to four times faster than AutoLISP. There are some differences between AutoLISP and Visual LISP in regards to ActiveX support and other systems related features, but for the most part if you know AutoLISP, you know Visual LISP. The ''Visual" part comes from the full-screen text editor provided with Visual LISP that makes

programming in AutoLISP much easier. Visual LISP is a significant

(31)

< previous page

page_3

next page >

Page 3

improvement over AutoLISP and brings more power to that language than ever before.

The BASIC language system found inside AutoCAD is Visual BASIC for Applications. VBA is provided through a cooperation between Autodesk and Microsoft: it's a Microsoft product that Autodesk has licensed for use. The reasons for this generous gesture on Autodesk's behalf is that Visual BASIC is a very popular programming language and it better provides for an integrated programming environment. Of course, Microsoft is also quite interested in this venture as well since Microsoft makes the easiest to integrate tasks for VBA to work with. Developers and users of AutoCAD will find that this joint development tool represents a powerful feature for the creation of enhanced productivity utilities. VBA is a superior development tool for creating dialog boxbased interfaces. The Visual Development Environment is very flexible and provides the type of tools needed to create good-looking applications. There are several other features, covered later in this chapter that make it a powerful choice for developers.

How AutoLISP Differs from VBA

The primary difference, other than language structure, between AutoLISP (including Visual LISP) and the VBA language option is that AutoLISP runs from the command line or menu system. Solutions based on VBA are more interactive in nature and make extensive use of dialog boxes. Even though AutoLISP is capable of working with dialog boxes, VBA is far superior in that regard. Using the dialog box editor, you can quickly design new dialogs. The code window is just a click away from the dialog box editor window, so you can develop user interfaces quickly. Lastly, the controls or dialog box components found in VBA are better than those found in the AutoLISP DCL. Each of these components (controls in VBA terms) has many properties that the programmer can control during both run and design time. Programmers who use Visual BASIC will be able to build dialog-based interfaces significantly faster and better than those who build with AutoLISP.

(32)

Another primary difference between the two languages has to do with how they interface with other programs in a computer. VBA is simply much better at talking to other Windows programs than AutoLISP. Through a standardized process-to-process communications system, VBA is able to initiate other programs, control the programs, and pass data back and forth. Of course, the other programs must be able to respond to the requests from VBA, and not all Windows-based programs are capable of this task. To find out if a particular program can be interfaced through VBA, check for VBA automation support or ActiveX support in the product description. All of the Microsoft Office 97 products respond very well to VBA automation. Visual LISP supports ActiveX type interfacing as well, but not as elegantly as VBA automation and certainly not as well documented as in many references. You can learn more about ActiveX and how to use it to control word processing as well as spreadsheet applications in other texts. Some examples of interfaces to other programs are presented in later sections and on the associated media of this book.

It is important to note that you can expand AutoLISP through the ObjectARX (AutoCAD Runtime eXtension) to provide interfaces to other Windows programs. However, this involves using compilers and other system development tools that are not provided with AutoCAD. This sort of expansion is more for advanced programmers who are

comfortable working with more than one computer language at a time. It is not recommended for developers who want to get the job done quickly so they can return to the design work that creates real income. In addition, more coding may be required to make the interfaces work. And this involves not only more time, but more effort on behalf of the

programmer. On the plus side, expanding AutoLISP in this manner does open the door to working with products that do not directly support VBA automation but offer some other interface options.

VBA provides a fast, easy-to-program solution for interfacing AutoCAD with other programs such as the Microsoft Office 97 productivity suite. From these you can integrate a word processor, spreadsheet system, or database directly with the AutoCAD drawing. And you do not

(33)

< previous page

page_5

next page >

Page 5

need to purchase any additional compilers to get the job done: VBA is more than capable of working with these other packages. You just have to spend the time to program it the way you want it.

Another area where VBA is different from AutoLISP is in file handling. VBA provides a greater array of options for reading and writing data files. VBA's file input and output options include sequential text, random access records, and binary data. Through interfaces to Access 97 it can work with a variety of database structures. AutoLISP works with sequential text files, and through a library of functions it can also work with a variety of database systems. Thus VBA provides more options for file accessing, which can be an important aspect in building integrated applications from tasks that have traditionally been independent. An example would be a coordinate geometry system that stores data about points in a direct access binary data file. AutoLISP would have a difficult time (except through ObjectARX expansion) working with this data, while there is a chance that VBA could read and work with the numeric data stored in the file.

AutoLISP and VBA programming styles differ greatly when it comes to object manipulation and creation. VBA programs use functions that are related to the entity object definitions in order to perform the edit operations on a particular entity. AutoLISP can either use the command system of AutoCAD or directly change the data found in the entity objects based on programmatic control. Visual LISP provides a library of functions that also access the objects in the same manner as VBA through the ObjectARX interface. VBA also provides a pipeline to the command processor of AutoCADhowever, there are some good reasons not to use it.

It's a good idea to avoid using AutoCAD's COMMAND system for manipulating objects in the drawing. The simple reason is speed of execution and application control. A classic example of the speed is found in the Explode function that is associated with the block reference and other complex objects. Instead of using the EXPLODE command in AutoCAD to explode a block insert, VBA would first get the block

(34)

ence object and then run the associated Explode function. This executes significantly faster than sending the object entity name to the command processor following the EXPLODE command. AutoCAD must first interpret the command name just sent, then check the object to make sure it is of the correct type to explode, and then call the same function being called when the Explode method is called for the object.

Using methods instead of commands may sound complicated at first, but it really isn't when applied in a programming context. Both VBA and AutoLISP applications programmers must decide whether to use the familiar COMMAND-based sequences or to gain the speed to execution by accessing the objects directly.

We have presented a comparison table of VBA and AutoLISP data types below. As seen in the table there are numerous data types in VBA that are not supported in AutoLISP. At the same time, there are several AutoLISP data types specific to AutoCAD entity handling that are handled as objects and collections of objects in the VBA environment. It is through this use of objects that VBA is different from AutoLISP when working with AutoCAD data. All other data manipulation in AutoLISP is supported in VBA, plus a lot more. VBA is better suited to data processing applications than AutoLISP as a result of this expanded data type support.

While AutoLISP provides a data type specific to working with the AutoCAD database such as entity names and pick sets, VBA works through the object system. Objects in AutoCAD are exposed to VBA, and that makes their properties and methods available for manipulation. This calls for some different thinking when it comes to working with

AutoCAD customization in VBA as compared with AutoLISP. Again, it cannot be stressed enough: although VBA is a powerful tool in the customization of AutoCAD, it is not always going to be the best solution. Sometimes just a simple menu macro can be more productive to an operator than a fancy dialog boxbased application. It is always important to maintain the perspective of the operator when writing software that customizes a package such as AutoCAD.

(35)

< previous page page_7 next page >

Page 7

Table 1.1: Comparison of data types between AutoLISP and VBA

Data type AutoLISP VBA

Boolean Nil or non-nil binding Boolean 1 byte binary data

2 byte integer Integer Integer

4 byte integer None Long integer

4 byte floating point None Single precision real

8 byte floating point Real Double precision real

Currency, money counting None Currency

Date and Time Julian days as real numbers Date/Time 8 byte value

String of characters String String

Entity name Ename data type Object

Selection set Pickset data type Collection

List List Array, Collection, Object

Point List List Array of real numbers

Visual BASIC versus Visual BASIC for Applications

Just what are the differences between Visual BASIC and Visual BASIC for Applications? For the most part, not too many. If you already know VB, then working with VBA is easy with just a few adjustments. For now, the important difference to keep in mind is that VBA runs inside AutoCAD while VB runs outside AutoCAD. This means they communicate with the AutoCAD system in different waysand more importantly for many programmers, at different speeds. VBA is faster than VB when it comes to manipulating entities inside AutoCAD.

So does that mean you should not consider purchasing Visual BASIC? The answer to that question is really up to you and where you plan to go with the language.

(36)

If you intend to use VBA as a primary development engine, then we highly recommend purchasing one of the Visual BASIC editions. When you install any of the Visual BASIC editions (Standard or Professional), you get more controls available to your applications development. In addition, the programming talents learned from VBA can be applied in Visual BASIC to develop applications completely outside of AutoCAD to solve other design and engineering problems. On the other hand, if your intent is to use VBA only when it is the ''best" solution to the problem at hand, then

purchasing Visual BASIC is not really called for. Perhaps the only exception would be to gain the use of a control that is not provided in VBA such as the communications module opening the door to RS-232 serial communications via a modem. This control is provided in the Professional edition of Visual BASIC and is not found in the VBA environment. Of course, not everyone will need that control, either!

Chapter 11 is devoted to the subject as well as the issues involved in porting applications from one environment to the other. VBA and VB are not identical in the way they work. For instance, they have different approaches to starting a form due in part to the fact that they use different forms development and management systems.

Essential VBA Vocabulary and Concepts

As with any computer language system, the VBA environment has unique terminology. These terms will be used freely throughout this book. Thus, if you are new to the visual development environment or new to Visual BASIC, you will need to become familiar with these terms.

These first terms relate to general Windows programming. They are used frequently to describe how something takes place in the computer environment or how a program can talk to some other program.

Windows: The rectangular areas on the display where you communicate with the user. Each window will have an ID

that identifies it to the system, and it is through that ID that you talk to a specific Windows

(37)

< previous page

page_9

next page >

Page 9

task. AutoCAD typically has two windows: the graphics window and the text window. If you run more than one copy of AutoCAD at a time, then there may be more than the two windows in the system. Note that VBA talks only to the first one found, and this can be a problem when you open multiple windows of AutoCAD at once.

Events: The variable processes that take place as the computer runs. Events include actions such as keyboard input,

mouse clicks, interface requests, process messages, and so forth. Anything that can happen in the computer is essentially an event. Most of the programming done in VBA is in response to events that the user initiates. When the user clicks the mouse while it is pointing to a button in one of your programs, an event-related task of your design is started. You program just what this event does, and it is through a series of event handling tasks that an application is created. Programs can cause events to happen that make other programs respond in some way. These messaging events are how VBA communicates with other programs, including AutoCAD.

Messages: When an event occurs, messages are used to relay information about the event to the various processes that

might be interested. Most incoming messages relate to the operating system such as the changing of a window's disposition. Depending on the application, user-initiated and system-initiated messages may be the only messages a program needs to handle. Other messages are from one program to another. For most applications you will write, these messages are outgoing, as your program is making a request of another program to do something. Messages are

typically in the form of code numbers. About the only exceptions occur when user input is involved and strings are passed as part of the message. As such, message transmission tends to be quick in the computer and is not as encumbering as it may sound.

IDE: This stands for the Integrated Development Environment and is used to reference the editor, project explorer,

object browser, properties window, and other programmer information windows. The IDE is a rendition of the Microsoft Developer Studio that is used for other language

(38)

systems such as C++ and FORTRAN. If you already program in the studio environment then you already are familiar with many of the windows in the IDE.

The next few terms relate to the VBA IDE.

Forms: The windows designed by your programming efforts are forms, and you will use the form editor to develop the

appearance of your forms. For the majority of VBA applications there will be a primary form that the user will interface with by selecting button options and other items. Applications can have multiple forms or multiple dialog boxes, and your program controls which ones are active or visible at any given time.

Controls: The individual items in a dialog box are called controls. There are several types of controls available in VBA,

including buttons, text displays, icon or bitmap buttons, lists, pop-up lists, and so forth. All the most common items found in a dialog box are available to VBA developers. When you are in the form editor, the control toolbox should be visible. This toolbox contains buttons for each of the primary controls. To use one, select the button, then locate on the form where you want the control to be placed.

Properties: This term is used to describe the set of data associated with an object such as a form or a control or some

other program object. In VBA program development, you manipulate the properties of the controls in a dialog box where you can change their values as needed by an application. When we are talking about objects, the properties are the data elements associated with them. For example, an Arc object in AutoCAD would have properties for the center point, radius, and angles. By changing the properties, you change the way the object will be displayed or will work with the system.

Project: A program in VBA is a project, and the project window will display all of the components in a given project.

When VBA inside AutoCAD is first started, the only component in the project is the AutoCAD drawing that is currently active. As forms and modules are added to the

(39)

< previous page

page_11

next page >

Page 11

project, they appear in the project window display. Projects are stored in DVB files in the hard drive of the computer.

Module: Projects contain forms and modules. The forms are the dialog box and associated code while modules are just

code with no dialog boxes. Modules are typically used to house standard routines from a productivity library or to hold code and data that is accessed by more than one form.

Objects: Objects are containers that house both program code and data. Generally, the data elements are called

properties, and the program code elements are called methods. The best way to think of objects is as a set of data that uses routines to manipulate that data. Other programs can use some of the routines while others are privately held inside the object for internal use only. Objects are capable of being cloned into new objects that share the same properties and methods. Software libraries often make use of the cloning or inheritance aspect of objects to build a tree of different yet related objects. Because of this cloning, objects can also use the same name as other objects to reference information or routines that are unique inside that object. The subject of object-oriented programming can fill a book by itself and is beyond the scope of this text. However, you will become familiar with the concept of object-oriented programming just because that is how things are accomplished in VBA as far as working with AutoCAD. In VBA, the object browser is used to explore the objects available. When an object is selected, its properties and methods are displayed for further reference. This makes programming in objects very easy, and as we explore the development environment further you will see that object programming can be quite easy.

Methods: This term is applied to the subroutines and functions that are inside an object. When looking for a particular

function that performs a particular activity, you start by looking for the object that controls those aspects of the system. Once you identify the proper object, the method can be found along with the properties. For example, to change the start point of a Line object in AutoCAD, the StartPoint method is

(40)

used. This method can be found in the object definition for a Line entity called acLine. AutoCAD methods and objects tend to start with the characters ac, making them easy to identify in the code as well as when searching the object browser.

Collections: A collection is a group of common objects that can be referenced as a singular item. For example, a project

contains collections of modules and user forms. More important to the task of customizing AutoCAD is the fact that groups of drawing objects are manipulated as collections. When working with a selection set in VBA, you are working with a collection.

Getting Comfortable with the IDE

The first thing you will encounter as you learn VBA is the IDE. The IDE is a collection of windows that combine to form a complete programming system, including an editor for the program text, a forms or dialog box editor to build the interface, a project component browser, and other tools to make the programming task easy. For some, their first

impression of the IDE is that it is a bit overwhelming because so much information is presented at once. It appears to be a very complex tool to use, but that is far from the truth. All you need is to spend a little time working within the

environment to become comfortable with the elements inside.

The situation is not unlike learning to drive a car for the first time. At first, the controls are foreign, and you're not sure which are important and which are not important. But after spending a little time behind the wheel in driver education, you become comfortable with the feel of the vehicle, and you learn how to scan the dashboard for critical information. The VBA IDE is much the same. There are windows displayed that you may not need to use in your programming efforts, at least not all the time. But because they are presented when you first start the system, most think they must be important and become concerned when they don't understand what they see. Because of the complex display, many beginners get the feeling that the system is complex and difficult to use.

(41)

< previous page

page_13

next page >

Page 13

These windows can be hidden most of the time, brought forward when needed, and pushed to the background when not. So, like learning that the battery gauge in a car does not require constant checking, there are windows that you do not need to see all the time as you write programs in VBA.

Starting the VBA IDE

The start-up procedure for the IDE inside AutoCAD varies slightly depending on which version of AutoCAD you are running. As of the writing of this book, there are two approaches to starting the IDE. The different approaches depend on the exact version of AutoCAD in use.

VBA first appeared in AutoCAD Release 14 as a preview edition. Installation of the preview edition was optional, so not all AutoCAD R14 installations will have VBA installed. You need to make sure you have VBA installed if you are still running the original Release 14 product of AutoCAD. To install VBA from that version, get the original AutoCAD distribution CD and use the Windows Explorer program to locate the VBA setup program. When loaded, VBA will appear as a pull-down menu entry. Selecting the editor option from that menu entry starts the IDE.

An updated version of AutoCAD Release 14 (called Release 14.01) and AutoCAD 2000 both contain VBA as a normal part of the system installation. In order to have VBA not installed, you must select a custom installation and remove the mark for the VBA components. As a consequence, most AutoCAD Release 14.01 installations contain VBA. Start the IDE in this environment by typing the command VBAIDE at the command line of AutoCAD.

The difference between VBA in AutoCAD R14 and AutoCAD 2000 is that the newer version (AutoCAD 2000) contains many more methods and properties that allow access deep into the AutoCAD system. There are also more objects available in the newer version.

Another way to start the IDE is when you're loading a VBA project into memory. The VBALOAD command is used to load a project, and

(42)

there is a toggle on the dialog box for file selection that indicates whether the editor should be started after the project has been loaded. The existing project will be displayed when the IDE starts up.

Figure 1.1 VBAIDE in AutoCAD

When started with a project already loaded, the IDE will present a full-screen development environment containing multiple windows as seen in figure 1.1. Select the one you want to work with by picking it from the Windows pull-down menu or by selecting the proper icon in the toolbar menus shown. When starting with no existing VBA program in memory, the IDE presents a blank work area with the project explorer and properties windows visible. Use the menu Insert options to start the definition of a code module or input form. The next chapter contains a tutorial walk-through to create a simple program in VBA and can be used to learn the basics behind programming in this environment.

What's in the IDE?

As we mentioned before, there are numerous windows in the IDE, and at first they may not appear all that friendly. But it does not take long

(43)

< previous page

page_15

next page >

Page 15

before you will be comfortable navigating your way through complex programs of your own design. The IDE was written by programmers, for programmers, and as such it serves as a very powerful tool in the development of applications. So let's look at the various components in the IDE and get a general feeling as to what they are for and how to use them.

Project Explorer: (Figure 1.2) This window presents a tree diagram showing the modules and forms that are part of the

current project. The Project Explorer provides one method for getting around in your program code. To get to a particular module, select it in the hierarchy, then select the view code or form button. When you're writing code, you won't use the Project Explorer too often, so it can be hidden to make more space for the code window.

The Project Explorer becomes more and more useful as your projects grow in complexity through the addition of more forms and code sections. As the need comes up, you can restore it to the screen for navigating about your project.

Figure 1.2 Project Explorer

User Form Windows: The dialog boxes of an application are defined in user form windows. Generally you start

development of a new application by opening a new user form window and then placing the controls for that window into the grid displayed. You can quickly jump to the code window and the code specific to an event by double clicking on a control while in the user form window. Designing new forms is very easy, and it is tempting to get ''creative" in how you present something. Chapter 13 has been devoted to programming style, and we recommend that you adopt standard styles for a variety of reasons.

Properties Window: (Figure 1.3) The details about whatever object is currently highlighted will be shown in the

(44)

include the name of the object, the color or display disposition of controls and forms, captions, and numerous other features. You'll use the Properties window the most when you are working on the design of a form for user input. During coding it will seldom be referenced, except to see what possible values a property might take. Like the Project Explorer, it can be removed from view to make more room for the code window.

Each object on a form has a variable number of properties, and the list will change as you select the different controls. These represent the control properties that can be set at design time when you are creating the program for the first time. For some controls, there are additional properties that can be added while the program is running. When referencing a property in the help system, make sure to note if it is run time changeable.

Figure 1.3 Properties window

(45)

Code Window: Program entry and review takes place in the code windows: there is a code window for each user form

that has code associated with it. Entering code into a new program is aided in the code window by the system. When you reference an object such as a control in a form or an AutoCAD data entity, the editor will prompt you through the various levels of the object to get to the property or method you need. And as you debug your programs the system will show you the code that caused a problem in the code window related to the user form or module in which the problem occurred.

The Object Browser: (Figure 1.4) Start the Object Browser window by selecting the Object Browser button, by selecting

it from the View menu, or by pressing the function key 2. The Object Browser is a tree structure display that shows all the objects known by the VBA system. This is

(46)

where you go ''shopping" for an object when you are not sure of the name or when you are looking for a method (function) to perform a particular task. The Object Browser links to the help system through the function key 1 that facilitates the learning of the object library. Although there are many objects in the library it does not take too long to learn the important ones.

Figure 1.4 Object Browser Developing Applications with VBA inside AutoCAD

The steps involved in developing applications using VBA start with properly identifying that VBA is a proper, if not the best, solution for the job. Although VBA is a very flexible programming solution, it does not provide a method for adding new commands to AutoCAD, and this may present a problem for the developer. Instead, VBA applications revolve around dialog boxes and interfaces to AutoCAD and other programs. So the first step in developing a VBA application is to develop the user interface.

The user forms editor and toolbox are used to define the dialog box or user form. Select a control from the toolbox, then locate on the form grid where you want it to be and how big you want it to be. You'll then reference the properties window to change the captions or colors or whatever other properties need to be modified to fit the application. As you define the controls, you can enter the code window to define what happens when the control object is picked, clicked, changed, or some other event takes place related to the control object.

(47)

< previous page

page_18

next page >

Page 18

A key aspect to keep in mind when writing programs in VBA is that the programs are event oriented. That means you program modules that respond to events. The events your modules will respond to are usually user drivencaused by a mouse click or keyboard activity. Hence most of the code you write will be to respond to these events and to process the input values when instructed to do so by the user. Unlike other programming environments you may be used to working in, there is no main program that controls the flow of events. At least there is no main program you have to write. When you run your program, you actually run a dialog box manager that looks at the form design, paints it on the screen, and handles the essential program setup sequences. You are responsible for programming the setup and processing modules that pertain only to the data you are manipulating. The remaining activities that take place in the Windows environment are controlled by the VBA processing system. If you have ever programmed or looked at the process involved in developing a Windows application the hard way, you will greatly appreciate all that VBA does to aid in your application development.

The common structure of a VBA program is to simply collect data in a dialog box and then process the data when a button is pressed. Generally, there is a dialog box setup stage where default data is placed into the controls. Keeping the data in the controls is a great way to store the data in your program. When the user changes the value, your program can test to see if the data change is proper in the context of the application. That way, the data in the control is always something that can be used, and no more code may be needed to check the value for accuracy and usability. If a module needs to know what the value of a particular user input variable is, the control is accessed to get the current data value. In most VBA applications there is at least one button that performs a process with the input data. There may be more than one button for more complex applications, but there will be at least one. That way the user can input all data, review it on the screen, then press the activation button to process the data into output. There should also be an abort or

(48)

exit button in case the user needs to run some other task inside AutoCAD and return to your program.

The next chapter will walk you through the process of how to write a simple program in VBA that actually does

something useful. If some of these concepts in programming seem difficult to you, go through the next chapter carefully and observe how easy programming in VBA is once you get used to it. The hardest thing for most programmers

learning VBA is the idea of saving data in the input dialog, even though the dialog may not be visible on the screen. But this is a natural way of programming, once you become familiar with objects and the tactics involved in object-oriented programming.

(49)

< previous page

page_20

next page >

Page 20

Chapter Two

VBA Application Jump-Start

In this chapter we are going to jump right into the VBA programming environment and develop an application program. The program is not advanced, but it does serve as a good example of the power of VBA inside AutoCAD. It also gives programmers who are learning the VBA system a chance to try out the features in the programming environment by following the step-by-step procedures.

Description of the Application

The program to be developed is the start of a bill of material counting routine. Specifically, it will count block references in the drawing and report them in a list box as seen in Figure 2.1. When the list members are selected, the block references are highlighted in the drawing.

This application demonstrates a number of aspects of how VBA applications handle things inside AutoCAD. It also shows the true power of VBA inside AutoCAD and how objects can be used to keep the coding at a reasonable level. The application shows objects of all kinds in use, ranging from dialog box objects to AutoCAD objects.

As a teaching tool, this program involves a form for user reporting and input. It also involves blocks and the manipulation of the block table.

(50)

Selection sets, filters, basic user input, and string handling are also demonstrated in this simple example. Programmers learning how to develop applications using VBA should attempt to build the same problem by following the instructions below.

Figure 2.1

Block Counter macro running Start Your IDE

Get started by loading AutoCAD 2000 into the computer, then starting the VBA developer environment with the command VBAIDE. When using AutoCAD R14, you will be required to first install the VBA system before the VBAIDE command environment will be available. VBA is not supported under earlier releases of AutoCAD. Design the Form

The development of many VBA applications will start with a dialog box or form. Forms are easy to build inside VBA using the visual tools provided. A form is an object, and the items that go inside the form are also objects, but they are called components more often than not.

Using the pull-down menus, go to Insert then select the UserForm option. A rectangle will appear on the screen that contains grid points.

(51)

Figure 2.2 Toolbox controls

The toolbox contains the components that can make up a screen. As you move your mouse over each and

(52)

hesitate, a highlight box (tool tip) will appear telling you the name of the object as in figure 2.3.

Figure 2.3

CommandButton selection

The dialog box in Figure 2.1 contains two controls (objects). The button is a control, and so is the listbox. Select the CommandButton option from the toolbox controls.

Locate a point on the grid to place the button as in Figure 2.4.

Figure 2.4

Placing CommandButton in grid

If you make a mistake or want to move the button on the grid, just select it and drag it to a new location. You can also resize it and change the corners as needed by your application. The control just inserted will behave like most Windows objects do. You can change its location and size with the pointing device only. Now let's change the information inside the control object. That is, we will change some of the properties of the CommandButton to suit our needs. You cannot change these properties with a mouse alone, so you will have to do some keyboard work.

Select the properties dialog box as in figure 2.5.

Pick the Caption property within the list shown. You may have to scroll the list to get to the property you want. Using the keyboard, type a new caption value''Return to AutoCAD."

(53)

Figure 2.5 Properties dialog

Notice that as you type the command button will change as well. The text you are typing will appear in the CommandButton in the form design window. You can resize the CommandButton as needed so that the text fits.

References

Related documents

The total coliform count from this study range between 25cfu/100ml in Joju and too numerous to count (TNTC) in Oju-Ore, Sango, Okede and Ijamido HH water samples as

For helpful overviews of the global situation, see Steven Hahn, &#34;Class and State in Postemancipation Societies: Southern Planters in Comparative Perspective,&#34;

The small premature infant who has undergone a sur gical procedure and would have to be fed by gavage is much more easily and safely fed through a gastrostomy tube (Fig. 2)..

This study investigates the potential of bimetal impregnated catalysts supported on activated carbon derived from biomass for Selective Catalytic Reduction (SCR) of Nitrogen

19% serve a county. Fourteen per cent of the centers provide service for adjoining states in addition to the states in which they are located; usually these adjoining states have

Spain’s Podemos, Greece’s Syriza, France’s Parti de Gauche and Portugal’s Left Bloc and Communist Party, together with like-minded parties across Europe have been inspired in

Passports Labour legislation Unemployment benefits Child allowance Birth &amp; marriage certificates Consumer Protection Regulation Environment-related permits Work permits