API Programming Contest #2: Win $100!

I am pleased to announce the second SolidWorks API programming contest! (See results of first contest here.) In this edition, we’re going to test your skills involving assemblies. Here’s how to win one of three gift cards or a 3-month premium membership to

How To Enter and Win
  1. Download the example file set here and open both assemblies.
  2. Write a VBA macro in as few lines as possible that meets the conditions stated below.
  3. Submit the macro to contest@cadsharp.combefore July 1, 12:00AM EST.
  4. The winners will be announced on our blog in July, along with everyone else who submitted a working macro, ranked from fewest lines to most lines.
Conditions for Success
  1. The only required precondition for running the macro is that “contest2_start.SLDASM” is active.
  2. After the macro runs, the resulting assembly has the same center of mass as “contest2_complete.SLDASM”.
  3. After the macro runs, the resulting assembly has the same degrees of freedom as “contest2_complete.SLDASM”. (The green cylinders can spin in place and no other components can move in any way.)
  4. The macro contains no hard coded physical property values: face areas, face normals, edge lengths, vertex coordinates, etc.
  5. The macro does not use IModelDocExtension::SelectByID2 to select entities for mating.
  6. The macro uses the Option Explicit statement.
Additional Comments
  • This problem is not intended to reflect any real life problem. It is simply a puzzle. As long as you achieve the result described above, you can use any tricks or shortcuts you can think of, regardless of whether they entail good programming practices.
  • The models were created in SolidWorks 2012 but any version of the SolidWorks API may be used.
  • Comments, blank lines, and lines resulting from a line continuation character (underscore) will not be counted in the final line count.
  • Multiple variable declarations on one line (and similar syntax tricks) will be counted as separate lines.
  • Any person may submit multiple solutions and I will only consider the submission with the fewest lines of code.

Three winners will be chosen based on the number of lines of code in their macro.

First prize: $100 gift card at
Second prize: $50 gift card at
Third prize: $50 gift card at

Note: The Amazon gift cards can only be awarded to entrants who may purchase or one of its affiliates in Australia, Canada, United Kingdom, Germany, Italy, France, Spain, Netherlands, China, Brazil, India, Mexico, and Japan. Otherwise, a 2-month Power User membership (valued at $199) will be awarded instead. Optionally, a winner that is entitled to a gift card may choose to receive the 2-month Power User membership instead.

The winners will be announced in July. May the best programmer win!

Want to learn about future contests and new content? Sign up for our newsletter.

By |June 11th, 2015|2 Comments

What’s New In The SolidWorks 2015 API

SolidWorks 2015

The SolidWorks 2015 API contains quite a few enhancements that I am excited to share with you. Here are some of the most significant:

  • Access scenes.
  • Insert a table-driven pattern feature.
  • Get or set the components and transforms for interferences.
  • Specify more document printing options.
  • Create and access local curve- and sketch-driven patterns.
  • Get type of body folder cut list.
  • Specify more options when mirroring components in an assembly.
  • Add a width mate to an assembly.
  • Specify whether to print a specified layer when printing a drawing document.
  • Get a feature’s folder.
  • Move a feature to another location in the FeatureManager design tree of a part or assembly.
  • Get all of the bodies that result from splitting a part.
  • Modify a split-body feature by changing its split bodies.
  • Specify more options when editing a mate in an assembly.
  • Support for intersect features.
  • Support for extracting Scanto3D information.
  • Specify whether to keep or delete bodies in a multibody part.
  • Divide a sketch segment into equally spaced sketch segments or points.
  • Get the display dimension object for a specified pattern property or a sketch relation.
  • Get the sketch segments that define the path of a structural member body.
  • Specify more properties when creating a weldment gusset.
  • Specify more properties when creating a structural member end cap.
  • Specify more properties when creating cosmetic threads.
  • Modify variable-pitch helix features.

Want to see the API interfaces and calls related to each of these topics? You need only open up the local API Help, go to the Index tab, and search for the “Release Notes” category. This will show all enhancements in SolidWorks 2015 SP0 in great detail.

As always, if you discover an area where the API is lacking, don’t be afraid to submit it to the SolidWorks API support team.


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

By |October 20th, 2014|0 Comments

Tips for Finding and Organizing Code Snippets

If you’re even the least bit serious about SolidWorks API programming, then you need to have a game plan for efficiently doing each of these:

  • Finding code for use in a macro you are currently writing or plan to write
  • Organizing code so it can be easily found and re-used

Tips for Finding SolidWorks API Code

For example, let’s pretend that we want to learn how to change the active configuration of every component in an assembly. Here are a few avenues we might explore for finding such code (in rough order):

1. Record the action with the macro recorder and then study the code. In this particular case, the best we can do is record ourselves changing the configuration. There’s no way to record performing this task on every component in an assembly.

