Anda di halaman 1dari 16

VBA: Integrating with Microsoft Access - Part 1

By dave espinosa-aguilar This article is the first in a series on integrating the programming power of AutoCAD VBA with the functionality found in other Windows applicationsspecifically, Microsoft Access. Through Visual Basic programming within AutoCAD software, you can launch Access and bring the full power of a database application into an AutoCAD drawing session. The information in this series demonstrates how you can organize, query, and manipulate entity information, on-screen or in the background, of an AutoCAD sessionwithout spending a dime on additional compilers or documentation. If you have AutoCAD and Microsoft Access already loaded on your workstation, this technology is ready and waiting for you to take advantage of. If you're willing to get up to speed on it. And that's the catch: you must enter the object-oriented world of Visual Basic programming to add Access functionality to AutoCAD. Even if you've programmed in AutoLISP, you'll find that Visual Basic is not as forgiving or as accommodating. You'll also learn that the rules you must follow to create a viable VB application are very strict. Of course if you have some experience with AutoLISP programming, you have an advantage over someone who has no programming experience. And although the world of object-oriented programming isn't necessarily hard to master, as with any language, it does take time and a lot of practice to learn. So why should you bother? What are the advantages of integrating Access and AutoCAD VBA? The more you learn about the software you already own, the more productive and efficient you become with it. If the nature of your drawings and designs lends itself to database functionality, then set aside any preconceived notions you may have about cranking out code, and go Zen with me for a bit as we consider some potentially profound questions. What Does Microsoft Access Offer an AutoCAD User? The information in many types of CAD drawings essentially reduces to a vast database of numeric, financial, and textual information. Consider for example a drawing that has thousands of point entities reflecting survey location and elevation data.

Or this: a landscaping plan filled with hundreds of plant types each of which has field data associated with it (plant type, age of plant, water requirement, plant nursery source, plant cost, and so on). And now this: an architectural design that has cost and manufacturer information associated with materials, parts, and details. In each of these cases, much of this information is not associated with its related CAD, entities in an easy-to maintain and easy-to-query format, and it can be a timeconsuming (and expensive) process not only keeping tabs on all of it, but also working with it efficiently. Challenges With Block/Attribute Data Storage Methods Many AutoCAD entities hold additional associated valuable data through the use of Blocks with Attributes, but you can only manipulate this data or share it with other Windows applications in a very limited way using AutoCAD alone.

Figure 1: Six objects with associated data. Figure 1 shows six insertions of a single block with two attributes. The first attribute holds a keyword which distinguishes 'chairs' from 'seats' and the second attribute holds a number of chairs or seats. Imagine that your design has hundreds of such block insertions and hundreds of other block definitions as well, each with a unique set of attribute values. Although you can "pull" some information from these blocks and export it to a text file (for example, using templates with the ATTEXP command), you cannot: 1. Add up the total number of blocks that have chair for their first attribute value since all six blocks are named the same. 2. Add up the totalor take the average value or find the minimum or maximum valueof the second attribute value in those blocks having seat for their first attribute value. 3. Replace the values of the second attribute of those blocks having chair for their first attribute value.

4. Create a selection set or change the properties of those blocks using an SQL-type query for a stronger visual understanding of the data. All of which points to the primary benefit of databases: you can query them numerically, financially, by date, by string matches, and so on. But if you want to examine, process, tally, or otherwise manipulate the values you are storing in block attributes, you have few, if any, options within AutoCAD to do so. A database overcomes these limitations and many others. You may be asking, What about DBCONNECT, ASE, and other database technologies internal to AutoCAD? After all, you can use these tools to link AutoCAD entities with databases and then manipulate the entities. These tools are great as far as they go. But as anyone who has ever used them will tell you, they have a severely limited capacity to analyze entities, generate reports, import/export data, and mass-process field values internal to AutoCAD entities. The required linking interface alone (manually selecting entities to link them with database records) can be a prohibitive process. By programming AutoCAD thru its VBA technology, you can link external database records to AutoCAD entities based on the entities' existing properties and attribute values. Small Drawing = Fast Drawing Also keep in mind that using external databases with AutoCAD makes for fast AutoCAD sessions. When you store database information right in AutoCAD, it slows AutoCAD down (the bigger the drawing, the slower it processes). By externalizing data and linking it with AutoCAD entities, you not only gain full database functionality over that information, but you also significantly reduce drawing size. For example, imagine that you have a series of blocks representing tree types, each block containing up to 20 fields of unique data. Now the client asks you to change the values of certain fields for certain types of trees. Typically you would have to manually edit the block data. Have you ever changed over 20 attribute values in a block manually? It's time-consuming grunt work, isn't it? But if this data were in a database, you could easily create an index of those records that meet your criteria and change their field values in secondsif you have used AutoCAD VBA to link each CAD tree symbol to a record rather than attaching the data to the tree symbol in a CAD format. You also wind up with faster CAD drawings to work with since the entity count in the drawing is smaller. Currency, Dates, Numeric Quantities and Truth Conditions

