VBA: Integrating with Microsoft Excel - 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 applications—specifically, Microsoft Excel. Through Visual Basic programming within AutoCAD, you can launch Excel and bring the full power of a spreadsheet application into an AutoCAD drawing session. The information in this series will demonstrate how to generate, organize, query, and extract linework visibly or behind the scenes during an AutoCAD session without spending a dime on additional compilers or documentation. If you have AutoCAD and Microsoft Excel already loaded on your workstation, this technology is ready and waiting for you to take advantage of it. To enter the world of Visual Basic programming and add Excel functionality to AutoCAD software, you have to be willing to spend the time it takes to master this object-oriented programming tool. Even if you've programmed in AutoLISP® before, Visual Basic is not as forgiving or as accommodating, and the rules that must be obeyed for everything to work right when you run your own VB applications are very strict. This isn't to say that an AutoLISP programmer can't conquer the world of Visual Basic; it just takes more dedication and effort. So... as with any serious investment of your time, it pays to step back and examine what getting up to speed on Visual Basic (and the integration of AutoCAD VBA and Microsoft Excel) brings to your table in the first place. The more you learn about the software you already own, the more powerful it gets and the more impact it stands to have on your productivity. If the nature of your drawings and designs lends itself to spreadsheet functionality, then consider setting aside notions of cranking out code, and go Zen with me for a bit as we consider some potentially profound questions... beginning with "Why should any AutoCAD user care that integration of AutoCAD and Microsoft Excel is even possible?"

Reason #1: Automated Fully Customizable Part Counts
Have you ever counted entities in a drawing manually? By that I mean to ask have you ever (with your finger or pencil) tallied every parking lot space or every chair or every toilet in a bathroom or window on an exterior building wall or every HVAC fixture throughout a series of roof plans? Have you every counted sprinklers or landscaping features by plant type, bolts or screws for an assembly, or datapoints for a given site plan? Imagine pressing a menu button and being done with the process!

Reason #2: Queries
Maybe you use blocks with attributes. Have you ever wished you could count blocks (or maybe even select them) based on the values in those attributes? Maybe you use Extended Entity Data, which attaches gobs of unique information to individual entities. Wouldn't it be slick if there were an easy way to take the sum or average of that information within seconds? There are some ingenious tricks and techniques out there like using the old SSX.LSP routine, the internal FILTER command and various other filtering functions in AutoCAD, layer isolations, the ATTEXT Block Attribute extraction to CDF/SDF command, and even basic select-objects techniques to report entity counts in a drawing. But none of them come close to the reporting, querying, and attachment control that a linked spreadsheet application can offer. Want to specify the name of a block with an attribute value that falls within a certain numeric range and have those entities meeting that criteria reported with full text formatting in a real spreadsheet template? You can with VBA. Imagine reporting attribute information or extended entity data from entities based on their location in the drawing or even based on the way in which they are being used or were originally generated (for example, count all blocks named "x" that were inserted by CAD operator "y" during month "z" of last year). If you're a SQL guru, you could actually query blocks with attribute data using a SQL query statement—entirely through VBA.

Reason #3: Portability and Data Reporting
Are there people in your office who use Excel with the same impressive proficiency that you use AutoCAD software? Have you ever wanted to share your AutoCAD information with them in a format with which they can easily work? Through coding, you can convert any kind of AutoCAD information into a format that speaks another Windows application's language. You can translate your vector base into a grid base or a record base. You can view, report, and analyze drawings with all the usual analytical bells and whistles in a spreadsheet (flow charts, pie diagrams, trend charts, and so on) so that non-AutoCAD users using their native reporting methods and their native graphical tools can easily understand that AutoCAD data .

Reason #4: Externalized Data
The golden rule of CAD drawing performance: small = fast. An AutoCAD session is never faster to work with than when you start it up. From then on, everything just goes downhill in terms of speed and performance. It makes sense to bust out any information in a drawing that is not immediately relevant to the work being done. For example, attributes eat up memory and they're cumbersome to work with. Why not store them (associated with the relevant entities) in spreadsheet cells rather than as nested entities in a drawing? Data externalization provides two terrific benefits: external editing and manipulation of data and drawing-size reduction, which increases drawing performance. It is possible to open a spreadsheet and change the value of a cell without ever opening AutoCAD. Can you imagine how easy it would be to swap values of certain cells using Excel sorting/replacing or reformatting functions and have those changes immediately reflected in AutoCAD block attributes? How much smaller would your drawings be (and how much faster would they load, save, regenerate, and edit) if attribute entities were completely removed from them? And while we're discussing attributes...

Reason #5: Hard-Coded Textual Options
Now this one might really play with your mind. Imagine that you could control (hardwire) those values you allowed to be entered for any particular use of text or blocks with block attributes. For example, imagine that when you open a drawing, it reads information read from a spreadsheet and automatically sends that data to a title block. Imagine that you could provide your users a combo box of preset textual or numeric values for any block's attribute values (based on the block name no less) when those blocks are inserted. And imagine that the hardwired set of values was controlled in a password-protected master spreadsheet file so that only certain users could change the allowed values for those block attributes? There are actually ways (using AutoCAD VBA and Excel) to do this kind of thing. The stuff of dreams.

