SlideShare a Scribd company logo
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, Microsoft Excel. In the first segment we discussed what was possible, 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, and in this session we
discuss how to port formatted data from AutoCAD VBA to Excel worksheets.
Objects of Our Desire
Now that you know how to make an AutoCAD VBA routine speak "Excel-ese," and
how to launch a session of Excel, let's examine the Workbook and the Worksheet
objects in Excel.
You can study the properties of these and other Excel objects through the AutoCAD
VBA IDE (integrated development environment) by:
1. Running the IDE (use the VBAIDE command).
2. 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.
3. 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).
Figure 1: The Object Browser.
View Larger
Figure 2: Create a UserForm as shown.
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:
2. Run the application now.
3. Click on the top button to open a spreadsheet.
4. Click on the middle button to fill the first column with values.
5. Click the third button to shut down the application and the spreadsheet.
Note: Excel will not completely close down until after you've told it not to
save the spreadsheet.
Excel VBA IDE
AutoCAD software isn't the only application with a VBA IDE. Microsoft Excel also
has a VBA IDE, which you can access from the Excel main menu by selecting Tools
> Macro > Visual Basic Editor (see Figure 3).
View Larger
Figure 3: Accessing the Excel VBA IDE.
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:
5. Restart the application.
6. Use the top and middle buttons to send the new values to the spreadsheet.
7. Remember to stretch the column width of the first column to accommodate the
values passed to it.
The resulting values passed to the spreadsheet should look like those shown in Figure
4.
Figure 4: The values are passed to the spreadsheet.
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.
2. Run the application again to see the effect.
Not much needs to be said here. 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.
The value of 4 is passed to four cells, and the average, sum, and a subtraction of
values is calculated in adjacent cells.
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.
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).
The 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
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.
Figure 2: The VBA Manager Dialog loads, unloads, and exports application code.
Our First User Program
Rather than try to explain every button and function in these interfaces, we're going to
go straight to developing our very first program. It's objective is simple enough: open
and close Excel. Make sure you have Excel already installed on your system, and then
follow along as we begin to develop our first application:
1. Start by making sure you're in a brand new AutoCAD session.
2. Use the VBAMAN command to bring up the VBA Manager dialog box.
3. Click the New button. This creates a new project with a default project name
(ACADProject)
4. Click the Visual Basic Editor button to go to the IDE.
5. Enter Control+R or select Project Explorer from the View pull-down menu to view
the Project Explorer. It may be docked to one side of your window or it may be a
floating window. In either case, it should be reporting your ACADproject.
6. If the project name displays a + (plus) sign to the left, click on the plus sign to see
subitem ThisDrawing (see Figure 3).
Figure 3: The project window reports projects loaded, and UserForms included in a
project.
View Larger
Figure 4: A UserForm is created for the application. The Project window and
Toolbox are organized for easy object placement.
7. From the Insert pull-down menu, select UserForm pull-down to insert a UserForm
into this project. Stretch the UserForm dialog box and the window the UserForm sits
in so that they take up approximately the space shown in Figure 4.
8. From the View pull-down menu select Toolbox, which opens the Toolbox dialog
box. You can also stretch the Toolbox dialog box.
Setting Up an Excel Reference
Once you've added the UserForm to the project, the next step is telling AutoCAD
software how to speak Excel-ese. References expand AutoCAD VBA to include new
tools and capabilities, and for this application we need to be able to speak in terms of
worksheets, cells, ranges, and other concepts associated with spreadsheets. Here's
how we do it:
1. From the Tools pull-down menu, select References, which brings up the References
dialog box.
2. Several references at the top of the Available References list may already be
selected. Leave them as they are, and search down through the list of available
references until you see one that looks like Microsoft Excel 9.0 Object Library (this
assumes Microsoft Excel 2000 is already installed). Select the box to the left of the
Library as shown in Figure 5. When you do this, the Location label at the bottom of
the dialog box should report a path similar to c:Program FilesMicrosoft
OfficeOfficeEXCEL9.OLB.
Figure 5: Adding the Microsoft Excel 9.0 Object Library reference enables your
application to speak "Excel-ese."
3. Click the OK button, which returns you to the IDE.
That's all it takes to expand our application to speak in Excel terms.
Adding Buttons to the UserForm
Now that you've told the application how to speak Excel-ese, let's create some buttons
on our UserForm dialog box that launch Excel, close Excel, and Quit out of our
application. Here we go:
1. Move your cursor over 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.
View Larger
Figure 6: You can re-organize the look and layout of your application and
development interfaces at any time.
2. Move your cursor over the UserForm and pick an upper-left point. This will spot a
button on the UserForm. Click and drag on the button grips to stretch it into any size
you like. Create two more buttons and stretch them so that they appear similar to those
shown in Figure 6.
3. Slowly click twice over a button to move the cursor inside the button, enabling you
to change the button's label.
If you click twice too quickly, a code window will appear instead. Close out any code
windows that appear and try again if necessary, clicking slowly inside each button to
move the cursor into the button text.
4. Change the label for each button so that CommandButton1 text reads Launch Excel,
CommandButton2 text reads Close Excel, and CommandButton3 text reads Quit as
shown in Figure 7.
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.
Your First Coded Object
Now that you have finished the dialog box, it's time assign code to each button.
Again, we're going to start very simple by writing the code for the Quit button.
1. Double-click the Quit button to bring up the button's code window.
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. In the
upper-right corner of the code window is another combo box with value Click, which
tells you that the code will be called up when this button is clicked while the
application is running. In the main part of the code window are two already typed
statements:
Private Sub CommandButton3_Click()
End Sub
2. 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. The END command in Visual Basic
terminates a running application. We're going to run our little program and use this
button to stop it. The indenting of the command isn't vital to the program running
correctly, but it does help keep command statements visually organized.
3. Close the code window.
4. From the Run pull-down menu, select Run Sub > UserForm menu item to launch
our program.
Your dialog box should appear over your AutoCAD session. Clicking on the upper
two buttons will do nothing, but if you click the Quit button, you should return to the
IDE.
5. Click the Quit button to terminate the program.
You just ran your first program! You can also run a program by typing the F5 key
when you are in the IDE.
Launching and Closing Excel
This next part is going to take some explaining. But first, let's get the code for the top
two buttons assigned.
1. Double-click the Launch Excel button to bring up its code window and type the
following code into it:
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 first—after 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.
•