2. Look in the API Help for an example. This is where I usually start. Unless you’re researching something obscure, the API Help may very well have something similar to what you need. In our case, we might try looking under “Components –> Traverse” and “Assemblies –> components”. Both yield some fruit, but the latter in particular will take you to a list including IAssemblyDoc::GetComponents, which is the ideal method to use in this situation. Since this is such a common method, there are several examples of its usage, though these examples are far more complex than we really need.

3. Search on Over the years I’ve amassed a pretty formidable code library, I am not shy to admit. While only Premium members have full access, it is often-times useful to use the search field at the bottom of each page to search for a particular API call. This will usually bring up macros from the macro library. For example, if you search for “GetComponents” than you’ll be taken to a list of results including “Run code on every part in an assembly”. Unlike the examples in the API Help, I tend to keep my examples as simple and focused as possible, making them much more snippable (yes, I just coined that word).

4. Look on the SolidWorks API forums. This is usually my last resort, but it is worthwhile nonetheless. The topics covered by inquiring minds over the years are quite substantive, including many obscure topics not covered in the API Help. The challenge here is mostly figuring our what keywords to type in to ensure good results. Don’t be surprised if takes you a while to dig through the results. To ensure that you’re only relevant results, click the “Only for API” option before searching.

5. Search on Google. I almost never do this, because most results take you to the forums (which is easier to search within the forums’ search tool) or the online API Help (which is usually harder to search than the local API Help). Nevertheless, there’s a plethora formerly-active forums and API enthusiast websites tucked away in the omnipotent Google cache that might yield a gem of information.

Tips for Storing and Organizing SolidWorks API Code

Once you’ve learned how to change every assembly component’s active configuration, a wise move is to keep that code in an easily accessible place for later use. If you neglect to do this, then the next time you need that code, not only do you have to dig for it in any existing macro but you have to spend time extracting the relevant code from the irrelevant code. Spare yourself the tedium and store your code in a single, accessible location:

1. One large macro. Each code snippet should be in its own module, or at least its own function or sub-procedure. The advantage is that you can quickly test your code since it’s already in .swp form. The disadvantage is that you need SolidWorks open to in order to look at the code, making it more tedious to reference, especially if you’re working in .NET. I don’t recommend this approach, though a lot of people use it.

2. Word document. Certainly the simplest solution. Just make sure your document is backed up.

3. Evernote. This is my personal favorite. I use Evernote for far more than just API code, because it’s such a useful tool for organizing any information you need to access quickly. You can create a separate note for each snippet, and then tag them with “API”. Since the local Evernote client syncs with your online account, you’re data is safe and accessible from anywhere. Oh, and it’s free unless you need to upload more than 60 MB per month.

4. Code snippets feature in Visual Studio (.NET only). This is a little-known feature within the Visual Studio environment. Even the snippets can be accessed very quickly, they are stored locally, which means a lot of data down the drain if your hard-drive crashes.

5. I have never used this, but it seems like a good alternative to Visual Studio’s built-in code snippet manager. This will also work with VBA code. If I weren’t already using Evernote I might give this a try.

Additional Advice for Code Snippet Storage

Finally, let me offer two pieces of advice for those storing code snippets, regardless of location:

—Include comments in your code snippets. Yes, I know, documenting what your code does seems annoying in the moment, but 6 months later you’ll thank yourself for it.

—All but the simplest snippets should be stored as complete, self-contained, fully-functioning programs. Some might say, then, that we’re no longer talking about snippets at all, and perhaps that is true. But I have found that unless you work with the API regularly, it is easy to forget what prerequisite code is necessary for a snippet to work correctly. Let’s consider our earlier example. Here’s what a complete program changing every component’s active configuration looks like:

Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim swComp As SldWorks.Component2
Dim i As Integer
Dim vComps As Variant
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swAssy = swModel
    vComps = swAssy.GetComponents(False)
    For i = 0 To UBound(vComps)
        Set swComp = vComps(i)
        swComp.ReferencedConfiguration = "Test"
    Next i
End Sub

This takes up quite a few lines. So you might be tempted to store a truncated, incomplete instead:

vComps = swAssy.GetComponents(False)
For i = 0 To UBound(vComps)
    Set swComp = vComps(i)
    swComp.ReferencedConfiguration = "Test"
Next i

Do not do this. You are defeating the purpose of using code snippets. The whole purpose is to prevent the need to re-research and re-write code, and yet that is invariably what will happen because you 1) forgot the context of this code (i.e., the data types involved and how to access those objects), 2) need to share the code with someone who doesn’t know the context, or 3) need to test the code (and in its current state, it will not compile).


There’s a lot of places to look in order to find the code you need, though starting with the macro recorder and local API Help is probably best. When it comes to storing code, Evernote is the clear winner, in my opinion. Always store code snippets as complete programs and always include helpful comments.

That ends our look at finding and storing SolidWorks API code. If you have any other tips or tricks you’d like to share, I’d love to hear about them! Please share below.

Want to hear about new videos, macros, webinars, live training events, and blog posts? Sign up for our newsletter.

By |July 9th, 2014|9 Comments
Go to Top