Video: The 99 Must-Know SolidWorks API Calls

Did you know that there are probably over 10,000 API calls available in SolidWorks? Yet less than 1% of them are necessary for creating even very complicated automation macros and add-ins. To prove this, I created a macro that would satisfy the specifications of a mock case study involving part, assembly, and drawing automation using only 99 unique SolidWorks API calls. A line-by-line look at how this macro works was presented At SolidWorks World 2012 in a session called “Goldmember: 99 Must-Know Methods and Properties of the SolidWorks API”.

Here is a list of those API calls, in the order that they are first used. (Some of them are used more than once.)

1. ISldWorks::GetOpenFileName
2. ISldWorks::SendMsgToUser2
3. ISldWorks::ActiveDoc
4. IModelDoc2::GetType
5. IModelDoc2::ActiveView
6. IModelView::EnableGraphicsUpdate
7. ISketchManager::AddToDB
8. ISldWorks::SetUserPreferenceToggle
9. IModelDocExtension::SelectByID2
10. ISketchManager::InsertSketch
11. ISketchManager::CreateCircleByRadius
12. IModelDoc2::AddDimension2
13. IFeatureManager::FeatureExtrusion2
14. IModelDoc2::FirstFeature
15. IFeature::GetTypeName
16. IFeature::GetNextFeature
17. IFeature::Select2
18. IFeatureManager::FeatureCut3
19. IPartDoc::GetBodies2
20. IBody2::GetFaces
21. IFace2::GetSurface
22. ISurface::IsCylinder
23. IFace2::GetArea
24. IEntity::Select4
25. IFeatureMananger::FeatureFillet
26. IPartDoc::SetEntityName
27. IBody2::GetEdges
28. IEdge::GetCurveParams3
29. ICurveParamData::StartPoint
30. IModelDoc2::AddConfiguration3
31. IModelDoc2::DeleteConfiguration2
32. IPartDoc::SetMaterialPropertyName2
33. IModelDocExtension::SetMaterialPropertyValues
34. IModelDocExtension::CustomPropertyManager
35. ICustomPropertyManager::GetNames
36. ICustomPropertyManager::Get3
37. ICustomPropertyManager::Set
38. ICustomPropertyManager::Add2
39. IModelDocExtension::SaveAs
40. IModelDoc2::OpenDoc6
41. IAssemblyDoc::AddComponent4
42. IAssemblyDoc::GetComponentByName
43. IComponent2::GetBodies3
44. IModelDoc2::GetEntityName
45. IAssemblyDoc::AddMate3
46. IAssemblyDoc::GetComponents
47. IEntity::GetComponent
48. IComponent2::ReferencedConfiguration
49. IComponent2::FeatureByName
50. IComponent2::Select4
51. IAssemblyDoc::EditPart2
52. IFeature::GetDefinition
53. IExtrudeFeatureData2::GetDepth
54. IExtrudeFeatureData2::SetDepth
55. IFeature::ModifyDefinition
56. IAssemblyDoc::EditAssembly
57. IComponent2::GetModelDoc2
58. IModelDoc2::SelectionManager
59. ISelectionManager::GetSelectedObjectType3
60. ISelectionManager::GetSelectedObject6
61. IDisplayDimension::GetDimension2
62. IDimension::SetSystemValue3
63. IModelDoc2::ForceRebuild3
64. IModelDoc2::ShowNamedView2
65. IModelDoc2::ViewZoomtofit2
66. ISldWorks::GetUserPreferenceStringValue
67. ISldWorks::NewDocument
68. IDrawingDoc::SetupSheet5
69. IDrawingDoc::CreateDrawViewFromModelView3
70. IDrawingDoc::ViewDisplayShaded
71. IView::ScaleDecimal
72. IDrawingDoc::FeatureByName
73. IDrawingDoc::AutoBalloon4
74. INote::GetAnnotation
75. IAnnotation::GetPosition
76. IAnnotation::SetPosition
77. IView::InsertBomTable3
78. IView::GetVisibleComponents
79. IDrawingDoc::NewSheet3
80. IDrawingDoc::GetSheetNames
81. IDrawingDoc::Sheet
82. IDrawingDoc::ActivateSheet
83. ISheet::SetName
84. IComponent2::Name2
85. IDrawingDoc::Create3rdAngleViews2
86. ISheet::GetViews
87. IView::GetReferencedModelName
88. IView::ReferencedConfiguration
89. IDrawingDoc::InsertModelAnnotations3
90. IModelDoc2::ClearSelection2
91. IView::GetFirstDisplayDimension5
92. IDisplayDimension::GetNameForSelection
93. IDisplayDimension::GetNext5
94. IModelDocExtension::AlignDimensions
95. IModelDocExtension::GetPackAndGo
96. IModelDoc2::GetPathName
97. IPackAndGo::SetSaveToName
98. IModelDocExtension::SavePackAndGo
99. ISldWorks::CloseAllDocuments