Reason #6: Tabulation
In an AutoCAD drawing, put a bunch of text entities with numeric values (for example, currency) in a vertical column (see Figure 1). Now add them up and report that value at the bottom of the column. Oops! Something changed. Edit one of the text entity values and retotal everything. Find their average value or their minimal value or their maximum value and report that, too, at the bottom of the column. Oops! Sales tax just went up! Increase all of the text entity values by a new percentage value and change the new total at the bottom of the column. Are we having fun yet? For years, people have been using TEXT entities to report tabulated data on drawings without the benefit of tabulation tools to do it, and a TEXT entity doesn't know the difference between a dollar and a toilet. Spreadsheets have been cranking out this kind of information for over a decade. Think hard about this one, folks. Maybe, just maybe, the process of creating schedules is possible without getting a headache.

Figure 1: Creating a schedule even this simple is time-consuming to construct and tally without a spreadsheet.

Reason #7: True Text-Formatting Control At the recent AUGI® Annual General Meeting, the top 10 wish-list items were announced for the year and right up there near the top (for the umpteenth year in a row) was "tabbing for MTEXT"). If you've ever tried to align columns of TEXT or reorganize the line-by-line textual content of an entity after its assigned width space changed (a very painful process), or if you've ever tried to perform any number of basic text-formatting

manipulations within AutoCAD software (which are a cinch to do in Excel), you know how hard it is. Now you don't have to wait for such tools. By importing spreadsheet data (or even my linking and/or embedding it), you can bring full text control to your AutoCAD drawings (see Figure 2). Changing the assigned width of columns of textual or numerical data can be as simple as a drop-and-drag operation.

Figure 2: When you bring Excel grids into your drawings, you have complete control over text formatting, column width, cell border thickness, and even background patterning.

Reason #8: Formulas? What else can a spreadsheet do with data in a cell? Well for one thing, it can contain a formula to generate cell content based on other cells. That means that you can actually apply formulas for TEXT entities in your drawings! Aside from obvious uses of this capability (such as generating totals after a part count), you could even use Excel to figure out (through conditional states) what text, notes, or details need to be imported into a drawing based on parts found in a drawing. Yes, folks... this starts getting wild.

Reason #9: Automated Linework Generation
And while we're on the subject of things being imported based on queries and tallies and other amazing spreadsheet operations, we can also generate linework itself from spreadsheets. You can convert databases to an Excel format, and easily view and edit them. And once you have that data in a spreadsheet format, it is possible to start generating linework from it! Imagine that you have a basic COGO point set of X, Y, and Z values broken down into three columns. Contour lines or TINs could be generated from this information.

Reason #10: Costing Out a Drawing
Excel spreadsheets make great reference tables. Imagine that you have a list of prices for items you insert into your drawings, and imagine that you want a part count and a financial assessment of a drawing. To do this, you can begin with surveys of the entity database, pulling the necessary computational information into preset columns in a spreadsheet, and then price out the cost of the entire project based on an entirely different spreadsheet of price-per-item values. Inventories on steroids, and generated no less by a CAD user! I could give you in a heartbeat another 10 reasons to think seriously about this stuff, from enhanced job opportunities and more competitive salaries to the complete historical tracking of any drawing. In the coming articles, we'll examine sample code and develop microapplications that accomplish the types of operations described above. And it's not miracle working. It is, however, exciting and profitable stuff... for anyone willing to learn the game.

VBA: Integrating with Microsoft Excel - Part 2
By dave espinosa-aguilar This article is the second in a series on integrating the programming power of AutoCAD® VBA with the functionality found in other Windows applications—specifically, Microsoft® Excel. In the first article, we discussed what is possible; now it's time to examine how it's possible. And that begins with a quick overview of the AutoCAD VBA Integrated Development Environment (or IDE).

At the command prompt, enter the command VBAIDE. This initializes the IDE in a separate window. You can use the ALT+TAB keys to switch back and forth between the IDE and your AutoCAD session. If you close AutoCAD, the IDE window closes with it. The IDE is used to develop and debug your program code and your dialogs and to view the information your program is processing (see Figure 1). Once you have finished using the IDE (usually after saving your programming work), you can close the IDE window without closing AutoCAD.

View Larger Image Figure 1: The IDE enables you to simultaneously view your application user forms, code, the object browser, the toolbox, object properties, references and more.

The VBA Manager You can also bring up the IDE through the use of the VBAMAN command. Unlike VBAIDE, the VBAMAN command enables you to load (and unload) existing VBA project files to/from memory before jumping to the IDE to develop or modify them. You can work with several project files open at once. When you use the VBAMAN command, the VBA Manager dialog box opens. The Visual Basic Editor button in this dialog box takes you to the IDE (see Figure 2). The VBA Manager is also where you create new project files, develop macros to run your project files, or embed your programs in any of your open drawings.