More Related Content

What's hot

Meher Baba - Discourses 7th ed (452p).pdf
Meher Baba - Discourses 7th ed (452p).pdfMeher Baba - Discourses 7th ed (452p).pdf
Meher Baba - Discourses 7th ed (452p).pdf
Bruno Antunes
 
Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 Macros
Emmett Ross
 
AutoCAD 3D Introduction.pptx
AutoCAD 3D Introduction.pptxAutoCAD 3D Introduction.pptx
AutoCAD 3D Introduction.pptx
Gulshan Kumar
 
Estetica y-belleza,-proporcion-aurea-2017
Estetica y-belleza,-proporcion-aurea-2017Estetica y-belleza,-proporcion-aurea-2017
Estetica y-belleza,-proporcion-aurea-2017
YayoMefui
 
Perspectiva isométrica
Perspectiva isométricaPerspectiva isométrica
Perspectiva isométricaPatricia_05
 
U 1 ING IND cecy
U 1 ING IND cecy U 1 ING IND cecy
U 1 ING IND cecy
cecymendozaitnl
 
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование....NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
NETFest
 
Normas dibujo tecnico
Normas dibujo tecnicoNormas dibujo tecnico
Normas dibujo tecnico
GeNaVa12
 
BE sem 1 Engineering Graphics(E.G.) full course ppt
BE sem 1 Engineering Graphics(E.G.) full course pptBE sem 1 Engineering Graphics(E.G.) full course ppt
BE sem 1 Engineering Graphics(E.G.) full course ppt
Dhruv Parekh
 
AutoCAD 2020 Toolsets
AutoCAD 2020 ToolsetsAutoCAD 2020 Toolsets
AutoCAD 2020 Toolsets
lordj78
 
Learn CATIA V5 in 3DEXPERIENCE 2017x
Learn CATIA V5 in 3DEXPERIENCE 2017xLearn CATIA V5 in 3DEXPERIENCE 2017x
Learn CATIA V5 in 3DEXPERIENCE 2017x
Antonio Napolitano
 
Introduction to CATIA
Introduction to CATIAIntroduction to CATIA
Introduction to CATIA
Rahul Kumar
 
Catia sketcher workbench
Catia  sketcher workbenchCatia  sketcher workbench
Catia sketcher workbench
Jayesh Sarode
 