The presentation was very well received. Here is some of the feedback emailed to me afterward:

[quote author=”James” website=”UtilX”]Your “Goldmember” presentation was the best API session I’ve attended in 8 SWW events!”[/quote] [quote author=”Steve” website=”Harsco Industrial”]Just left your “Goldmember” class you gave at Solidworks World 2012.  Thank you for coming and offering these classes!  You have opened a new world to me that I feel I can dive into…  Thank you![/quote] [quote author=”Michael” website=”WL Gore & Associates”]Hello Keith.  I was in your excellent course on Tuesday.  I was pretty impressed with how you got through all 99 right in the allotted time.  Thanks for the great course and insight.[/quote]

This presentation also works as a great refresher for those who have worked with the API in the past but may need to quickly brush-up on the API by hitting only the highlights.

Although it was not recorded at SolidWorks World, I later recorded myself giving the entire presentation again. Premium members can watch it here. The lesson page also includes the code itself.

What API calls do you consider “must-know”? Please share in the comments below!


Want to keep up with new blog posts, videos, and macros we create each month? Sign up for our newsletter!

By |April 19th, 2012|0 Comments

Video : Create Custom Features with the SolidWorks API

Did you know that you can create completely custom features that behave just like regular SolidWorks features? This is possible with macro features. Just like a standard SolidWorks feature, macro features reside in the FeatureManager tree and can do anything a standard feature can do an more. Using a macro features you can do the following:

  • Create or edit bodies
  • Perform tasks during every feature rebuild
  • Use PropertyManager pages as a user interface, complete with temporary body previews
  • Prevent tampering by disabling the ability to suppress, edit, or delete

As demonstrated in the embedded video, this all makes for a feature that looks and feels like it came right out of the box. Best of all, since the code controlling the macro feature remains in the source macro file, modifications can be made to the source code that will reflect in every instance of the macro feature. It’s just like when you update a model and the change is reflected in all drawings referencing that model.

A word of warning, however: Macro features certainly fall under the category of “advanced” functionality, and for that reason they are the topic of the very last lesson in my course. Indeed, if I would consider any part of one’s API knowledge the “crown jewel” it would be the ability to write macro features. And until now, no tutorials existed to ease the learning of this powerful aspect of the API.

In my 43 minute lesson, Lesson 7.5 in our VBA course, I walk you through the creation of a complex macro feature from beginning to end. No stone is left un-turned. To help organize the procedure for creating macro features, I break the video up into several steps:

Part A: Macro feature basics
Part B: Creating a new body
Part C: Replacing an existing body
Part D: Implementing a PropertyManager page (PMP) as a user interface
Part E: Adding additional PMP controls for the body’s dimensions
Part F: Implementing edit definition
Part G: Remembering PMP control values
Part H: Implementing temporary body previews
Part I: Spike Creator demonstration