3. 2. we're going to go straight to developing our very first program. it should be reporting your ACADproject. If the project name displays a + (plus) sign to the left. click on the plus sign to see subitem ThisDrawing (see Figure 3). It's objective is simple enough: open and close Excel. 5. Make sure you have Excel already installed on your system. Our First User Program Rather than try to explain every button and function in these interfaces. Click the Visual Basic Editor button to go to the IDE. Use the VBAMAN command to bring up the VBA Manager dialog box.Figure 2: The VBA Manager Dialog loads. It may be docked to one side of your window or it may be a floating window. . This creates a new project with a default project name (ACADProject) 4. and exports application code. 6. Start by making sure you're in a brand new AutoCAD session. Enter Control+R or select Project Explorer from the View pull-down menu to view the Project Explorer. Click the New button. In either case. and then follow along as we begin to develop our first application: 1. unloads.

Stretch the UserForm dialog box and the window the UserForm sits in so that they take up approximately the space shown in Figure 4. Click the OK button. Setting Up an Excel Reference Once you've added the UserForm to the project. 8. Select the box to the left of the Library as shown in Figure 5. 2. and UserForms included in a project. and for this application we need to be able to speak in terms of worksheets. which brings up the References dialog box. the Location label at the bottom of the dialog box should report a path similar to c:\Program Files\Microsoft Office\Office\EXCEL9. ." 3. select References. When you do this. The Project window and Toolbox are organized for easy object placement. You can also stretch the Toolbox dialog box.0 Object Library reference enables your application to speak "Excel-ese. which opens the Toolbox dialog box. From the Insert pull-down menu.Figure 3: The project window reports projects loaded. select UserForm pull-down to insert a UserForm into this project. and other concepts associated with spreadsheets. From the View pull-down menu select Toolbox. which returns you to the IDE. ranges. Here's how we do it: 1. the next step is telling AutoCAD software how to speak Excel-ese. Leave them as they are. Several references at the top of the Available References list may already be selected.0 Object Library (this assumes Microsoft Excel 2000 is already installed). View Larger Image Figure 4: A UserForm is created for the application. References expand AutoCAD VBA to include new tools and capabilities. cells. and search down through the list of available references until you see one that looks like Microsoft Excel 9. Figure 5: Adding the Microsoft Excel 9.OLB. From the Tools pull-down menu. 7.

let's create some buttons on our UserForm dialog box that launch Excel. Slowly click twice over a button to move the cursor inside the button. and CommandButton3 text reads Quit as shown in Figure 7. Move your cursor over the various objects in the Toolbox dialog box and pay close attention to the tooltips.That's all it takes to expand our application to speak in Excel terms. enabling you to change the button's label. Here we go: 1. This will spot a button on the UserForm. 4. Create two more buttons and stretch them so that they appear similar to those shown in Figure 6. View Larger Image Figure 6: You can re-organize the look and layout of your application and development interfaces at any time. Move your cursor over the UserForm and pick an upper-left point. 3. close Excel. Click and drag on the button grips to stretch it into any size you like. and Quit out of our application. CommandButton2 text reads Close Excel. Find the tool with tooltip CommandButton and click it. Change the label for each button so that CommandButton1 text reads Launch Excel. Your cursor changes to CommandButton draw mode. If you click twice too quickly. Adding Buttons to the UserForm Now that you've told the application how to speak Excel-ese. Close out any code windows that appear and try again if necessary. a code window will appear instead. Figure 7: It is a helpful practice to include a Quit button in your primary UserForm to provide an easy means to stop your application when it is running. . clicking slowly inside each button to move the cursor into the button text. 2.

You just ran your first program! You can also run a program by typing the F5 key when you are in the IDE. 1. We're going to run our little program and use this button to stop it. The code window shows a combo box with the value CommandButton3 in the upper-left corner so you know the code you're writing will pertain to this button only. Click the Quit button to terminate the program. In the main part of the code window are two already typed statements: Private Sub CommandButton3_Click() End Sub 2. select Run Sub > UserForm menu item to launch our program. let's get the code for the top two buttons assigned. Click between these two statements and enter the word End so that the code statement now appears as: Private Sub CommandButton3_Click() End End Sub Each button acts as a routine unto itself. 5. which tells you that the code will be called up when this button is clicked while the application is running. but it does help keep command statements visually organized. 1. Again. it's time assign code to each button. you should return to the IDE. Double-click the Launch Excel button to bring up its code window and type the following code into it: . 3. Clicking on the upper two buttons will do nothing. Close the code window. Double-click the Quit button to bring up the button's code window. Launching and Closing Excel This next part is going to take some explaining. The indenting of the command isn't vital to the program running correctly. The END command in Visual Basic terminates a running application. 4. but if you click the Quit button.Your First Coded Object Now that you have finished the dialog box. In the upper-right corner of the code window is another combo box with value Click. But first. Your dialog box should appear over your AutoCAD session. we're going to start very simple by writing the code for the Quit button. From the Run pull-down menu.

