Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 3
1 of 7
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234694...
VBA/API - Part 3 By Neil Munro Last month, in the second part of this three-part tutorial, we added code to our macro to place an occurrence of a Marker part at the assembly center of gravity (COG). In this tutorial, we'll add a number of additional procedures. One procedure will update the position of the Marker part to the assembly COG, in response to the user clicking the Update button. We'll also add a procedure to set the scale of the Marker part. Finally, we'll add code to set the visibility of origin geometry (planes, axes, center point) in the Marker part. Along the way, we will look at methods you can use to find and fix programming errors (debugging). The hierarchy of objects for our program is shown in Figure 1. Download Files For those diehards who have coded their way through the previous tutorials, continue on with your existing files. If you are just joining us, download Cog_B.zip (129 KB) and extract the files. Cog_B.zip (zip - 129Kb) You can download the files used in this tutorial from here.
Figure 1: Assembly COG object hierarchy. The zipped file contains the following: Marker.ipt COG_B.ivb Place Marker.ipt in a folder included in the current project file. The COG_B.ivb project file includes all code up to the end of last month's tutorial. Rename this file to COG.ivb and load the project through the Autodesk Inventor™ VBA IDE. Here's how: 1. From the Tools drop-down menu on the Autodesk Inventor main menu bar, select Macro > Visual Basic Editor, which opens the VBA editing environment. 2. From the VBA drop-down menu, select File > Load Project. Browse to the folder containing COG.ivb and load it. Updating Marker Position Although it is possible to automatically update the position of the Marker part in response to events that occur in Autodesk Inventor, we'll keep it simple by only updating the position of the Marker part when the user clicks the Update button on our form. The code required to update the part position is almost identical to the code in the InsertMarker subroutine. We'll create a transient matrix to hold the assembly COG position, and then use that data to move the Marker part to the current assembly COG. Although the Marker part is grounded after insertion, there is nothing to prevent the user from ungrounding it, moving or rotating it, or even assembling the Marker part to other assembly components. The matrix used to transform the Marker part restores the orientation (rotation) of the part to match the assembly coordinate system (zero rotation about all axes). Our update procedure will not check for assembly constraints, but you could add code to check for, and then delete, any assembly constraints on the Marker part prior to moving it. 1. Create a new private subroutine named UpdateMarker. 2. Cut the first six lines (not including comments) of code from the InsertMarker procedure, and then paste them into the UpdateMarker procedure.
1/21/2010 6:35 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 3
2 of 7
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234694...
3. Delete the line setting the accuracy of the assembly's mass properties. Your code should match Figure 2. 4. Add the following line above the End Sub line: Call m_oOccMarker.SetTransformWithoutConstraints(oMatrix) The SetTransformWithoutConstraints method moves the component (Marker.ipt), regardless of any assembly constraints on the occurrence. However, the next update to the document would reapply any assembly constraints. As an extra assignment, see if you can add code to this procedure to delete any assembly constraints attached to the component occurrence prior to updating its position. Hint: An assembly ComponentOccurrence has a Constraints property. 5. Copy the code from the InsertMarker procedure that sets the Marker part properties that ground the part and set it as a reference component. Paste it just below the line added in step 4. 6. Copy the code from InsertMarker that calls the UpdateXYZ subroutine. Paste it just below the code added in step 5. 7. Add a line of code to update the document (see InsertMarker). Although an object variable defined within the procedure will be disassociated from any object assigned to it when the procedure ends (goes out of scope), adding a specific line to set the variable equal to nothing at the end of the procedure is considered good programming practice. 8. Add the following line to the end of the procedure (before End Sub). Set oMatrix = Nothing The UpdateMarker subroutine should match Figure 3.
View Larger Figure 3: Additional code added to UpdateMarker. Testing and Debugging
Figure 4: Assembly with Marker part. Let's test this procedure. Open an assembly that contains an occurrence of the Marker part. I'll use a simple assembly of two unique blocks of identical size. 1. From the VBA drop-down menu, select Tools > Macros. 2. Click Run (CogTool should be the only macro available). The assembly in Figure 4 has the blue block fixed at the assembly origin, and the gray block is constrained such that its center is -24 inches along the assembly Z axis.
1/21/2010 6:35 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 3
3 of 7
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234694...
Figure 5: Revised and updated assembly. 3. Make a change to the assembly by moving an underconstrained component or by changing the offset value of an assembly constraint. 4. From the Assembly COG dialog box, click the Update button. The assembly in Figure 5 included changes to two assembly constraints that moved the gray box 2 inches in the Y direction and 4 inches closer to the blue block in the Z direction. The Marker part moved to the new assembly COG, and the labels on the form reflect the updated assembly COG coordinates.
Figure 6: Error message on Marker move. 5. Unground the Marker part and move it away from the assembly COG. 6. Use the Rotate Component tool to reorient the Marker part. 7. Click the Update button again. The Marker part returns to the assembly COG and is reoriented so that the three orthogonal cylinders through the part are aligned with the assembly reference axes. That was too easy. What would happen if the user deleted the Marker part while our macro is running? Let's try it. 1. Delete the Marker part from the assembly. 2. Click the Update button. An error message is displayed, indicating that the programmed failed while moving the Marker part (see Figure 6). 3. Click the Debug button on the error message dialog box. The line containing the error is highlighted in the Code window. Obviously, if the occurrence is no longer in the assembly, the variable m_oOccMarker cannot hold a reference to it. 4. To stop the macro, click the Reset tool on the VBA Standard toolbar (see Figure 7). Accounting for all possible user actions is a challenging task even for a relatively simple program. Error handling enables your program to recover from unexpected conditions such as the one just encountered. A full discussion of error handling is beyond the scope of this tutorial (and probably beyond the scope of the author). However, let's add error trapping and handling for this particular problem. Since we now know which line of code will generate the error, we can add code to check for
Figure 7: Reset tool.
1/21/2010 6:35 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 3
4 of 7
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234694...
an error on this line. 5. Add the following line as the first statement in the UpdateMarker procedure: On Error Resume Next This line forces execution of the next program statement when an error is encountered anywhere in the procedure. We'll add a line directly below the identified line to check if an error actually occurred. The Err object is a VBA object that contains information about the error. Look up Err object in the VBA Help to learn more about error handling. 6. Add the code shown in Figure 8 immediately below the statement that moves the Marker part.
View Larger Figure 8: Error-handling code. Breakpoints and Tracking Objects
Figure 9: Breakpoint in subroutine. There are a number of other tools in the VBA Editor to help you track down errors in your code. One useful technique is to place a breakpoint prior to a suspect section of code and then examine variables as you step through program statements. 1. Activate the Autodesk Inventor window and click the Undo tool on the Standard toolbar to bring back the deleted Marker part. 2. Activate the VBA window. 3. Click in the gray margin next to the code line shown in Figure 9. The line is highlighted with a red background. The program will pause prior to executing this statement. 4. Select Tools > Macros from the VBA drop-down menu, and run the CogTool macro. 5. Delete Marker.ipt from the assembly. 6. Click the Update button on the Assembly COG dialog box. The VBA Editor is activated, and the breakpoint line is highlighted. The macro is still active, but execution is paused. From here, you can examine variable values and step through the code statements to check program logic and execution. 7. Press the F8 function key to execute the highlighted statement. 8. Press F8 again to move to the line starting with Call oMatrix. You can examine the value of nonobject variables by moving the cursor over the variable. 9. Move the cursor over .X near the end of the highlighted line. The X value of the assembly COG is shown in a tool tip (see Figure 10). View Larger Figure 10: Examining variable values. Note: Your value will differ from the one shown in Figure 10. Note also that rounding errors give a value slightly different than the expected value of zero in this assembly. You can also watch the value of any variable (including object variables) in a separate window in the VBA Editor. 10. Right-click the word Err in the If Err Then statement and select Add Watch from the shortcut menu that appears. 11. Click OK to accept the default settings for the Watch. The Watches window is shown and the Err object is added to the Watched expressions. You can dock this window (if it is not already docked) to any edge of the VBA Editor.
1/21/2010 6:35 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 3
5 of 7
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234694...
12. Click the plus sign next to the Err expression in the Watches window. All properties of the Err object are displayed along with their current values. 13. Press F8 until the If Err Then statement is highlighted. The Err object in the Watches window now displays all values associated with the error (see Figure 11). 14. Continue to press F8 to move through the procedure. Since If Err is true, the code inside the If...End If statements executes. A message is displayed warning the user of the problem, and the UI is changed to only enable insertion of the Marker part. Note: You can press the F5 function key to resume normal program execution. Note: The Locals window (View > Locals Window from the VBA drop-down menu) displays all variables with assigned values in the current procedure. If the procedure is attached to a form, the Me object (the form) will also be listed in the Locals window. Expand the Me object to examine all form level objects and variables. Accessing Parameters A useful task that is easily accomplished in a VBA macro is changing model and user-defined parameters in a document. For example, you might change the value of an assembly constraint offset, update the assembly, and then perform some calculations based on the offset value (part position, velocity, and so on). In our program, the user enters a scale value in the txtScale textbox, and we use this value to update a Marker part user parameter that controls the part size. We have a variable (of type ComponentOccurrence) that holds the occurrence of the Marker part in the assembly. Our macro limits the Marker part to only one occurrence, but normally there can be many occurrences of the same component in an assembly. To access the parameters of the Marker part, we require the PartComponentDefinition object of that part document. Fortunately, the ComponentOccurrence object has a Definition property that returns the PartComponentDefinition object for the component. It is important that object properties don't always move you down in the object hierarchy. It is common to see an Application property for an object that returns the top-level Application object. 1. In frmCog, create a new private subroutine named ScaleMarker. 2. Declare the following variables (refer to Figure 1 to follow the object hierarchy): Dim oPartDef As PartComponentDefinition Dim oParams As UserParameters Dim oParam As UserParameter Note: It is not always necessary to declare variables at every level of the object hierarchy used in a procedure. The oParams variable will hold the collection of UserParameters, while the oParam variable will reference one of the user parameters in the collection. These individual parameters can be accessed directly without declaring a collection-level variable. The two approaches are illustrated in the following code. Collection object (oParams) used: Set oPartDef = m_oOccMarker.Definition Set oParams = oPartDef.Parameters.UserParameters Set oParam = oParams.Item(1) Collection object not used: Set oPartDef = m_oOccMarker.Definition Set oParam = oPartDef.Parameters.UserParameters.Item(1)
Figure 13: Scale Marker part on insertion. 3. Add the code shown in Figure 12 to the ScaleMarker procedure. 4. Clean up at the end of the procedure by setting the three object variables declared at the beginning of the procedure equal to nothing. Now that we have a procedure to scale the Marker part, when do we want to use it? The Marker part is scaled when the user clicks the Update button, but setting the Scale parameter to a default size when the part is inserted might be useful as well.
1/21/2010 6:35 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 3
6 of 7
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234694...
5. Select InsertMarker from the Procedures list at the top of the Code window. If the procedure is not visible in the list, select General from the object list (General procedures not associated to a control), and then select InsertMarker from the procedures list. Enter the code shown in Figure 13 (above the line that updates the document).
View Larger Figure 12: Changing the Scale parameter.
Figure 14: Validating scale value. 6. Select UpdateMarker from the procedure list. 7. Add a statement to call the ScaleMarker procedure. You don't force a change to the textbox text in this case. As with the InsertMarker procedure, enter this line prior to the document update statement in this procedure. As always, we are considering every possible user attempt to crash our macro. What would happen if the user deleted all the text in the txtScale textbox or entered text that was not a number? The Val(txtScale.Text) statement would return zero, and Autodesk Inventor would complain (report an error) when the program attempts to scale the Marker part out of existence. Fortunately, a small If statement can eliminate this possible problem. 8. Just prior to calling the ScaleMarker procedure, add an If statement that checks the value of the txtScale textbox. If the value is less than or equal to zero, set the text in the texbox to "1.0". Don't peek, but your code should match that shown in Figure 14. Reference Geometry Visibility OK, this has gone on long enough. Let's add a procedure to set the visibility of the reference geometry in the Marker part, based on check box settings on our form. The code will obtain the PartComponentDefinition of the Marker part, and from there, access the WorkPlanes, WorkAxes, and WorkPoint collections of the Marker part. The origin planes, axes, and center point are always the first items in these collections. Again, refer to Figure 1 to track the object hierarchy. 1. In frmCOG, create a new private subroutine named ShowWorkGeom. 2. Add the code shown in Figure 15. 3. Call the ShowWorkGeom procedure from the UpdateMarker procedure (after the statement that calls the ScaleMarker procedure. 4. Call the ShowWorkGeom procedure from the InsertMarker procedure (after the statement that calls the ScaleMarker procedure).
View Larger Figure 15: Code to display Marker origin geometry. The Grand Test Well, we could go on forever adding extra features to our program, but let's call it a day and test what we have. See the link at the end of the tutorial for a version of the program that fills in a few of the holes we've left in this version. 1. Run the CogTool macro and enter 2 in the txtScale textbox. 2. Click the Update button. The Marker part doubles its size. 3. Click the Planes check box and then click the Update button. The Marker part's origin planes are displayed. 4. Place breakpoints at a few points in the program, and then step through the program (F8). Examine objects and variables in the Watches and Locals windows as you step through the program statements. 5. Try assigning different materials to some assembly components. Verify that the assembly COG changes and the Marker part moves to the new assembly COG after Summary Autodesk Inventor VBA macros can perform tasks ranging from simple to very complex. Hopefully, this series of tutorials has reduced the hesitation some of you might have had in getting started with customization in Autodesk Inventor software. Once you become familiar with the basic techniques and objects of the Autodesk Inventor API, it is much easier to find your way through the extensive object model. Download COG_Done.zip for a version of this program that contains a few additional procedures. The txtScale_KeyPress procedure contains code to filter keyboard input from the user.
1/21/2010 6:35 PM
Autodesk - Autodesk Inventor Services & Support - VBA/API - Part 3
7 of 7
http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=234694...
Be sure to check out the additional article this month introducing the Autodesk Inventor Series. As always, topics for future tutorials are always welcome. Contact me at
[email protected] with your suggestions. COG_Done.zip (zip - 47Kb) The completed COG. © Copyright 2010 Autodesk, Inc. All rights reserved.
1/21/2010 6:35 PM