Parts A through H cover the essentials of creating a robust macro feature without any unnecessary bells or whistles. In the last part, I present to you the final iteration of the Spike Creator macro—the basics of which we developed two lessons earlier.  Specifically, I give more detail on how the merge functionality of the Spike Creator macro feature works. Also provided on the lesson page is the source code for the second macro shown in the YouTube promo, so you can see exactly how to update custom properties or run any other code you want during rebuild.

Personally, I love that SolidWorks is so customizable, right down to the most basic building block of a model—the feature. If anyone has any cool ideas for a macro feature, I’d love to hear it. Just share in the comments below.


Want to keep up with new blog posts, videos, and macros we create each month? Sign up for our newsletter!

By |April 9th, 2012|2 Comments

Advanced API: Using Persistent IDs to Locate Objects

Fundamental to writing macros and add-ins with the SolidWorks API is knowing how to get the pointer to a particular object.  In some cases, this is a simple.  If you need a selected object’s pointer then you just use ISelectionManager::GetSelectedObject6.  If you need the name of a feature called “CutExtrude1” then you would just use IPartDoc::FeatureByName.  These methods, however, assume that you know the name of that object.  This isn’t always the case.  What to do then?

First, you need to programmatically locate the object.  The most common way is to traverse the FeatureManager tree (in the case of a feature or component) or traverse the geometry or topology itself (in the case of a face, edge, vertex, etc.).  Once you have the object, however, how does your program “remember” it for later use?  You could store its name or perhaps its location, but depending on the object this could be very tedious.

Instead, a much easier option is to use “persistent IDs”.  Persistent IDs are a unique identifier for any selectable object.  According to the API Help, “The reference IDs persist for the objects in the model document across SolidWorks sessions. Other applications can use persistent reference IDs to locate objects at runtime.”  This means that, unless you remove and then recreate that object, you can always locate that object so long as you have its ID.

Obtaining an object’s ID is very simple.  Just use IModelDocExtension::GetPersistReference3, which returns an object containing the persistent ID.  (Fun fact: Think your password is unique?  A persistent ID has 297 digits.)  Later, even if its a different SolidWorks session with a different program, you can re-obtain that object’s pointer using IModelDocExtension::GetObjectByPersistReference3.

Want to see how easy they are to use?  Open up any existing part or create a new one and add at least one feature.  Paste the following code in a new VBA macro and set a breakpoint on the line right after IModelDoc2::ClearSelection2 is used.  Now, select a feature in the FeatureManager tree and run the macro.  When your code breaks, look at your part and notice that nothing is selected.  Click Run to continue the code, and then look at the part again.  Why is the feature re-selected?  The persistent ID for that feature was obtained right before the selection was cleared.  On the line following IModelDoc2::ClearSelection2, the pointer was re-obtained using the persistent ID and then re-selected using appropriate Select method.

Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swObj As SldWorks.Feature
Dim swRef As Variant
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swSelMgr = swModel.SelectionManager
    Set swObj = swSelMgr.GetSelectedObject6(1, -1)
    swRef = swModel.Extension.GetPersistReference3(swObj)
    swModel.ClearSelection2 True
    Set swObj = swModel.Extension.GetObjectByPersistReference3(swRef, Empty)
    swObj.Select2 False, Empty
End Sub

You can make this code work with any selectable object.  Just change the data type for swObj to something else—a face, a note, a component, etc.—and then make sure that you use the correct Select method for that object. A version that allows you to re-select multiple entities using persistent IDs is found here.

As you can see, this technique for locating objects can be far simpler than using entity names or attributes, because you don’t even need to assign the ID—it’s already there.  Indeed, many people wrongly use attributes when persistent IDs should be used.  Attributes will be discussed in part two of this series.


Want to keep up with new blog posts, videos, and macros we create each month? Sign up for our newsletter!

By |March 13th, 2012|6 Comments

Free PDF: 23 VBA Errors and How To Fix Them

Download the free PDF here