Databases understand data types. They can distinguish the difference between a numeric value (such as an integer, a long or double real number), a dollar value, a True or False condition, or a date value. They "know" how to store these value types efficiently and to ask questions about them differently. Block attributes see every data value as a textual value no matter what that data represents to you, and this is why block attributes can't be numerically processed or queried effectively. When you explode a block with attribute values (using Express Tools or other tools that retain the attribute values), you wind up with TEXT entities that you cannot manipulate as easily as numeric values. To streamline data storage and keep AutoCAD sessions fast, to gain full control over data that you associate with CAD entities, and to query and manipulate huge amounts of data and the CAD entities that data is associated with, quickly, an external database is often the best alternative. What's Ahead? In the coming five segments of this series, we will examine how to use the AutoCAD VBA development environment and configure it for a typical application that links to Microsoft Access. You will learn how to create a database file with internal tables and how to close those tables and shut down the links. Once you have the database creation and linkage process down, you will begin to populate and edit database information, learn how to create entity-linking methods for it, and find out how to query the data. In the final segments we'll examine several sample applications that make it possible to:

Query a CAD drawing using SQL statements. Autolink entities to records. Graphically manipulate entities based on their data. Convert attribute data to database records. Generate an entity based on database records. That's exciting stuff ahead if you are willing to take the database plunge.

Applying Customization: ZOOM Elbow Room - Part 2

By Dave Pitzer Last time we developed an AutoLISP function that performed a Zoom Extents plusthat is, it issued a Zoom Extents command and then zoomed a bit further out. This new zoom feature provided an extra "border" around the extents of the drawing making working at the borders easier. As a review, here is the AutoLISP code for the macro:
(Defun C:ZEE () (command "Zoom" "E" "Zoom" "0.95x") (princ) )

This AutoLISP function performs two ZOOM commands: a Zoom Extents, followed by a Zoom out of 5 percent relative to the Extents view, giving use of the "elbow room". Working With the Pull-down Menus This month you will incorporate the equivalent of this AutoLISP macro into the AutoCAD menu system. Specifically, we're going to add a Zoom Extents+ macro to the other ZOOM command options in the

View drop-down menu. Note: The following steps assume that you are using the "out-of-box" AutoCAD menu. If you have developed or are using a different base menu, apply these steps to that menu. First, open the base, or source, menu file. You'll find this file in the \Support folder of a standard AutoCAD installation. It's name is acad.mns. Open this file in an ASCII text editor, such as Microsoft Notepad. Note: The standard acad.mns file is large, and Windows may prompt you to open the file in Microsoft WordPad instead. Accept the invitation. If you have another text editor installed, use that and perform the steps below.

View Larger Figure 1: The View Pulldown menu section. 1. Once you have the acad.mns file open, use the editor's search function and search for ***POP3. The text editor should take you to the section of the menu shown in Figure 1.

