Explorar E-books
Categorias
Explorar Audiolivros
Categorias
Explorar Revistas
Categorias
Explorar Documentos
Categorias
Este artigo o primeiro de uma srie sobre como integrar o poder de programao do AutoCAD
VBA com a funcionalidade encontrada em outros aplicativos do Windows especificamente,
o Microsoft Excel. Atravs de programao AutoCAD Visual Basic, voc pode iniciar o Excel e
trazer todo o poder de um aplicativo de planilha em uma sesso de desenho do AutoCAD. As
informaes nesta srie iro demonstrar como gerar, organizar, consulta e extrair linework
visivelmente ou nos bastidores durante uma sesso do AutoCAD sem gastar um centavo em
compiladores adicionais ou documentao. Se voc tem o AutoCAD e o Microsoft Excel j
carregado na sua estao de trabalho, esta tecnologia est pronto e esperando por voc tirar
vantagem disso.
Para entrar no mundo da programao Visual Basic e adicionar funcionalidade do Excel para o
software AutoCAD, voc tem que estar disposto a gastar o tempo que leva para dominar esta
ferramenta de programao orientada a objeto. Mesmo que voc programou em AutoLISP
antes, Visual Basic como no perdoar ou acomodando, e as regras que devem ser obeyed por
tudo a trabalhar bem, quando voc executar seus prprios aplicativos VB so muito rgidas. Isso
no quer dizer que um programador de AutoLISP no pode conquistar o mundo do Visual Basic;
demora mais dedicao e esforo.
Ento, como com qualquer investimento srio de seu tempo, vale a pena recuar e examinar o que
ficar a par do Visual Basic (e a integrao do AutoCAD VBA e o Microsoft Excel) traz para a
sua mesa em primeiro lugar. Quanto mais voc aprender sobre o software que voc j possui,
fica mais poderoso e o mais impacto que est a ter na sua produtividade. Se a natureza de seus
desenhos e projetos presta-se a funcionalidade de planilha, ento considere deixando de lado as
noes de pr em marcha o cdigo, e vai Zen com um pouco como podemos considerar algumas
perguntas potencialmente profundas... comeando com "por que deve qualquer usurio
AutoCAD conta que a integrao do AutoCAD e o Microsoft Excel possvel?"
Reason #1: Automated Fully Customizable Part Counts
Voc j contou entidades em um desenho manualmente? Por isso eu queria perguntar tem voc
sempre (com seu dedo ou lpis) registrou cada espao de estacionamento ou cada cadeira ou
cada casa de banho em um banheiro ou uma janela em uma parede exterior do edifcio ou cada
dispositivo eltrico de HVAC em toda uma srie de planos de telhado? Tem todos os aspersores
contados ou ajardinar recursos por tipo de planta, parafusos ou parafusos para um assembly, ou
plano de datapoints para um determinado site? Imagine-se pressionando um boto de menu e
sendo feito com o processo!
Reason #2: Queries
Talvez voc usar blocos com atributos. Voc sempre quis que voc poderia contar blocos (ou
talvez nem selecion-las) com base nos valores desses atributos? Talvez voc usar dados
entidade estendida, que decorra de montes de informaes exclusivas de entidades individuais.
No seria slick se houvesse uma maneira fcil de levar a soma ou mdia dessas informaes em
segundos?
Existem alguns truques engenhosos e tcnicas como por a usando o velho SSX.Rotina LSP, o
comando de filtro interno e vrias outras funes de filtragem em AutoCAD, isolamentos de
camada, a extrao de atributo de bloco extatrib de comando CDF/SDF e selecione-objetos bsicos
at tcnicas para relatar a entidade conta em um desenho. Mas nenhum deles chegou perto a
relatrios, consulta e controle de anexo que um aplicativo de planilha vinculado pode oferecer.
Quero especificar o nome de um bloco com um valor de atributo que cai em um determinado intervalo
numrico e ter essas entidades reunio que critrios relataram com formatao de texto completo em
um modelo de planilha real? Voc pode com VBA. Imagine a relatar informaes de atributo ou dados
de entidade estendida de entidades com base em sua localizao no desenho ou mesmo baseada na
maneira em que eles esto sendo usados ou foram originalmente gerados (por exemplo, contagem de
todos os blocos chamados "x" que foram inseridas pelo operador de CAD "y", durante o ms de "z" do
ano passado). Se voc um guru de SQL, voc realmente poderia consultar blocos com dados de
atributo usando uma instruo de consulta SQL inteiramente atravs do VBA.
Reason #3: Portability and Data Reporting
Existem pessoas em seu escritrio que usam o Excel com a mesma proficincia impressionante que voc
use o software AutoCAD? Alguma vez voc j quis compartilhar suas informaes de AutoCAD com eles
em um formato com o qual eles facilmente podem trabalhar? Atravs da codificao, voc pode converter
qualquer tipo de informao do AutoCAD em um formato que fala a lngua do outro aplicativo Windows.
Voc pode traduzir sua base de vetor em uma base de grade ou uma base de registro. Voc pode exibir,
relatar e analisar desenhos com todos os habituais analticos sinos e assobios em uma planilha
(fluxogramas, diagramas de torta, grficos de tendncias e assim por diante) para que usurios noAutoCAD usando seus mtodos de relatrios nativos e suas ferramentas grficas nativas podem
facilmente entender que dados do AutoCAD
.
Figure 1: Creating a schedule even this simple is time-consuming to construct and tally without a
spreadsheet.
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.
The IDE
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
At the command prompt,
AutoCAD.
Figure 2: The VBA Manager Dialog loads, unloads, and exports application code.
Figure 5: Adding the Microsoft Excel 9.0 Object Library reference enables your application
to speak "Excel-ese."
the various objects in the Toolbox dialog box and pay close attention to the
tooltips. Find the tool with tooltip CommandButton and click it. Your cursor changes to CommandButton
draw mode.
1. Move your cursor over
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.
2. Likewise, 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. The code for this object begins by dimensioning variable excelApp as an Excel
application object type, variable wbkObj as an Excel Workbook object type, and variable shtObj as an Excel Worksheet object type (all three of which
are types now available to us with the excel 9.0 Object Library referenced). If any error occurs, the code is instructed to continue on instead of
stopping at the error. The UserForm is hidden from view and the error state variable is cleared (set to a value of zero). Here's the relevant code:
Next, the application variable is set to a currently running session of Excel. This may seem a little weird at first, but the code does not start by
launching Excel. Now, if Excel isn't running, this statement generates an error (which has a nonzero value). If an error is generated, then we know that
Excel isn't running yet. So we clear the error state and use the CreateObject function to launch an Excel session. So we're essentially saying "If Excel is
already running, set the variable to what is running. Otherwise, start up Excel." If launching Excel generates an error, we know that Excel isn't even
installed. We report this through a message box exclamation function and end the program. Here's that code:
Once the application variable is set to either the currently running session of Excel or a new session of Excel, the UserForm is made visible again, and
the workbook and worksheet variables are set to the first workbook and the first worksheet in that session. This done, the UserForm is made visible
again so that we can click the buttons to close Excel down or quit our VBA program. Here's that code:
The code for the Close Excel button is fairly imitative of that for the Launch Excel button. Variable excelApp is dimensioned from scratch again in
this procedure as an Excel application object type. The code is instructed again to continue if an error is encountered, the UserForm is hidden, and the
error state is cleared. Variable excelAPP is set to an assumed already running session of Excel. If Excel isn't running (someone may click Close Excel
firstafter all, you have to consider every possibility), an error is generated, and we are told Excel isn't running. If no error is generated, then the
application quits. The UserForm is made visible again so that we can click our three buttons:
When running this VBA routine, it helps to use ALT+TAB to switch between Excel and AutoCAD after Excel has been launched. Viewing the
Windows Task Manager (CTL+ALT+DEL) is also helpful to check if you've left any Excel application open. 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 should see an icon for the currently running
Excel session. 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, how to format that passed information, and how to channel
it to a single cell or multiple cells and ranges. We'll also look at how to pull information from a spreadsheet into a UserForm list box, edit box, combo
box, and so on. For now, make sure you understand clearly how to make the Excel connection.
The Object Browser reports the properties, classes, and variable types associated with objects. For example, if you
select a Worksheet class, it has a Cells property as a Range class. If you select the Range class, it has a Value
property, which holds a variant value. Let's use this information to pump different types of values (integers, real
numbers, and text) into cells in an opened spreadsheet.
1. Use the process outlined in the last tutorial to create a UserForm as shown in Figure 2.
2. Add a Microsoft Excel Object Library reference to the form.
3. Stretch the UserForm and CommandButtons so that they can accommodate the button text.
4. Apply the following code to the top button, CommandButton1, and bottom button, CommandButton3:
We added an End command to the code for CommandButton3 so that when this button is clicked, not only is the
current spreadsheet closed, but the VBA routine is also exited, thus returning us to the VBA IDE. You can run the
routine at this point, but remember, once the Excel spreadsheet appears on your screen, 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. Let's examine the code for CommandButton2.
Going Out for the Pass
The code for this CommandButton assumes that Excel is already running. Three variables are established to hold
an integer, a real number, and a text value. These values are passed to the Excel Worksheet object cell-value
property using (row,column) format and notation.
1. Apply the following code to CommandButton2:
Figure 3).
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. Replace the code for CommandButton3 with the following code, which completely closes Excel without first
calling a DisplayAlert prompt:
2. Run the application again, clicking on the top button and then the middle button.
Did you notice that the value 1.5 was not reported properly in cell 2,1? This is because each cell has default
formatting, and we have not instructed Excel to change its formatting once data has been passed to its cells. With
the Format function you can set the formatting for any cell by passing formatted values to the cell.
3. Quit the application.
4. Replace the code for CommandButton2 with the following code:
Keeping Up Appearances
In addition to cell value formatting, you can also control cell sizing, boldfacing, italicizing, and column widths.
1. Replace the code in CommandButton2 with the following code:
2. Run the application again to see how to control the appearance of values.
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.
So let's end this segment by examining the code that accomplishes this.
Next time, 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.
on the
reverse process: pulling information from a preexisting Excel spreadsheet into the AutoCAD VBA environment.
We also examine our first sample application, which queries an AutoCAD drawing for all user-inserted blocks and
reports its findings in a UserForm and a new spreadsheet.
Pulling Values
Why might you want to pull values from specific cells in a preexisting Excel spreadsheet into the Textboxes,
Listboxes, 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. By referring to any row in this spreadsheet, 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, let's examine the code that connects AutoCAD VBA objects with a preexisting
spreadsheet. First examine the simple spreadsheet shown in Figure 1.
The sample application below pulls cell values from this spreadsheet and its cell values into a Textbox, a Listbox,
and a Combobox. The code also demonstrates how cell values can be reported in columns for a Combobox.
Create the spreadsheet shown in Figure 1 and save it in a known directory. In a new VBA project, insert a
UserForm and add CommandButtons, a Textbox, Listboxes, and Comboboxes as shown in Figure 2. 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. 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 also expand the Combobox to see the columnar data pulled from the
spreadsheet. It goes without saying that for any of the remaining sample applications shared in this series, you
must always add a Microsoft Excel Object Library reference before your code can speak "Excelese."
Now that you have an idea of how to move information back and forth between AutoCAD VBA objects and a new
or existing spreadsheet, let's examine our first really powerful yet simple sample application.
Sample Application: Block Reporter
Now things get exciting. This small utility surveys a drawing for any user-created Blocks and tallies them for you. It
also offers you the option of pumping this tallied information into a new spreadsheet. 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. It then cycles through that list of Block names and counts the total number of Block Inserts found for
each name. Since several buttons use the same variable names for accessing Excel objects, these variables are
declared publicly in the General Declarations area rather than in each subroutine. You can see the utility interface in
Figure 3.
At the risk of stating the obvious, to test this utility, you must either create a new drawing with some blocks in it or
open an existing drawing with blocks in it before running it. Remember, too, to create your Excel reference before
running this utility!
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.
The routine builds a list of layer names from the selected LINEs. It then creates a new list of layer names without
duplicate values. The entire drawing database (ModelSpace) is surveyed for LINEs on the layer name list, and
each LINE's length is added to a total per layer. These length totals are passed to the new spreadsheet. In building
construction drawings, you could use this utility as a way to calculate HVAC venting values, pipe GPM values,
wall surface area values, or electrical wiring lengths.
Sample Application #3: Spreadsheet Graphics Reporter
Microsoft Excel can present numeric information in ways very different from those found in AutoCAD software.
This application shows how you can present layer surveys using Excel graphics. A list is made of all layers found
in the drawing. A total entity count for each layer is then calculated and the results are reported in percentages
using an Excel Graphics pie chart. The interface for the utility is shown in Figure 2, and the code for the interface is
shown below Figure 3. Be sure to create several entities on several layers to test this routine.
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. When the utility is run on this drawing, the spreadsheet
shown in Figure 3 is generated. Notice that 13 entities are found on Layer4 (see #5 in Legend), which comprise 40
percent of all point entities found in the drawing.
Using this type of utility requires that the spreadsheet of "ATTRIBUTE values" travel with the drawing, so that
the values for attached entities can be edited, queried, and so on. You're already used to having font files, shape
files, external reference file, and other file types travel with their corresponding drawings, so requiring a
spreadsheetfile to travel with corresponding drawing files should be no great burden. By naming the spreadsheet
file the same file name as a drawing file, you can keep related spreadsheets and drawings together. Hey, 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.
If it isn't obvious already, the real power of this application is its ability to externalize ATTRIBUTE data to an
Excel spreadsheet. Because the ATTRIBUTE values are stored outside the drawing, the drawing itself is much
smaller (no ATTRIBUTE entities are in it), so the drawing is faster to load, edit, and save. 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, not just BLOCKs. 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, the next time AutoCAD is launched and that
entity is surveyed with this VBA utility, the updated "ATTRIBUTE values" will be reported properly.
Have you ever tried globally editing actual ATTRIBUTE values, in different ATTRIBUTE tags across
different BLOCK insertions, in a drawing all at once? It's a piece of cake with Excel using Search and Replace
functions on cells throughout a spreadsheet. The ramifications for "ATTRIBUTE value" editing using this
methodology are staggering.
Storing "ATTRIBUTE values" in this way means that ATTRIBUTEs could hold formulas! Don't even get
me started on how wild this gets.
Unlike a BLOCK which has a fixed number of ATTRIBUTES that can be filled, a spreadsheet can hold
virtually unlimited "ATTRIBUTE values" for any entity since its values are stored as unlimited cell values in a
dedicated row. One inserted BLOCK might hold three "ATTRIBUTE values" while the same BLOCK inserted
elsewhere in the drawing might hold 20 "ATTRIBUTE values." Using normal AutoCAD BLOCK objects, this
type of information-packing would be impossible.
"ATTRIBUTE values" stored in this way can be stored as actual numbers, or currency values, or dates if
needed! Up until now, 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"). "ATTRIBUTE values" in a
spreadsheet can actually be added to each other, processed in formulas, 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. With a spreadsheet used for
"ATTRIBUTE values," you can mix the order of values in any way you choose, regardless of what entity type
they're attached to. You can create a cell/ATTRIBUTE sequence standard so that values always report in the
same order, too, if you want value order maintained.
I told you this AutoCAD VBA/Excel integration stuff gets wild. I wasn't kidding. Now that we have an idea of how
this application works logistically and what benefits it can provide us, let's examine the application interface
shown in Figure 4 below. TextBox1 in the code provided is actually the textbox object for ATTRIBUTE
attachment, and TextBox2 is the textbox for the complete XLS filename (drive, directory, file name, extension).
The utility requires some existing drawing entities already in place in order to have "ATTRIBUTE values"
attached to them, and of course you'll need to make a Tools/Reference to Excel to make it work. This utility does
not declare public variables. Each button is self-contained to open and close Excel for its own uses rather than
leaving Excel open until the application is terminated.
A final reminder: these sample applications are created to demonstrate, not optimize, the points being made in this
series. There are countless ways to rewrite them more efficiently and more powerfully. The essential goal behind
them is to make clear their potential to the reader.
In this application, 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). If an entity has a corresponding row of
information in the spreadsheet, all row values are listed in the ListBox. The Attachment button searches the
spreadsheet for the handle of a selected entity. If it finds the handle, it attaches the new value in TextBox1 (within
the frame) to the end of the handle row. If a handle does not exist, a new row is linked with the handle and the
value is placed to the right of it.
If a spreadsheet does not exist with the same file name of the current drawing, by default a new spreadsheet is
created bearing the same name as the drawing. The Delete Attribute function clears a linked row with previously
reported ListBox values except for a required single selected value. The Clear All Attributes function deletes
(using the xlShiftUp function) the entire linked row, which has the selected entity's handle value.
Conclusion
There are many ways to externalize data in a drawing besides moving ATTRIBUTE data into a spreadsheet
format. Large notes, schedules, and title-block data are examples of other information that might be well suited to
a spreadsheet format, especially considering the more powerful text-formatting control available in Excel. In the
final segment of this series, we will examine more sample applications which further illustrate just how valuable
integrating these technologies can be.
In the meantime, enjoy tweaking the applications we covered in this article!
to a
spreadsheet so that you can reduce drawing size and edit attribute values outside of AutoCAD software. This
process also provides a way to treat attribute data as more than a string by enabling you to assign numeric values,
currency, dates, and so on to it. In this final segment, we examine sample applications that do cost analysis using a
pricing index spreadsheet and layer delegation based on a drawing block's attribute values.
Sample Application #5: Cost Analysis
Examine the pricing index spreadsheet in Figure 1. The names of four drawing blocks appear in column A, and a
corresponding price for each block appear in column B. This application searches for occurrences of these four
blocks in any drawing, calculates their cost, and provides a grand total. The spreadsheet itself specifies the query
criteria since only those blocks listed in column A are searched for in the drawing. You could easily tailor this
application to search for other entity types found on specified layers.
The application reads all values found in column A until it finds an empty cell. It then searches the drawing and
reports the number of instances of each block it finds. 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. Finally, it adds up these
costs and delivers a grand total. Previous sample applications have also shown how this data itself can be exported
to a spreadsheet report. Anyone can generate a new pricing index sheet or edit an existing one to perform this type
of cost analysis.
The interface for this application, shown in Figure 2, is fairly straightforward. Listboxes report block names,
quantities, prices by block name, and totals. The spreadsheet file name is specified in the Price Spreadsheet text
box, and the Grand Total appears in the Grand Total text box. You'll need to activate an Excel Object Library
Reference as usual, and it goes without saying that to test this application, you'll need corresponding block
insertions in a drawing. Figure 2 shows the application running with blocks in a drawing.
By changing the spreadsheet column values, you can delegate blocks to practically any Layering standard at any
time with no entity picking whatsoever. Figure 3 shows the spreadsheet used for defining ranges and assigning
layers. 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. The application searches for all insertions of the block whose
name is entered in the "Block name to treat" text box, and then assigns them to new layers based on what range
they fall in.
When you run this application, the block with value 34 is moved to layer100, the block with value 120 to layer200,
and the block with value 270 to layer300. The layers of all three blocks could easily be reset to Layer 0, and you
could set up new ranges with new layer names in the ranges.xls spreadsheet.
Again, this sample application demonstrates how you can use a spreadsheet to analyze and modify AutoCAD
entities for AutoCAD-based reporting. You could easily modify this application to control the new layer
assignment color, line type, or even whether the block is visible. This functionality has strong potential for
facilities management applications.
Conclusion
Some things aren't worth waiting around for when you can easily build them yourself. AutoCAD VBA, when
combined with Microsoft Excel, can provide new and powerful ways to get work completed, to optimize AutoCAD
performance and expand its capabilities, 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.
Numerous VBA forums on the Internet these days are populated by AutoCAD VBA users willing to discuss the
unlimited possibilities of automating your work. Check them out. If you have Microsoft Excel loaded on your
AutoCAD systemput it to work!