If you’ve done any significant amount of programming with the SolidWorks API, no doubt you’ve run into compile or run-time errors. In my thousands of hours working with the API, here are the 23 I encounter the most:

  • “Compile error: variable not defined”
  • “Run-time error ’450?: Wrong number of arguments or invalid property assignment”
  • “Run-time error ’91?: Object variable or With block variable not set”
  • “Run-time error ’5?: Invalid procedure call or argument”
  • “Run-time error ’13?: Type mismatch”
  • “Code execution has been interrupted”
  • “Run-time error ’438?: Object doesn’t support this property or method”
  • “Run-time error ‘-2147417848 (80010108)’: Automation error The object invoked has disconnected from its clients”
  • “Run-time error ’98?: A property or method call cannot include a reference to a private object, either as an argument or as a return value”
  • “Compile error: Method or data member not found”
  • “Run-time error ’424?: Object required”
  • “Compile error: Expected user-defined type, not project”
  • “Run-time error ‘-2147417851 (80010105)’: Automation error The server threw an exception.”
  • “Run-time error ’445?: Object doesn’t support this action”
  • “Compile error: Can’t find project or library”
  • “Compile error: User-defined type not defined”
  • “Run-time error ‘-2147417848 (80010108)’: Method ‘IDisplayWireFrameXOR’ of object ‘IBody2’ failed”
  • “Compile error: ByRef argument type mismatch”
  • “Compile error: The code in this project must be updated for use on 64-bit systems. Please review and update Declare statements and then mark with the PtrSafe attribute.”
  • “Could not load some objects because they are not available on this machine.”
  • “Run-time error ‘53’: File not found:
  • “Compile error: Expected variable or procedure, not project”
  • “Compile error: Object library feature not support”

Figuring out what these errors mean and how to fix them can be a real challenge. That’s why I created a free PDF, VBA Debugging Tips for SolidWorks API Programmers, that addresses each of these errors—their causes AND their solutions. This PDF also covers basic debugging tips that will be helpful for those new to SolidWorks API programming.

Let me address just one of these right now. The third error listed is “Run-time error ’91?: Object variable or With block variable not set”. This usually occurs when you are trying to use an API call belonging to an interface that you have not yet accessed. So for example, try typing this in your VB Editor and running it:

Dim swApp As SldWorks.SldWorks
    Sub main()
    swApp.SendMsgToUser "Hello world!"
End Sub

You should get the aforementioned error:

The error is occurring because the swApp object variable was never set. Consequently we can remedy the problem rather easily by simply adding one line to our macro:

Dim swApp As SldWorks.SldWorks
Sub main()
    Set swApp = Application.SldWorks
    swApp.SendMsgToUser "Hello world!"
End Sub

Likewise, you’ll also get the same error if you leave out the Set keyword. (In Visual Basic for Applications, assigning a reference to an object variable requires the Set keyword. This isn’t the case in other languages, however.)

Sometimes you will get this error message in situations where the solution is less obvious. Chances are you doing one of the following:

  1. You accidentally killed the pointer you were intending to use. For example, if you closed out a model and then tried using the IModelDoc2 pointer to that document that you had previously obtained.
  2. You are using a method incorrectly, so that the interface you thought was going to be returned was never actually returned. For example, if you use IAssemblyDoc::AddMate3 to create a concentric mate between two planar faces, the API call will obviously fail to return the IMate2 object. Therefore, when you try to later use an IMate2 member with the variable that you thought contained an IMate2 object, you get this error.

In conclusion, I think we can all agree that the least enjoyable aspect of programming is debugging. Reduce the time you’ll spend debugging by using my free SolidWorks API debugging PDF and also by taking advantage of our free SolidWorks API training. Lastly, please let me know in the comments below of any other errors that you think I should include in the PDF.

Happy coding!

Want to keep up with future CADSharp.com content, webinars, and special offers? Sign up for our newsletter.

By |March 6th, 2012|0 Comments

Jedi skills : How to create bodies without using features