" If launching Excel generates an error. If any error occurs. the code is instructed to continue on instead of stopping at the error. the application variable is set to a currently running session of Excel. and variable shtObj as an Excel Worksheet object type (all three of which are types now available to us with the excel 9. double-click the Close Excel button to bring up its code window and type the following code into it: Let's take a closer look at the code for the Launch Excel button. this statement generates an error (which has a nonzero value). then we know that Excel isn't running yet. start up Excel. but the code does not start by launching Excel. we know that Excel isn't even installed. The UserForm is hidden from view and the error state variable is cleared (set to a value of zero).2. variable wbkObj as an Excel Workbook object type. Likewise. Now. This may seem a little weird at first. The code for this object begins by dimensioning variable excelApp as an Excel application object type. if Excel isn't running. set the variable to what is running. Otherwise.0 Object Library referenced). We report this through a message box exclamation function and end the program. So we're essentially saying "If Excel is already running. So we clear the error state and use the CreateObject function to launch an Excel session. If an error is generated. Here's the relevant code: Next. Here's that code: .

If Excel isn't running (someone may click Close Excel first—after all. The code in the Close Excel button does shut down the currently running session. but if you check the Task Manager after using Close Excel. . you have to consider every possibility). and we are told Excel isn't running. the UserForm is made visible again. Variable excelApp is dimensioned from scratch again in this procedure as an Excel application object type. For now. the UserForm is hidden. then the application quits. Viewing the Windows Task Manager (CTL+ALT+DEL) is also helpful to check if you've left any Excel application open. and the error state is cleared. the UserForm is made visible again so that we can click the buttons to close Excel down or quit our VBA program. If no error is generated. how to format that passed information. Variable excelAPP is set to an assumed already running session of Excel.Once the application variable is set to either the currently running session of Excel or a new session of Excel. an error is generated. This done. and the workbook and worksheet variables are set to the first workbook and the first worksheet in that session. combo box. The UserForm is made visible again so that we can click our three buttons: When running this VBA routine. and so on. you should see an icon for the currently running Excel session. edit box. You can always shut down any Excel sessions through the Task Manager if needed. What happens if you press Launch Excel twice in a row? What happens if you then press Close Excel? In Conclusion In future segments we'll discuss how to pass information to Excel from our VBA routine. We'll also look at how to pull information from a spreadsheet into a UserForm list box. and how to channel it to a single cell or multiple cells and ranges. The code is instructed again to continue if an error is encountered. Here's that code: The code for the Close Excel button is fairly imitative of that for the Launch Excel button. make sure you understand clearly how to make the Excel connection. it helps to use ALT+TAB to switch between Excel and AutoCAD after Excel has been launched.

. You can study the properties of these and other Excel objects through the AutoCAD VBA IDE (integrated development environment) by: 1. Microsoft Excel." and how to launch a session of Excel.VBA: Integrating with Microsoft Excel .Part 3 By dave espinosa-aguilar This article is the third in a series on integrating the programming power of AutoCAD® VBA with the functionality found in other Windows applications—specifically. let's examine the Workbook and the Worksheet objects in Excel. Running the IDE (use the VBAIDE command). and in this session we discuss how to port formatted data from AutoCAD VBA to Excel worksheets. Using the Object Browser tool (use the F2 function key in the VBA IDE or use the View/Object Browser pull-down menu option) with the primary Combobox set to Excel (see Figure 1). In the first segment we discussed what was possible. Objects of Our Desire Now that you know how to make an AutoCAD VBA routine speak "Excel-ese. 2. 3. in the second segment we discussed how to establish a basic link with Excel through AutoCAD VBA to open an Excel session and close it down. Using the Tools/References pulldown menu option to activate a Microsoft Excel Object Library reference by placing a check next to this entry in the References listbox.

real numbers. it has a Cells property as a Range class. Apply the following code to the top button. 2. Let's use this information to pump different types of values (integers. If you select the Range class. which holds a variant value. 4. if you select a Worksheet class. For example. classes. 1. CommandButton1. 3.Figure 1: The Object Browser. and variable types associated with objects. and text) into cells in an opened spreadsheet. Stretch the UserForm and CommandButtons so that they can accommodate the button text. and bottom button. CommandButton3: . it has a Value property. Use the process outlined in the last tutorial to create a UserForm as shown in Figure 2. The Object Browser reports the properties. Add a Microsoft Excel Object Library reference to the form. View Larger Image Figure 2: Create a UserForm as shown.