Vistas taller
Vistas tallerVistas taller
Vistas taller
Lic. Oney Begambre
 
Anforderungsanalyse - Grundlagen und Prototyping
Anforderungsanalyse - Grundlagen und PrototypingAnforderungsanalyse - Grundlagen und Prototyping
Anforderungsanalyse - Grundlagen und PrototypingChristian Baranowski
 
Facade Design Pattern
Facade Design PatternFacade Design Pattern
Facade Design Pattern
Livares Technologies Pvt Ltd
 
Engineering drawing graphics
Engineering drawing graphics Engineering drawing graphics
Engineering drawing graphics
Selva Prakash
 
Engineering Graphics
Engineering GraphicsEngineering Graphics
Engineering Graphics
SINY MARY LONA
 

What's hot (20)

Meher Baba - Discourses 7th ed (452p).pdf
Meher Baba - Discourses 7th ed (452p).pdfMeher Baba - Discourses 7th ed (452p).pdf
Meher Baba - Discourses 7th ed (452p).pdf
 
Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 Macros
 
AutoCAD 3D Introduction.pptx
AutoCAD 3D Introduction.pptxAutoCAD 3D Introduction.pptx
AutoCAD 3D Introduction.pptx
 
Estetica y-belleza,-proporcion-aurea-2017
Estetica y-belleza,-proporcion-aurea-2017Estetica y-belleza,-proporcion-aurea-2017
Estetica y-belleza,-proporcion-aurea-2017
 
Perspectiva isométrica
Perspectiva isométricaPerspectiva isométrica
Perspectiva isométrica
 
U 1 ING IND cecy
U 1 ING IND cecy U 1 ING IND cecy
U 1 ING IND cecy
 
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование....NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование...
 
Normas dibujo tecnico
Normas dibujo tecnicoNormas dibujo tecnico
Normas dibujo tecnico
 
BE sem 1 Engineering Graphics(E.G.) full course ppt
BE sem 1 Engineering Graphics(E.G.) full course pptBE sem 1 Engineering Graphics(E.G.) full course ppt
BE sem 1 Engineering Graphics(E.G.) full course ppt
 
AutoCAD 2020 Toolsets
AutoCAD 2020 ToolsetsAutoCAD 2020 Toolsets
AutoCAD 2020 Toolsets
 
Class diagrams
Class diagramsClass diagrams
Class diagrams
 
Learn CATIA V5 in 3DEXPERIENCE 2017x
Learn CATIA V5 in 3DEXPERIENCE 2017xLearn CATIA V5 in 3DEXPERIENCE 2017x
Learn CATIA V5 in 3DEXPERIENCE 2017x
 
Proyección isométrica
Proyección isométricaProyección isométrica
Proyección isométrica
 
Introduction to CATIA
Introduction to CATIAIntroduction to CATIA
Introduction to CATIA
 
Catia sketcher workbench
Catia  sketcher workbenchCatia  sketcher workbench
Catia sketcher workbench
 
Vistas taller
Vistas tallerVistas taller
Vistas taller
 
Anforderungsanalyse - Grundlagen und Prototyping
Anforderungsanalyse - Grundlagen und PrototypingAnforderungsanalyse - Grundlagen und Prototyping
Anforderungsanalyse - Grundlagen und Prototyping
 
Facade Design Pattern
Facade Design PatternFacade Design Pattern
Facade Design Pattern
 
Engineering drawing graphics
Engineering drawing graphics Engineering drawing graphics
Engineering drawing graphics
 
Engineering Graphics
Engineering GraphicsEngineering Graphics
Engineering Graphics
 

Viewers also liked

VBA for AutoCAD
VBA for AutoCADVBA for AutoCAD
VBA for AutoCAD
Tiến Quang Phan
 
Auto cad vba
Auto cad vbaAuto cad vba
Auto cad vba
Nguyễn Trung
 
Programacion VBA para AutoCad 2007 ejemplos
Programacion VBA para AutoCad 2007 ejemplosProgramacion VBA para AutoCad 2007 ejemplos
Programacion VBA para AutoCad 2007 ejemplos
jjcontras
 
Manual auto cad 2013 y 2014
Manual auto cad 2013 y 2014Manual auto cad 2013 y 2014
Manual auto cad 2013 y 2014
Aldo Pizarro Espinoza
 
