You are on page 1of 11

Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

VBA/API - Part 1
By Neil Munro

Autodesk Inventor 5 includes Microsoft's Visual Basic for Applications (VBA) as an embedded customization tool. In this month's and
next month's tutorials we'll introduce a few of the concepts you'll need to understand if you want to extend Autodesk Inventor with VBA
macros. In addition, we'll get our programming hands dirty with a small macro to track the center of gravity of an assembly. In this
month's tutorial, we'll concentrate on the VBA environment; next month we'll look at accessing the Autodesk Inventor API.

Note: You can follow these tutorials even if you have no prior programming experience. However, before you begin, read the API
Overview section in the Programming Help file (which is available only if you do a complete or custom installation of Autodesk Inventor
5). You don't need to understand the entire file, but the instructions in these tutorials will make more sense if you have some familiarity
with the concepts discussed in it. A good understanding of how Autodesk Inventor software works is a prerequisite to any
customization effort.
Start with a Plan
As usual, a little planning goes a long way. The macro we want to create must:

Track the center of gravity (COG) of the assembly.


Present an object that can be used with Autodesk Inventor software's Measure tool to determine the distance between key assembly
points (rotation axis, mounting points, and so on) and the COG.
Not affect the COG calculations.
Present a continuous display of the assembly COG coordinates.

The Autodesk Inventor API (application programming interface) enables you to create custom objects that could fulfill the above
requirements, but their creation and manipulation is beyond the scope of these tutorials. We'll use a predefined Marker part (see Figure
1) to track the assembly COG. We'll assign the part a material with zero density to exclude it from mass and assembly COG calculations.

Because it is a part, we can use the built-in origin geometry as helper objects during distance measurements to the assembly COG. In
addition, the three orthogonal cylinders through the sphere will align with the X, Y, and Z axes of the assembly. So that we can see the
part in assemblies of varying scales, we'll add the ability to quickly scale the part.

Figure 1: Marker.ipt.

1 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 2: VBA integrated development environment.

Note: The COG.IPT will be provided with next month's tutorial.


Macros and the VBA Environment
The criteria for our macro require that we have some form of a user interface (UI). To keep it simple, the Marker part will update its
position to match the assembly COG only on the user's command. The display of origin geometry and the scale of the COG part are
changes that also require user interaction. Finally, the display of the current assembly COG coordinates will require a user interface.
Although our macro will have a UI, it is not a requirement. You can create useful and complex macros that do not require any user
interaction.

Autodesk Inventor macros can be stored in three places. A macro can be:

Embedded in a document.
Defined in a default VBA project.
Defined in an external VBA project.

The API Overview in the Programming Help file outlines these options. We'll use an external VBA project to maximize transportability of
the macro.

To create a new VBA project:

1. From the main menu in Autodesk Inventor, Select Tools > Macro > Visual Basic Editor from the drop-down menu.

The VBA IDE (integrated development environment) displays (see Figure 2).

Figure 3: Module editing.


2. Select Tools > Options from the Visual Basic Editor menu.