5. and a text value. Click on the top button to open a spreadsheet. thus returning us to the VBA IDE. but remember. Going Out for the Pass The code for this CommandButton assumes that Excel is already running. Note: Excel will not completely close down until after you've told it not to save the spreadsheet. but the VBA routine is also exited. Let's examine the code for CommandButton2. 1. 4. You can run the routine at this point.column) format and notation. . 3. Click on the middle button to fill the first column with values. a real number. Click the third button to shut down the application and the spreadsheet. once the Excel spreadsheet appears on your screen. Apply the following code to CommandButton2: 2. you must toggle back to your AutoCAD session (use ALT+TAB to move back and forth between the current Excel session and AutoCAD software) to see your UserForm.We added an End command to the code for CommandButton3 so that when this button is clicked. These values are passed to the Excel Worksheet object cell-value property using (row. Run the application now. not only is the current spreadsheet closed. Three variables are established to hold an integer.

With the Format function you can set the formatting for any cell by passing formatted values to the cell. 3. Replace the code for CommandButton2 with the following code: . 4. which you can access from the Excel main menu by selecting Tools > Macro > Visual Basic Editor (see Figure 3). Replace the code for CommandButton3 with the following code.5 was not reported properly in cell 2.Excel VBA IDE AutoCAD software isn't the only application with a VBA IDE. Run the application again. Did you notice that the value 1. which completely closes Excel without first calling a DisplayAlert prompt: 2. clicking on the top button and then the middle button. Microsoft Excel also has a VBA IDE. Quit the application. View Larger Image Figure 3: Accessing the Excel VBA IDE. and we have not instructed Excel to change its formatting once data has been passed to its cells.1? This is because each cell has default formatting. What if you want to close down the Excel spreadsheet without having to click a DisplayAlert dialog box that asks you if you want to save the workbook? Go to the Excel VBA IDE Help facility to find this information (DisplayAlert property of an Application object). 1.

. The resulting values passed to the spreadsheet should look like those shown in Figure 4. 6. Remember to stretch the column width of the first column to accommodate the values passed to it. 7.5. Restart the application. Use the top and middle buttons to send the new values to the spreadsheet.

Figure 4: The values are passed to the spreadsheet. Keeping Up Appearances In addition to cell value formatting. and column widths. Replace the code in CommandButton2 with the following code: . italicizing. 1. you can also control cell sizing. boldfacing.

and the average. 2. Run the application again to see how to control the appearance of values.2. Run the application again to see the effect. Home on the Range Sometimes you will want to pass a value to many cells or to pass a function to a cell for a spreadsheet calculation. The code uses the Range class of the object with a cell range format value and the Formula property of the Range class to assign a formula to a cell. sum. Not much needs to be said here. and a subtraction of values is calculated in adjacent cells. So let's end this segment by examining the code that accomplishes this. . The value of 4 is passed to four cells.

we'll discuss pulling values from an Excel spreadsheet into AutoCAD VBA objects such as ListBoxes and ComboBoxes. and we'll also get our first look at code to survey counts of objects within an AutoCAD drawing and report them in a spreadsheet.Next time. .

Figure 1: A simple sample spreadsheet.VBA: Integrating with Microsoft Excel . which queries an AutoCAD drawing for all user-inserted blocks and reports its findings in a UserForm and a new spreadsheet. Listboxes. The sample application below pulls cell values from this spreadsheet and its cell values into a Textbox. In the first three segments. let's examine the code that connects AutoCAD VBA objects with a preexisting spreadsheet. and a method to pass information from the AutoCAD VBA environment to Excel. a Textbox. I outlined the reasons for merging these two applications. . The code also demonstrates how cell values can be reported in columns for a Combobox. In this segment. and Comboboxes in an AutoCAD UserForm? Suppose that you have an existing spreadsheet with two columns of data in it: the first column lists Block names typically found in your drawings and the second column has a price for each Block. and Comboboxes as shown in Figure 2.Part 4 By dave-espinosa-aguilar This article is the fourth in a series on integrating the programming power of AutoCAD® VBA with the functionality found in other Windows applications—specifically. Listboxes. the procedure for establishing a link between them. Create the spreadsheet shown in Figure 1 and save it in a known directory. By referring to any row in this spreadsheet. and a Combobox. we focus on the reverse process: pulling information from a preexisting Excel spreadsheet into the AutoCAD VBA environment. you could write an AutoCAD VBA routine to find the total cost of all Blocks found in any drawing! Before we build such a neat tool. First examine the simple spreadsheet shown in Figure 1. a Listbox. Microsoft Excel. We also examine our first sample application. insert a UserForm and add CommandButtons. Pulling Values Why might you want to pull values from specific cells in a preexisting Excel spreadsheet into the Textboxes. In a new VBA project. Now apply the sample code to each CommandButton.

Run the application using ALT+TAB to verify the result of each CommandButton when it is clicked. It goes without saying that for any of the remaining sample applications shared in this series.Figure 2: UserForm layout for importing a spreadsheet's cell values. You must modify the path string in the code for the CommandButton that opens the existing spreadsheet to make these subroutines work properly. you must always add a Microsoft Excel Object Library reference before your code can speak "Excelese." . You must also expand the Combobox to see the columnar data pulled from the spreadsheet.


Now that you have an idea of how to move information back and forth between AutoCAD VBA objects and a new or existing spreadsheet. Sample Application: Block Reporter Now things get exciting. It also offers you the option of pumping this tallied information into a new spreadsheet. You can see the utility interface in Figure 3. let's examine our first really powerful yet simple sample application. This small utility surveys a drawing for any user-created Blocks and tallies them for you. these variables are declared publicly in the General Declarations area rather than in each subroutine. to create your Excel reference before running this utility! . The routine first builds a list of all Block names found in the drawing (excluding any that begin with an asterisk) and adds them to a Listbox. At the risk of stating the obvious. Remember. Figure 3: Block Reporter interface. to test this utility. It then cycles through that list of Block names and counts the total number of Block Inserts found for each name. you must either create a new drawing with some blocks in it or open an existing drawing with blocks in it before running it. Since several buttons use the same variable names for accessing Excel objects. too.


In the first segment of this series. I offered several reasons why any AutoCAD or AutoCAD-based product user would even care about this topic of integrating Microsoft Excel functionality with an AutoCAD-based product through AutoCAD VBA. It is the primary focus of the remaining segments of this series to examine and provide several simple yet demonstrative sample applications which point to the full potential of these merged technologies. .Figure 4: The Block Reporter in action.

The interface for the utility is shown in Figure 1. and the code for the interface is provided below the figure. you can select LINE entities. If the layer of a selected LINE has already been gleaned from a previously selected LINE.Part 5 By dave espinosa-aguilar This article is the fifth in a series on integrating the programming power of AutoCAD® VBA with the functionality found in other Windows® applications—specifically. Remember to create a Microsoft® Tool Reference (for example. Previously. and the second ListBox reports those same layer names without duplicates. Sample Application #2: Query Reporter With this application.0 Object Library) before running the utility. As with Sample Application #1 provided in the previous segment. The CommandButton's WordWrap property is set to True to accommodate the button text (see the code below). including the reporting of layer-entity counts using spreadsheet graphics. it is also ignored. creating part counts) and in the previous segment we looked at a sample application that. The first ListBox reports all layers gleaned from all selected LINEs. Figure 1: Interface for Query Reporter. tally the lengths of all lines found on each selected LINE's layer. we've explored the benefits of merging these two technologies (for example. Microsoft Excel 9. in fact. we'll examine two sample applications developed to query drawing data and report findings in spreadsheet format. Microsoft® Excel. In this segment. and we'll examine a truly powerful utility which can externalize data by using a spreadsheet row as an entity ATTRIBUTE substitute. Therefore. global variables used for spreadsheet linking are placed in the General Declarations section. If a non-LINE is selected. and report them to a spreadsheet. it is ignored. generated part counts.VBA: Integrating with Microsoft Excel . this utility shows one way to delete duplicate values found in a ListBox object—a very handy algorithm. .


pipe GPM values. Sample Application #3: Spreadsheet Graphics Reporter Microsoft Excel can present numeric information in ways very different from those found in AutoCAD software. you could use this utility as a way to calculate HVAC venting values. wall surface area values. In building construction drawings. It then creates a new list of layer names without duplicate values. This application shows how you can present layer surveys using Excel graphics. and each LINE's length is added to a total per layer. A list is made of all layers found in the drawing. or electrical wiring lengths. These length totals are passed to the new spreadsheet. The entire drawing database (ModelSpace) is surveyed for LINEs on the layer name list. . and the code for the interface is shown below Figure 3. The interface for the utility is shown in Figure 2. A total entity count for each layer is then calculated and the results are reported in percentages using an Excel Graphics pie chart. Be sure to create several entities on several layers to test this routine.The routine builds a list of layer names from the selected LINEs.

Figure 3: Spreadsheet showing Entity Percentages by Layer. Notice that 13 entities are found on Layer4 (see #5 in Legend).Figure 2: Interface for Spreadsheet Graphics Reporter and a sample drawing. Figure 2 not only shows the interface for this utility. . but also an example drawing in which several POINT entities have been created on various layers. including Layer 0. the spreadsheet shown in Figure 3 is generated. When the utility is run on this drawing. which comprise 40 percent of all point entities found in the drawing.

edited. this application makes it possible for any entity type to "contain ATTRIBUTE values. If a handle value is found in the spreadsheet.Sample Application #4: The Externalizer In the last sample application we'll look at in this segment." In essence. or deleted. then the existing values for that entity can be reported. . we break all the rules in AutoCAD about a BLOCK being the only type of entity that can "contain ATTRIBUTE values. these values are stored in a spreadsheet as rows of cell values. Slick. The application can survey any selected entity for its handle and create a new row of values for it if that handle is not already found in the spreadsheet. Each entity with its own ATTRIBUTES is linked to a unique spreadsheet row by using the entity's handle value (a unique hexadecimal value generated by AutoCAD software at the time of entity creation)." These "ATTRIBUTE values" are not actually created as ATTRIBUTE entities in the drawing. The first cell in any row is dedicated to the handle value of the entity to which it is linked. Instead.

Externalizing ATTRIBUTE data provides a number of other powerful (and perhaps not obvious) benefits: "ATTRIBUTE values" created in this way can be applied to any entity type. Have you ever tried globally editing actual ATTRIBUTE values. too. external reference file.Using this type of utility requires that the spreadsheet of "ATTRIBUTE values" travel with the drawing. the points being made in this series. TextBox1 in the code provided is actually the textbox object for ATTRIBUTE attachment. By naming the spreadsheet file the same file name as a drawing file. The ramifications for "ATTRIBUTE value" editing using this methodology are staggering." Using normal AutoCAD BLOCK objects. extension). shape files. and TextBox2 is the textbox for the complete XLS filename (drive. Each button is self-contained to open and close Excel for its own uses rather than leaving Excel open until the application is terminated. "ATTRIBUTE values" stored in this way can be stored as actual numbers. Now that we have an idea of how this application works logistically and what benefits it can provide us. One inserted BLOCK might hold three "ATTRIBUTE values" while the same BLOCK inserted elsewhere in the drawing might hold 20 "ATTRIBUTE values. You're already used to having font files. so requiring a spreadsheetfile to travel with corresponding drawing files should be no great burden. Unlike a BLOCK which has a fixed number of ATTRIBUTES that can be filled. you can keep related spreadsheets and drawings together. this type of information-packing would be impossible. if you want value order maintained. I told you this AutoCAD VBA/Excel integration stuff gets wild. or currency values. so that the values for attached entities can be edited. regardless of what entity type they're attached to. let's examine the application interface shown in Figure 4 below. not just BLOCKs. There are countless ways to rewrite them more efficiently and more powerfully. and save. A final reminder: these sample applications are created to demonstrate. . and of course you'll need to make a Tools/Reference to Excel to make it work. the drawing itself is much smaller (no ATTRIBUTE entities are in it). file name. so the drawing is faster to load." you can mix the order of values in any way you choose. ATTRIBUTEs in AutoCAD have only been able to store values as strings (an ATTRIBUTE value of 100 was not stored as a numeric value of 100 but as a word value of "100"). in different ATTRIBUTE tags across different BLOCK insertions. the real power of this application is its ability to externalize ATTRIBUTE data to an Excel spreadsheet. queried. If it isn't obvious already. a spreadsheet can hold virtually unlimited "ATTRIBUTE values" for any entity since its values are stored as unlimited cell values in a dedicated row. improved processes sometimes require new standards! This application is provided as a glimpse of the kinds of things that can be accomplished with Excel and AutoCAD VBA: the routine could be modified in countless ways to extend this ATTRIBUTE power even further. Hey. and so on. in a drawing all at once? It's a piece of cake with Excel using Search and Replace functions on cells throughout a spreadsheet. processed in formulas. "ATTRIBUTE values" in a spreadsheet can actually be added to each other. With a spreadsheet used for "ATTRIBUTE values. and other file types travel with their corresponding drawings. This utility does not declare public variables. directory. Wow! "ATTRIBUTE values" stored in this fashion can be edited in Excel without AutoCAD software even running! If "ATTRIBUTE values" for an entity are edited in Excel. Storing "ATTRIBUTE values" in this way means that ATTRIBUTEs could hold formulas! Don't even get me started on how wild this gets. I wasn't kidding. the next time AutoCAD is launched and that entity is surveyed with this VBA utility. Because the ATTRIBUTE values are stored outside the drawing. The utility requires some existing drawing entities already in place in order to have "ATTRIBUTE values" attached to them. or dates if needed! Up until now. the updated "ATTRIBUTE values" will be reported properly. edit. not optimize. or even evaluated against calendars! How many years have you been waiting for this capability? BLOCK ATTRIBUTE values always use the same ATTRIBUTE value order. You can create a cell/ATTRIBUTE sequence standard so that values always report in the same order. The essential goal behind them is to make clear their potential to the reader.

If it finds the handle. the Reporting function will bring up an alert if values do not exist for a selected entity (meaning there is currently no dedicated row for it in the spreadsheet). The Attachment button searches the spreadsheet for the handle of a selected entity. it attaches the new value in TextBox1 (within the frame) to the end of the handle row. a new row is linked with the handle and the value is placed to the right of it.In this application. Figure 4: The interface for the Externalizer. If a spreadsheet does not exist with the same file name of the current drawing. which has the selected entity's handle value. The Delete Attribute function clears a linked row with previously reported ListBox values except for a required single selected value. all row values are listed in the ListBox. If a handle does not exist. by default a new spreadsheet is created bearing the same name as the drawing. The Clear All Attributes function deletes (using the xlShiftUp function) the entire linked row. If an entity has a corresponding row of information in the spreadsheet. .







Conclusion There are many ways to externalize data in a drawing besides moving ATTRIBUTE data into a spreadsheet format. and title-block data are examples of other information that might be well suited to a spreadsheet format. schedules. especially considering the more powerful text-formatting control available in Excel. enjoy tweaking the applications we covered in this article! . we will examine more sample applications which further illustrate just how valuable integrating these technologies can be. In the meantime. Large notes. In the final segment of this series.

The names of four drawing blocks appear in column A. The spreadsheet itself specifies the query criteria since only those blocks listed in column A are searched for in the drawing. is fairly straightforward. You'll need to activate an Excel Object Library Reference as usual.Part 6 By dave espinosa-aguilar This article is the last in a series on integrating the programming power of AutoCAD® VBA with the functionality found in other Windows applications—specifically. Sample Application #5: Cost Analysis Examine the pricing index spreadsheet in Figure 1. Figure 1: A block pricing-index spreadsheet. Listboxes report block names. . This application searches for occurrences of these four blocks in any drawing. and the Grand Total appears in the Grand Total text box. In the five previous segments. You could easily tailor this application to search for other entity types found on specified layers. The interface for this application. calculates their cost. The application reads all values found in column A until it finds an empty cell. we looked at some of the productivity benefits that arise from merging these two technologies. it adds up these costs and delivers a grand total. These samples included automated part counts and graphical and textual reporting of entity counts and properties.VBA: Integrating with Microsoft Excel . shown in Figure 2. Microsoft® Excel. quantities. Figure 2 shows the application running with blocks in a drawing. Previous sample applications have also shown how this data itself can be exported to a spreadsheet report. dates. and a corresponding price for each block appear in column B. Anyone can generate a new pricing index sheet or edit an existing one to perform this type of cost analysis. and so on to it. In this final segment. you'll need corresponding block insertions in a drawing. Part 5 of this series demonstrated a totally new productivity concept: how to externalize attribute data to a spreadsheet so that you can reduce drawing size and edit attribute values outside of AutoCAD software. and totals. we examine sample applications that do cost analysis using a pricing index spreadsheet and layer delegation based on a drawing block's attribute values. currency. This process also provides a way to treat attribute data as more than a string by enabling you to assign numeric values. prices by block name. Finally. and I provided several sample applications to demonstrate them. and it goes without saying that to test this application. The spreadsheet file name is specified in the Price Spreadsheet text box. Next it multiplies this quantity by the corresponding block price found in column B to arrive at a total cost for each block named in the spreadsheet. It then searches the drawing and reports the number of instances of each block it finds. and provides a grand total.

the Layer Delegator sample application sends drawing blocks to new layers based on block attribute values. Blocks with a single attribute (indicating a numeric value) created on Layer 0 are compared with ranges specified in column A (minimum) and column B (maximum) of the spreadsheet. Here's the code for this sample application: View Larger Image Sample Application #6: Layer Delegator With an application of this type. you can examine information contained in an AutoCAD entity according to criteria specified in a spreadsheet and then treat that data accordingly in AutoCAD. and then moved to a corresponding layer name in Column C. In brief. .Figure 2: Cost-analysis interface along with block insertions.

xls spreadsheet. The application searches for all insertions of the block whose name is entered in the "Block name to treat" text box. Figure 3: Minimum and maximum attribute values and layer. Figure 3 shows the spreadsheet used for defining ranges and assigning layers.By changing the spreadsheet column values. Here's the code for this sample application: View Larger Image When you run this application. this sample application demonstrates how you can use a spreadsheet to analyze and modify AutoCAD entities for AutoCAD-based reporting. Figure 4: Application interface shown with blocks after conversion. Figure 4 shows the interface for the application and three blocks originally created on Layer 0 converted to new layers based on their single attribute value. and then assigns them to new layers based on what range they fall in. you can delegate blocks to practically any Layering standard at any time with no entity picking whatsoever. The layers of all three blocks could easily be reset to Layer 0. . line type. You could easily modify this application to control the new layer assignment color. Again. or even whether the block is visible. and you could set up new ranges with new layer names in the ranges. the block with value 120 to layer200. the block with value 34 is moved to layer100. and the block with value 270 to layer300. This functionality has strong potential for facilities management applications.

can provide new and powerful ways to get work completed. Check them out. If you have Microsoft Excel loaded on your AutoCAD system—put it to work! . to optimize AutoCAD performance and expand its capabilities. AutoCAD VBA. Numerous VBA forums on the Internet these days are populated by AutoCAD VBA users willing to discuss the unlimited possibilities of automating your work.Conclusion Some things aren't worth waiting around for when you can easily build them yourself. when combined with Microsoft Excel. and to report information found in AutoCAD more intuitively. You can easily modify and/or adapt the sample applications presented in this series to meet your own office's unique work processes. Spend some time examining how you normally get work done on any given day and ask yourself if there are ways in which Excel might be able to give you a hand.

Sign up to vote on this title
UsefulNot useful