Basic lisp
Basic lispBasic lisp
Basic lisp
Arvind sahu
 
Giáo trình tự động hóa thiết kế cầu đường, lập trình vba
Giáo trình tự động hóa thiết kế cầu đường, lập trình vbaGiáo trình tự động hóa thiết kế cầu đường, lập trình vba
Giáo trình tự động hóa thiết kế cầu đường, lập trình vba
hng1635
 
Manual autocad 2013
Manual autocad 2013 Manual autocad 2013
Manual autocad 2013
Ame Juárez Santiago
 
Excel Auto Cad Vba Automation
Excel Auto Cad Vba AutomationExcel Auto Cad Vba Automation
Excel Auto Cad Vba Automation
lsxinh
 
Giao trinh autocad 2007 full
Giao trinh autocad 2007 fullGiao trinh autocad 2007 full
Giao trinh autocad 2007 full
Brand Xanh
 
Hình họa vẽ kĩ thuật
Hình họa vẽ kĩ thuậtHình họa vẽ kĩ thuật
Hình họa vẽ kĩ thuậtnguyentuanhcmute
 
[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục
[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục
[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục
TÀI LIỆU NGÀNH MAY
 
Bai5 hình chiếu trục đo
Bai5 hình chiếu trục đoBai5 hình chiếu trục đo
Bai5 hình chiếu trục đoHoàng Linh
 
Bai tap va_huong_dan_thuc_hanh_autocad_vba
Bai tap va_huong_dan_thuc_hanh_autocad_vbaBai tap va_huong_dan_thuc_hanh_autocad_vba
Bai tap va_huong_dan_thuc_hanh_autocad_vba
thaihoa123
 
Hinh hoa bkhn
Hinh hoa bkhnHinh hoa bkhn
Hinh hoa bkhn
thanhtamyb
 
Bí mật trí tuệ người Do Thái
Bí mật trí tuệ người Do TháiBí mật trí tuệ người Do Thái
Bí mật trí tuệ người Do Thái
Brand Xanh
 
Luận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISC
Luận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISCLuận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISC
Luận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISC
Le Duy
 
Vba Class Level 1
Vba Class Level 1Vba Class Level 1
Vba Class Level 1
Ben Miu CIM® FCSI A+
 
Bài tập vẽ kỹ thuật pgs. trần hữu quế, 202 trang
Bài tập vẽ kỹ thuật   pgs. trần hữu quế, 202 trangBài tập vẽ kỹ thuật   pgs. trần hữu quế, 202 trang
Bài tập vẽ kỹ thuật pgs. trần hữu quế, 202 trang
Cửa Hàng Vật Tư
 
Giáo trình vẽ kỹ thuật kiến trúc xây dựng
Giáo trình vẽ kỹ thuật kiến trúc xây dựngGiáo trình vẽ kỹ thuật kiến trúc xây dựng
Giáo trình vẽ kỹ thuật kiến trúc xây dựng
Công ty thiết kế nhà đẹp 365
 

Viewers also liked (19)

VBA for AutoCAD
VBA for AutoCADVBA for AutoCAD
VBA for AutoCAD
 
Auto cad vba
Auto cad vbaAuto cad vba
Auto cad vba
 
Programacion VBA para AutoCad 2007 ejemplos
Programacion VBA para AutoCad 2007 ejemplosProgramacion VBA para AutoCad 2007 ejemplos
Programacion VBA para AutoCad 2007 ejemplos
 
Manual auto cad 2013 y 2014
Manual auto cad 2013 y 2014Manual auto cad 2013 y 2014
Manual auto cad 2013 y 2014
 
Basic lisp
Basic lispBasic lisp
Basic lisp
 
Giáo trình tự động hóa thiết kế cầu đường, lập trình vba
Giáo trình tự động hóa thiết kế cầu đường, lập trình vbaGiáo trình tự động hóa thiết kế cầu đường, lập trình vba
Giáo trình tự động hóa thiết kế cầu đường, lập trình vba
 
Manual autocad 2013
Manual autocad 2013 Manual autocad 2013
Manual autocad 2013
 
Excel Auto Cad Vba Automation
Excel Auto Cad Vba AutomationExcel Auto Cad Vba Automation
Excel Auto Cad Vba Automation
 
Giao trinh autocad 2007 full
Giao trinh autocad 2007 fullGiao trinh autocad 2007 full
Giao trinh autocad 2007 full
 
Hình họa vẽ kĩ thuật
Hình họa vẽ kĩ thuậtHình họa vẽ kĩ thuật
Hình họa vẽ kĩ thuật
 
[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục
[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục
[Kho tài liệu ngành may] giáo trình vẽ mỹ thuật trang phục
 
Bai5 hình chiếu trục đo
Bai5 hình chiếu trục đoBai5 hình chiếu trục đo
Bai5 hình chiếu trục đo
 
Bai tap va_huong_dan_thuc_hanh_autocad_vba
Bai tap va_huong_dan_thuc_hanh_autocad_vbaBai tap va_huong_dan_thuc_hanh_autocad_vba
Bai tap va_huong_dan_thuc_hanh_autocad_vba
 
Hinh hoa bkhn
Hinh hoa bkhnHinh hoa bkhn
Hinh hoa bkhn
 
Bí mật trí tuệ người Do Thái
Bí mật trí tuệ người Do TháiBí mật trí tuệ người Do Thái
Bí mật trí tuệ người Do Thái
 
Luận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISC
Luận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISCLuận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISC
Luận Văn Tính Toán Dầm Thép Tiết Diện Dạng Chữ I Chịu Xoắn Theo AISC
 
Vba Class Level 1
Vba Class Level 1Vba Class Level 1
Vba Class Level 1
 
Bài tập vẽ kỹ thuật pgs. trần hữu quế, 202 trang
Bài tập vẽ kỹ thuật   pgs. trần hữu quế, 202 trangBài tập vẽ kỹ thuật   pgs. trần hữu quế, 202 trang
Bài tập vẽ kỹ thuật pgs. trần hữu quế, 202 trang
 
Giáo trình vẽ kỹ thuật kiến trúc xây dựng
Giáo trình vẽ kỹ thuật kiến trúc xây dựngGiáo trình vẽ kỹ thuật kiến trúc xây dựng
Giáo trình vẽ kỹ thuật kiến trúc xây dựng
 

Similar to Autocad excel vba

Mfc programming tutorial automation step by-step
Mfc programming tutorial automation step by-stepMfc programming tutorial automation step by-step
Mfc programming tutorial automation step by-stepnamtranvanpt
 
Tutorials on Macro
Tutorials on MacroTutorials on Macro
Tutorials on Macro
Anurag Deb
 
Vbabook ed2
Vbabook ed2Vbabook ed2
Vbabook ed2
NilsonVallecillo
 
Create formsexcel
Create formsexcelCreate formsexcel
Create formsexcelRavi Gajul
 
Pranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheetPranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheet
PranaviVerma
 
Visual C# 2010
Visual C# 2010Visual C# 2010
Visual C# 2010
Ali Mattash
 
Software engineering modeling lab lectures
Software engineering modeling lab lecturesSoftware engineering modeling lab lectures
Software engineering modeling lab lectures
marwaeng
 
VBA Tips
VBA TipsVBA Tips
VBA Tips
Ike Onwubuya
 
Excel vba
Excel vbaExcel vba
Excel vba
Almeda Asuncion
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
JOSEPHINEA6
 
Unit IV-Checkboxes and Radio Buttons in VB.Net in VB.NET
Unit IV-Checkboxes    and   Radio Buttons in VB.Net in VB.NET Unit IV-Checkboxes    and   Radio Buttons in VB.Net in VB.NET
Unit IV-Checkboxes and Radio Buttons in VB.Net in VB.NET
Ujwala Junghare
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1
Vijay Perepa
 
Access tips access and sql part 3 practical examples
Access tips  access and sql part 3  practical examplesAccess tips  access and sql part 3  practical examples
Access tips access and sql part 3 practical examples
quest2900
 
Excel Vba Basic Tutorial 1
Excel Vba Basic Tutorial 1Excel Vba Basic Tutorial 1
Excel Vba Basic Tutorial 1
rupeshkanu
 
Visual basics Express Project
Visual basics Express ProjectVisual basics Express Project
Visual basics Express Project
Iftikhar Ahmed
 
Form4 cd4
Form4 cd4Form4 cd4
Form4 cd4smktsj2
 

Similar to Autocad excel vba (20)

Mfc programming tutorial automation step by-step
Mfc programming tutorial automation step by-stepMfc programming tutorial automation step by-step
Mfc programming tutorial automation step by-step
 
Tutorials on Macro
Tutorials on MacroTutorials on Macro
Tutorials on Macro
 
Vbabook ed2
Vbabook ed2Vbabook ed2
Vbabook ed2
 
Create formsexcel
Create formsexcelCreate formsexcel
Create formsexcel
 
Vba 2 (students copy)
Vba 2 (students copy)Vba 2 (students copy)
Vba 2 (students copy)
 
Pranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheetPranavi verma-class-9-spreadsheet
Pranavi verma-class-9-spreadsheet
 
Visual C# 2010
Visual C# 2010Visual C# 2010
Visual C# 2010
 
Software engineering modeling lab lectures
Software engineering modeling lab lecturesSoftware engineering modeling lab lectures
Software engineering modeling lab lectures
 
VBA Tips
VBA TipsVBA Tips
VBA Tips
 
Excel vba
Excel vbaExcel vba
Excel vba
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
 
Unit IV-Checkboxes and Radio Buttons in VB.Net in VB.NET
Unit IV-Checkboxes    and   Radio Buttons in VB.Net in VB.NET Unit IV-Checkboxes    and   Radio Buttons in VB.Net in VB.NET
Unit IV-Checkboxes and Radio Buttons in VB.Net in VB.NET
 
E learning excel vba programming lesson 1
E learning excel vba programming  lesson 1E learning excel vba programming  lesson 1
E learning excel vba programming lesson 1
 
Access tips access and sql part 3 practical examples
Access tips  access and sql part 3  practical examplesAccess tips  access and sql part 3  practical examples
Access tips access and sql part 3 practical examples
 
Excel Vba Basic Tutorial 1
Excel Vba Basic Tutorial 1Excel Vba Basic Tutorial 1
Excel Vba Basic Tutorial 1
 
Visual basics Express Project
Visual basics Express ProjectVisual basics Express Project
Visual basics Express Project
 
VBA
VBAVBA
VBA
 
Form4 cd4
Form4 cd4Form4 cd4
Form4 cd4
 
Vba primer
Vba primerVba primer
Vba primer
 
Excel300
Excel300Excel300
Excel300
 

Recently uploaded

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 

Recently uploaded (20)

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

Autocad excel vba

  • 1. 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, Microsoft Excel. In the first segment we discussed what was possible, 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, and in this session we discuss how to port formatted data from AutoCAD VBA to Excel worksheets. Objects of Our Desire Now that you know how to make an AutoCAD VBA routine speak "Excel-ese," and how to launch a session of Excel, let's examine the Workbook and the Worksheet objects in Excel. You can study the properties of these and other Excel objects through the AutoCAD VBA IDE (integrated development environment) by: 1. Running the IDE (use the VBAIDE command). 2. 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. 3. 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). Figure 1: The Object Browser.
  • 2. View Larger Figure 2: Create a UserForm as shown. 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:
  • 3. 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: 2. Run the application now. 3. Click on the top button to open a spreadsheet. 4. Click on the middle button to fill the first column with values. 5. Click the third button to shut down the application and the spreadsheet. Note: Excel will not completely close down until after you've told it not to save the spreadsheet. Excel VBA IDE AutoCAD software isn't the only application with a VBA IDE. Microsoft Excel also has a VBA IDE, which you can access from the Excel main menu by selecting Tools > Macro > Visual Basic Editor (see Figure 3).
  • 4. View Larger Figure 3: Accessing the Excel VBA IDE. 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:
  • 5. 5. Restart the application. 6. Use the top and middle buttons to send the new values to the spreadsheet. 7. Remember to stretch the column width of the first column to accommodate the values passed to it. The resulting values passed to the spreadsheet should look like those shown in Figure 4.
  • 6. Figure 4: The values are passed to the spreadsheet. 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.
  • 7. 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. 2. Run the application again to see the effect. Not much needs to be said here. 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. The value of 4 is passed to four cells, and the average, sum, and a subtraction of values is calculated in adjacent cells. 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. 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). The 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
  • 8. 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 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. Figure 2: The VBA Manager Dialog loads, unloads, and exports application code. Our First User Program Rather than try to explain every button and function in these interfaces, we're going to go straight to developing our very first program. It's objective is simple enough: open and close Excel. Make sure you have Excel already installed on your system, and then follow along as we begin to develop our first application:
  • 9. 1. Start by making sure you're in a brand new AutoCAD session. 2. Use the VBAMAN command to bring up the VBA Manager dialog box. 3. Click the New button. This creates a new project with a default project name (ACADProject) 4. Click the Visual Basic Editor button to go to the IDE. 5. Enter Control+R or select Project Explorer from the View pull-down menu to view the Project Explorer. It may be docked to one side of your window or it may be a floating window. In either case, it should be reporting your ACADproject. 6. If the project name displays a + (plus) sign to the left, click on the plus sign to see subitem ThisDrawing (see Figure 3). Figure 3: The project window reports projects loaded, and UserForms included in a project. View Larger Figure 4: A UserForm is created for the application. The Project window and Toolbox are organized for easy object placement. 7. From the Insert pull-down menu, select UserForm pull-down to insert a UserForm into this project. Stretch the UserForm dialog box and the window the UserForm sits in so that they take up approximately the space shown in Figure 4. 8. From the View pull-down menu select Toolbox, which opens the Toolbox dialog box. You can also stretch the Toolbox dialog box. Setting Up an Excel Reference Once you've added the UserForm to the project, the next step is telling AutoCAD software how to speak Excel-ese. References expand AutoCAD VBA to include new
  • 10. tools and capabilities, and for this application we need to be able to speak in terms of worksheets, cells, ranges, and other concepts associated with spreadsheets. Here's how we do it: 1. From the Tools pull-down menu, select References, which brings up the References dialog box. 2. Several references at the top of the Available References list may already be selected. Leave them as they are, and search down through the list of available references until you see one that looks like Microsoft Excel 9.0 Object Library (this assumes Microsoft Excel 2000 is already installed). Select the box to the left of the Library as shown in Figure 5. When you do this, the Location label at the bottom of the dialog box should report a path similar to c:Program FilesMicrosoft OfficeOfficeEXCEL9.OLB. Figure 5: Adding the Microsoft Excel 9.0 Object Library reference enables your application to speak "Excel-ese." 3. Click the OK button, which returns you to the IDE. That's all it takes to expand our application to speak in Excel terms. Adding Buttons to the UserForm Now that you've told the application how to speak Excel-ese, let's create some buttons on our UserForm dialog box that launch Excel, close Excel, and Quit out of our application. Here we go: 1. Move your cursor over 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.
  • 11. View Larger Figure 6: You can re-organize the look and layout of your application and development interfaces at any time. 2. Move your cursor over the UserForm and pick an upper-left point. This will spot a button on the UserForm. Click and drag on the button grips to stretch it into any size you like. Create two more buttons and stretch them so that they appear similar to those shown in Figure 6. 3. Slowly click twice over a button to move the cursor inside the button, enabling you to change the button's label. If you click twice too quickly, a code window will appear instead. Close out any code windows that appear and try again if necessary, clicking slowly inside each button to move the cursor into the button text. 4. Change the label for each button so that CommandButton1 text reads Launch Excel, CommandButton2 text reads Close Excel, and CommandButton3 text reads Quit as shown in Figure 7. 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. Your First Coded Object Now that you have finished the dialog box, it's time assign code to each button. Again, we're going to start very simple by writing the code for the Quit button. 1. Double-click the Quit button to bring up the button's code window. 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. In the upper-right corner of the code window is another combo box with value Click, which tells you that the code will be called up when this button is clicked while the
  • 12. application is running. In the main part of the code window are two already typed statements: Private Sub CommandButton3_Click() End Sub 2. 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. The END command in Visual Basic terminates a running application. We're going to run our little program and use this button to stop it. The indenting of the command isn't vital to the program running correctly, but it does help keep command statements visually organized. 3. Close the code window. 4. From the Run pull-down menu, select Run Sub > UserForm menu item to launch our program. Your dialog box should appear over your AutoCAD session. Clicking on the upper two buttons will do nothing, but if you click the Quit button, you should return to the IDE. 5. Click the Quit button to terminate the program. You just ran your first program! You can also run a program by typing the F5 key when you are in the IDE. Launching and Closing Excel This next part is going to take some explaining. But first, let's get the code for the top two buttons assigned. 1. Double-click the Launch Excel button to bring up its code window and type the following code into it:
  • 13. 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:
  • 14. 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 first—after 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
  • 15. 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. •