2. Add the bold text indicated by the arrow in Figure 1 (don't forget the ending semicolon). 3. Save the file and either start or restart AutoCAD to force a loading of the altered menu. 4. Check the altered menu by selecting it from the View dropdown. You should see the added Extents+ choice as shown in Figure 2.

Figure 2: The Altered View Pulldown menu section. 5. To test the macro, load a drawing (preferable a large one, extents-wise) and perform a ZOOM Extents. Then select Extents+ from the View menu and note that the display is zoomed out further. 6. To further test the macro, zoom into the drawing. Start the

LINE command and the choose Extents+ from the View menu. The display should zoom out to Extents plus an additional "elbow room" amount, giving the same view as obtained in Step 5. Being able to zoom out to the extents of the drawing plus a little bit more with a single "command" is useful when working with drawings, and the Extents+ menu macro does this quicklysaving time and increasing your efficiency. Next time, we'll devise a method of placing the Extent+ "command" on a toolbar.

Applying Customization: ZOOM Elbow Room - Part 1

By Dave Pitzer "The problem with zooming to extents," someone once said, "is that it backs you up against a wall." The "wall" in this case is the edge of the display window, and zooming

to extents leaves little elbow room to define zoom windows near the edges of the extents field. Look at Figure 1 where using the ZOOM EXTENTS command has backed up the drawing to the top edge of the display making it difficult to define a zoom window anywhere along the top edge.

View Larger Figure 1: A normal ZOOM EXTENTS view.

Wouldn't it be handy if the ZOOM EXTENTS zoomed to the extents and then just a little further out, leaving a narrow border at either the sides or top and bottom for more zoomingsomething like the result of the ZOOM shown in Figure 2?

View Larger Figure 2: A ZOOM EXTENTS+ view.

ZOOM EXTENTS + We can use AutoLISP to define a new ZOOM command that does just that. Here's what it would look like: (Defun C:ZEE () (command "Zoom" "E" "Zoom" "0.95x") (princ) ) Like many handy userdefined AutoLISP functions, this one is very simple. It issues the ZOOM command with the E (for extents) option and then reissues the ZOOM command with a zoom scale factor of 0.95x, which zooms the display out an additional 5 percent. The (princ) function merely prevents a "nil"

from being printed at the command line as the function terminates. As written, the function is called by typing ZEE (case insensitive) at the command line and then tapping the spacebar. Loading the Routine As you may know, each time a drawing opens, AutoCAD software searches the library path for an acaddod.lsp file. If it finds one, it loads the file into memory. So to have the C:ZEE routine available every time you start AutoCAD, just copy and paste the above code (including the very last right parenthesis) into your acaddod.lsp file. Or you can load a library of AutoLISP routines into the acaddod.lsp file, and they will be available every time you start a new drawing (or open an existing drawing). Very efficient.

Next time we'll incorporate this new ZOOM command into the View drop-down menu. Applying Customization: Writing LISP Macros Plus a Bonus 3D Toolchest

By Dave Pitzer AutoLISP and Visual LISP macros are among the simplest and most useful of AutoCAD software's customizability options. These short, user-defined LISP functions can perform a frequently used command sequence in only two or three keystrokes. Here's one example, familiar to those who work in 3D. If you were to rotate the current UCS ninety degrees about the X axis and switch to a Plan view on your keyboard, you'd need thirteen keystrokes. You could use the View pull-down (which utilizes a menu macro) to get down to two mouse clicks-but what you gain in reduced typing is lost through your manipulating the pull-downs. A simple LISP macro does the trick in as few as four or five keystrokes. Another, classic example is a LISP macro that starts the ZOOM command and then issues a zoom factor. Here's how you manually perform a 20-percent zoom-out of the current screen display:
Command: ZOOM [or Z] [All/Center/Dynamic/Extents/Previous/Scale/Window] <real time> .8x

That's nine keystrokes including pressing Enter, six if you use the PGP file shortcut for the ZOOM command; even using the Zoom tool on the standard toolbar requires two mouse clicks and three keystrokes. A simple LISP macro can reduce the operation to two or three keystrokes. Now It's LISP's Turn

Here is the LISP code that makes up the above Zoom/.8x zoom-out operation. Even though it makes no difference to the AutoCAD LISP interpreter, I've separated this routine into three lines.
(Defun C:Z8 () (command ".ZOOM" ".8x") (princ) )

This is the basic template for all LISP macros, no matter how complicated they become. The first line establishes the name of the function (C:Z8). The second line defines what the function does: the ZOOM command is called, followed by the .8x option, just as you would type it on the command line. The last line is for LISP housekeeping purposes; it ends the function with a clean return to an empty Command prompt. The heart of the macro is the middle portion where AutoCAD commands and options and user responses are defined. The first line is always the same; the only difference is the name assigned to the function. The last line is also always the same. The Rules of the Road for LISP Macros: First Line Start with "Defun," the abbreviation for Define Function, then C:, then the name you assign to the function; the routine above is named C:Z8, but you only have to type "Z8" and press Enter to launch it. Next, the pair of left and right parenthesis are LISP requirements. Note: Keep the name short-three or four characters-otherwise you defeat the purpose of the macro, and select a name that suggests what the function does. The Body The body of the function (often just one line of code) describes what AutoCAD commands are executed and specifies the answers to any prompts the command may issue. This portion of the macro performs the action you would at the keyboard. To emulate keyboard strokes, certain rules are established:

The LISP function command precedes the command name that is enclosed in double quotes. Use the full command name. Enter is represented by a pair of double quotes (""). The LISP keyword "pause" suspends the macro to receive user input, such as selecting a point or dragging. Prompt responses (other than an Enter) are enclosed in double quotes, such as "2" or "R".

Please note that many simple LISP macros do not require user input or point entry; they issue commands and fixed or hard-coded responses to prompts. Take a look at the following example:
(command "scale" pause "" '(2 3 0) "5")

Here, the SCALE command is called by the command function. Use Pause to select an object. The double-quote pair closes object selection. The SCALE command's "Specify base point" prompt is answered with the point '(2 3 0) and the "Specify scale factor:" prompt is answered by "5". Note: Before you write a macro, it's a good idea to review the AutoCAD command and its various prompts as well as any mouse input; the vast majority of macro problems are directly attributable to improperly replicating the prompt sequence. Command prompts and their order must be closely followed, just as with keyboard responses. All a macro does is play back simulated input from the keyboard. Macros for 3D If you work in 3D, here are a group of macros that will quickly pay for themselves. I find, for example, that typing "iso" and pressing Enter is much faster than using the View/3D Views/SE Isometric pull-down method. If you don't need these particular macros, use them as models for ones that will facilitate your AutoCAD work. The following four macros take advantage of four undocumented options to the VIEW/Orthographic command for placing the display in the Southeast, Southwest, Northeast, and Northwest isometric views. Since the Southeast (SE) isometric view is considered the standard iso view, I named my macro iso instead of ise.
(defun C:iso () (command "-view" "seiso") (princ) ) (defun C:isw () (command "-view" "swiso") (princ) ) (defun C:ine () (command "-view" "neiso")

(princ) ) (defun C:inw () (command "-view" "nwiso") (princ) )

The next six macros accomplish two handy operations with four keystrokes: they change the view to front, back, left, right, top, and bottom; and they change the UCS to Plan view.
(defun C:vft () (command "-view" "front") (princ) ) (defun C:vbk () (command "-view" "back") (princ) ) (defun C:vbt () (command "-view" "bottom") (princ) ) (defun C:vtp () (command "-view" "top") (princ) ) (defun C:vrt () (command "-view" "right") (princ) ) (defun C:vlf () (command "-view" "left")

(princ) )

Now that you know the procedure for writing simple LISP macros, try making up some of your own. Think of all the commands that cause you to frequently reach for pull-down menus. Then write some macros that accomplish the same operation much more quickly. Loading and Running Macros LISP macros, once written, must be loaded into AutoCAD memory in order to run. So let's group all of your macros into one file and have AutoCAD load them automatically. 1. From the APPLOAD command, select the Startup Suite function. 2. Type, or copy, your LISP macros into any ASCII text editor (such as Notepad). 3. Save this file with an LSP extension (for example, you might call your 3D macros 3dutils.lsp). 4. Place this file in the AutoCAD Support File Search Path. 5. Select Tools >AutoLISP >Load. 6. In the Load/Unload Applications dialog box, go to the list box, find the file, then drag it onto the Startup Suite icon. The file will now be read and loaded for each session of AutoCAD. 7. To run the macros, type the macro name at the Command prompt. Neat, huh? Come back next month to write more-complex macros and learn more about LISP.