3. On the Editor tab, place a check mark in the Require Variable Declaration check box. Then click OK. (We'll explain this setting later.)

4. Select File > New Project.

A new project (UserProject1) is added to the Project Explorer. The project currently has no macros defined, so we'll need to add our
macro, and then build the UI for the macro.

A macro can perform operations that range from a single simple task to a complex application. Adding a subroutine in a module
attached to the project creates a macro. So, what's a module or subroutine you ask?

A VBA module is a container for programming code (more explanation as we progress). A subroutine is a specific set of programming
instructions used to perform a task. Subroutines can be created inside a module, and if the subroutine has no arguments, it is
recognized as a macro. Are you confused yet? It should become much clearer as we go through the following steps.

5. Expand UserProject1 in the Project Explorer.

6. Expand Modules under UserProject1 (Module1 is included).

7. Double-click Module1. The Edit window is filled with the opened Module1 (see Figure 3).

2 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 4: CogTool subroutine.


Let's examine the newly displayed tools.

The list of procedures enables you to quickly access a particular named procedure in the module (you can define many different
procedures in a module).

The Code window is where you type in the instructions associated with a procedure (a subroutine is one of a number of procedural
types). For now, we'll ignore the Option Explicit code shown in the Code window.

Add a Subroutine to the Module


Now, let's create a subroutine in Module1, which Autodesk Inventor will recognize as a macro and which we'll use to start our assembly
COG tracker.

1. From the Visual Basic Editor menu, select Insert > Procedure.

2. Enter CogTool in the Name textbox. Note that the default settings are to create a Public subroutine. These are two of the requirements
for a macro, so click OK to create the subroutine. Your Code window should now match Figure 4.

Figure 5: Insert UserForm.


A subroutine contains code to perform a specific task and can be called from other code. Other things of interest about subroutine code
include:

To be recognized as a macro, a subroutine must be public.


The subroutine code is typed into the area before the End Sub statement.
The parentheses at the end of the subroutine declaration can contain arguments that are passed to (and can be returned from) the
subroutine. To be recognized as a macro, the subroutine must have no arguments.

An example of a subroutine with arguments is shown below.

Public Sub AddTwo (Int1 as Integer, Int2 as Integer, Ans as Integer)


Ans = Int1 + Int2
End Sub

Other program code could call this subroutine using the following syntax:

Call AddTwo (5, 6, MyAns)

The Int1 and Int2 arguments are assigned the values 5 and 6 respectively. The Ans argument is linked to the MyAns variable in a
two-way relationship. MyAns is assigned the value of Ans at the end of the subroutine (11 in this case).

Displaying the UI for Our Macro


We have in place all the elements to define the macro, so let's add some instructions to actually perform something. We are planning to
build a UI for our macro, so we'll add code to display our user interface. But before we add the code to show our UI, let's add the
container (UserForm) for the user interface.

1. In the Project Explorer window, right-click UserProject1 and select Insert > UserForm from the shortcut menu that appears (see
Figure 5).

3 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 6: Renamed form.


The Edit window now displays a blank form.

2. In the Properties window, highlight the UserForm1 text next to the Name property, and then enter frmCog as the name of the form
(see Figure 6).

Figure 8: Completed user interface.


4. Press the Tab key to accept the current method (Show) highlighted in the list (see Figure 7).

5. Press the space bar. A tool tip appears describing options (arguments) that can be used with the Show method. The form can be
Figure in
shown 7: aIntelliSense list of object
modal or modeless properties
state. and prevent access to other applications (that is, to Autodesk Inventor) while they are
Modal forms
methods.
visible. We want our form to be visible while we work in Autodesk Inventor software, so we need a modeless form.
This completes the creation of the container for the macro. Now let's work on the macro for the UI.
6. Complete the line of code to match the following:
1. From the Visual Basic Editor menu, select Window > Userproject1Module 1 (Code), which reopens the Code window.
FrmCog.Show vbModeless
Note: You can also navigate to the Code window by double-clicking or right-clicking objects in the Project Explorer.
That's it for our macro definition of the UI. When we run this macro, the UI for our assembly COG macro displays. It is then up to the
2. Click
user in the
to use theCode window
controls onnow
we will the empty
add toline
the above End Sub and type frmCog. (You must type the period after frmCog).
user form.

Note that awith


Working list of
VBAoptions is displayed immediately after typing the period. The list includes all the properties and methods associated
Controls
with therequires
The UI object preceding the controls:
the following period.

Objects
Labels and
to their properties
display the X, Y,and
andmethods are fundamental
Z coordinates to programming
of the assembly COG. Autodesk Inventor software, so a brief review is in order (an
overview
Buttons of to
Autodesk
Insert andInventor
Updateobjects is included
the position of theinMarker
the APIpart.
Overview in the Help file). We'll discuss Autodesk Inventor objects in more
detail in the to
A button next tutorial.
end the macro (Cancel).
A button to toggle the size of the form (>> button).
Objects are items that are manipulated with programming code. Autodesk Inventor exposes objects such as documents, part
Check boxes to toggle the display of the Marker part's origin geometry.
occurrences in an assembly, or feature objects within a part. VBA also exposes objects, including UserForms, and the controls
A text box to enable the user to enter a scale value for the Marker part.
placed on UserForms (TextBox, ListBox, Label, and so on).
WhenProperties areour
complete, settings associated
form will with
match the a particular
one object. 8.
shown in Figure YouButcan
howthink of properties
do we get there?as nouns associated with the object. A
UserForm object has many properties, such as BackColor, Height, Width, and Font. You can manipulate these properties through
1. Double-click
the PropertiesfrmCog in the
window, andProject
you canExplorer. The blank
also change formvalues
property is shown in the
during Edit window.
programming execution (for example, frmCog.Height = 140).
Methods are actions that are performed on the object during program execution (verbs). A UserForm object supports a number of
2. In the Properties window, change the Height property to 105, and then change the Width property to 285.
methods, including Move, Show, and Hide.
Next, we'll add labels for the X-coordinate display.
Now let's continue with the code to display the UI.3. Type sh after the period. The list of object properties and methods follows the
current text by jumping to the first property or method matching the text. This helpful VBA tool is called IntelliSense. We'll mention a few
other uses
3. Fromfor the
this VBA
tool over the course
Toolbox of the
dialog box, programming
click tutorials.. If the Toolbox is not visible, click the Toolbox tool on the Visual
the Label tool

4 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Basic Editor toolbar.

4. Click the form, and then drag to draw a rectangle similar to the one shown in Figure 9.
Release the mouse button to complete the control.

5. With the label selected on the form (it will be highlighted), make the following changes in
the Properties window.

Figure 9: Label control.


Name: IbIX

Caption: 0.00

Height: 13.5

Left: 18

SpecialEffect: Click the down arrow on the right side of the property setting and select 2fmSpecialEffectSunken from the
drop-down list (see Figure 2)

TextAlign: Select 3fmTextAlignRight from the drop-down list

Top: 4.5

Width: 72
Your control should match the one shown in Figure 11.

Note: You can click the property name and then enter values from the keyboard. The current value of the property is overwritten.

Figure 10: SpecialEffect selection.

Figure 11: Formatted Label control.

Figure 12: Second Label control.


6. Add a second label to the immediate left of the lblX control. Change the properties of this label to match the left-side image in Figure
12. Your form should match the right-side image in Figure 12. Drag the new label on the form to align it vertically with the first Label
control.

Copy and Paste the Label Controls

5 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 13: Coordinate Label Property changes.


Unlike the stand-alone version of Visual Basic, VBA does not support arrays of controls. We need to copy and paste the two label
controls to create independent labels for the Y and Z coordinates.

1. Select the two labels (click and drag a window around both), and then press Ctrl-C to copy both controls. Click the form and then
press Ctrl-V to paste both controls in the center of the form.

2. Select both new labels and drag them into position to the right of the first two labels.

3. Click the form and then press Ctrl-V to paste both controls again. Drag these two controls to the right of the second set.

4. Click on each new control in turn, and make the property changes as outlined in Figure 13.

Figure 14: Insert command button.

Note: We are using a common naming convention for VBA objects. The first three characters of the name indicate the control type
(lbl for label, cmd for command button), followed by a descriptive name. The name cannot include spaces.
Add Command Buttons

Next, we'll add a command button to the form. Again, we'll copy and paste the button once we've modified a few properties.

1. From the VBA Toolbox, click the Command Button tool .

2. Click and drag a rectangle on the form to create the button shown in Figure 14. Make the property changes outlined in Figure 14.

6 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 15: Additional command buttons.


3. Copy and paste the button three times. Modify the button positions (drag) and properties as outlined in Figure 15.

Figure 16: Frame control.


Add a Frame Control
Next, we'll add a Frame control to group the origin geometry CheckBox controls.

1. From the VBA Toolbox, click the Frame tool .

2. Create the frame using the same click-and-drag technique. Change the properties to match those shown in Figure 16.

Add CheckBox Controls

7 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 17: CheckBox controls added.

1. Add three CheckBox controls inside the frame. Set the following properties:

Name Caption Accelerator Width

chkPlanes Planes P 45

chkAxes Axes A 45

chkCP Center Point E 45

Your form should now match the one shown in Figure 17.

Complete the Controls

Figure 18: Completed form.

1. Finally, add a TextBox control to the lower-right corner of the form. Set the following properties:

Name: txtScale

Height: 15.75

Left: 200

Text: 1.0

Top: 66.25

2. Add a Label control above the TextBox control. Set its Caption property to Scale, and then set its Accelerator property to S.

3. Now, click the form title bar. Enter Assembly Cog as the value for the form's Caption property.

Your completed form should match the one shown in Figure 18.

8 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 19: Code window.


So, that was fun. What was it that we actually accomplished? The user interface is now in place, we just need to write the program that
will respond to the user's interaction with the controls we placed on the form.

The X,Y, and Z labels will display the current assembly COG coordinates.
The Insert button will insert the Marker part into the assembly.
The Update button will update the position and state of the Marker part (moves the part to the current assembly COG) and the
XYZ-coordinate displays.
The Cancel button will end the macro.
The More button will expand or contract the dialog box. We don't normally need to view the controls at the bottom of the form.
The check boxes control the visibility of the Marker part'sorigin geometry at the next update.
The Scale text box controls the size of the Marker part at the next update.
The accelerator keys enable a keyboard shortcut to the control using Alt + Accelerator.

Let's Write Some Code


We'll write the code to work with Autodesk Inventor in the next tutorial, but let's get started by writing the code that will run when the user
clicks the Cancel or More buttons.

VBA is an event-driven programming environment. Program code is associated with events initiated by the user. When a button is
clicked, program code attached to that event (ButtonName_Click) is executed.

1. Double-click the Cancel button on the form.

The Edit window displays the code associated with the default event for the button (Click), as shown in Figure 19. This code is stored in
the UserForm, not in a separate module. You can navigate to code for different controls, and to the events for the current control, by
selecting from the two drop-down lists at the top of the Code window (see Figure 19). Selecting a control or event that has no existing
code generates a subroutine outline as shown in Figure 19.

9 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

Figure 20: Completed code.


2. Enter the following line of code above the End Sub line.

Unload frmCog

The code will unload the form, thus ending the macro. Again, note that a tool tip appears when you enter the space after Unload.

3. Select cmdMore from the Control list at the top of the Code window. A subroutine for the Click event for the button is added to the
Code window.

This button will serve as a toggle to shrink and expand the form. The logic is as follows:

If the form is currently in its compact state:

Change the height property to 104.


Change the Caption property to << (to indicate a second click will compact the form).

If the form is currently in its expanded state:

Change the height property to 63.


Change the Caption property to >>.

The code must recognize the state of the form and perform operations based on the state. You can use a number of methods to do this,
but we will use an If statement. The logic for a VBA If statement is:

If (some condition) = true


then Do this
Else
Do something else
End if

Note: The Else + Do something else lines are optional in an If statement.


4. Enter the following code in the cmdMore_Click subroutine:

If frmCog.Height = 104 Then


frmCog.Height = 63
cmdMore.Caption = ">>"
Else
frmCog.Height = 104
cmdMore.Caption = "<<"
End if

Note that >> and << are enclosed in quotation marks. The Caption property expects a text string. Use the IntelliSense feature to select
the properties. Indent the code as shown to make it easier to read.

OK, one last code segment, and you can start the testing process. When the form is initially loaded, it will be the same height as it is in
the Edit (design) window. We want the form to appear in its compact state, so let's add a line of code that does that.

5. Select UserForm from the Control list at the top of the Code window. The default cmdCog_Click event is added to the Code window.
You can delete the subroutine for this event.

10 of 11 1/21/2010 6:36 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 1 http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234582...

6. Select the Initialize event from the Event list.

7. Add the following code to the UserForm_Initialize subroutine:

frmCog.Height = 63

Your Code window should match the one shown in Figure 20.

The Test
Testing is an ongoing process during the development of a program. A good strategy is to test a small section of code and fix any errors
you find. You can then move on to another area with some confidence that any new errors are not a result of that section of the
program.

1. From the Visual Basic Editor menu, select Tools > Macros.

2. In the Macros dialog box that opens, ensure CogTool is selected in the macros list, and click Run.

3. The Assembly COG form is displayed in its compact state.

4. Click the More button. The form expands to show all controls and the button text changes to <<.

5. Click the More button again. The form shrinks to its compact state, and the button text returns to >>.

6. Click the Cancel button. The form closes and you are returned to the VBA IDE.

Summary
Congratulations if you've hung in this long. Creating a form in VBA is a simple drag-and-drop process. You then adjust the values of the
Control properties to complete the form layout. Finally, you write code associated with user-initiated events.

Next month we'll tie the user interface into the Autodesk Inventor API to complete our Assembly COG project.

Copyright 2010 Autodesk, Inc. All rights reserved.

11 of 11 1/21/2010 6:36 PM

You might also like