Yes, it’s true. You can create bodies “on-demand” without using features—using the SolidWorks API, of course. How does this magic happen? Enter in a rarely used but very powerful interface called IModeler. This interface contains no less than 30 members (not including obsolete members) for creating every kind of solid body, surface body, and curve you can think of—all without clogging up your feature tree. Best of all, since these temporary bodies are still true bodies, any IBody2 member can be used on them.

Why are they temporary? Because as soon as the IBody2 object for the temporary body becomes Nothing, *poof*. They’re gone. You ask, “What’s the point, then?” Consider these scenarios:

1. Previews. The most obvious use here would be a macro feature preview, but a preview could be used in other contexts as well. Temporary bodies can be easily updated with new user input, and the programmer can choose not to make the temporary body selectable—just like you’re familiar with already when previewing a feature.

2. Performance. IModeler generates temporary bodies far faster than standard features. Combine this with the default invisibility of temporary bodies and the ability to use IBody2 functions on them, and you have a great tool for calculating mass and volume properties very quickly and without the user knowing. For example, perhaps your macro or add-in needs to calculate the volume inside of a pressure vessel. Using IModeler you could create a body that consumes the pressure vessel, run a subtract operation using IBody2::Operations2 using the pressure vessel as the tool body, delete out the unnecessary bodies, and then find the remaining volume.

Finally, in the event that you do want the temporary body to become a “normal” feature, no problem. That is what IPartDoc::CreateFeatureFromBody3 is for. That brings us to our final use of IModeler:

3. Macro features. A macro feature is a custom feature and consequently any body produced by this feature cannot come from a standard feature, hence the need for IModeler.

Want to see a simple example IModeler in action? Try out this code with a blank part document open:

Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swModeler As SldWorks.Modeler
Dim swBody As SldWorks.Body2
Dim swFeat As SldWorks.Feature
Dim swPart As SldWorks.PartDoc
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swModeler = swApp.GetModeler
    Dim dblData(8) As Double
    dblData(0) = 0
    dblData(1) = 0
    dblData(2) = 0
    dblData(3) = 1
    dblData(4) = 0
    dblData(5) = 0
    dblData(6) = 0.1
    dblData(7) = 0.1
    dblData(8) = 0.1
    Set swBody = swModeler.CreateBodyFromBox(dblData)
    Set swPart = swModel
    Set swFeat = swPart.CreateFeatureFromBody3(swBody, False, 0)
End Sub

The result should be a cube created instantly—without creating any sketches or using any features.

Want to learn more? Our video tutorial on temporary bodies, found in our complete VBA course, will show you how to do the following:

  • How to display temporary bodies (without converting them to permanent bodies)
  • How to check temporary bodies for faults
  • How to perform boolean operations (e.g., add, subtract, combine) on temporary bodies
  • How to change the color of temporary bodies
  • How to make temporary bodies unselectable

In the very near future we’ll be posting a video showing how to use temporary bodies in macro feature previews, so check back soon.

Happy coding,

PS: Don’t forget that our 20% off discount lasts only until March 10th! Just use coupon code “sww2012”.

Want to keep up with future CADSharp.com macros, videos, and live training classes? Sign up for our newsletter.

By |February 29th, 2012|0 Comments

Video: Learn API Basics in Just One Hour

At SolidWorks World 2012, I taught 30 API novices the following in a single hands-on session:

  • How to use the macro recorder
  • How to edit and clean up the recorded code
  • How to declare, assign values to, and use variables
  • How to research API calls in the API Help
  • How to implement auto-completion in VBA macros
  • How to create user forms with text boxes and buttons

A couple days ago I recorded myself delivering that same presentation, for you to watch for FREE if you sign up for our basic membership today.  As one student noted, this presentation will “take away your fear of the API”.  Lesson code and a free VBA cheat-sheet included.

If you’re already a member, just head over to the Videos section and watch it right now.  Hope you enjoy watching it as much as I enjoyed making it.


Want to keep up with future CADSharp.com content, webinars, and special offers? Sign up for our newsletter.

By |February 25th, 2012|0 Comments
Go to Top