SolidWorks Macros

November 11, 2007

Framed Box Revisited

In March 2007, I wrote a tutorial on creating a SolidWorks Macro that would create a Framed Box.  This macro worked by creating a cube, then selecting 3 faces and cutting extrudes thru each of them.  I decided to revisit this series of macros and add a few enhancements.  What I wanted to do was to allow the user to control the feature sizes via a custom SolidWorks PropertyManager Page.  The PropertyManager Page gives a macro a look and feel that is it part of SolidWorks.  The PropertyManager Page requires a program module to set up a few variables to setup and launch the PropertyManager class and PropertyManagerHandler class.  There is more learning involved in implementing this feature.

I tried to figure this one out, but soon realized I need some help via a good example. 
I am a strong supporter of “Learning By Example” for anyone who writes programs or macros for SolidWorks. 

In my searching for a good example, I found the macro “VBA_PropertyManagerPage.swp” on SolidWorks’ website.  This macro was put together as an example of how to create the PropertyManager page and how to add all of the control types that are available.  I started with this example, customized the form to suit my needs and I integrated my FramedBox macro.

I wanted the new macro to dynamically update the model while the PropertyManager page stayed open.  While working on the new macro, the PropertyManager page kept closing unexpectedly.  This was due to a conflict between the dynamic updated (I wanted) and the controls at the top of the page.  This was corrected by removing the “swPropertyManager_OkayButton” and adding the “swPropertyManagerOptions_LockedPage

Because of the capabilities of the PropertyManager page, I realized that I could improve the flow of the macro.  Now the macro first creates the framed box model, and then presents the current dimensions to the user.  As the user changes the dimensions, the model is dynamically updated.  Run the “FrameBoxPMP.swp” macro to see the new version.  This is way cool!

My enhancements did not stop there.

One of the inherent problems with this macro was that it cannot be used to create geometry in an existing model that once contained any type of geometry, even a simple sketch.  This is due to the macro accessing and modifying the dimensions, after the model has been created.  Looking thru the macro, you will see parameter references like "D1@Sketch1", "D1@Extrude1", and more.  These are the parameters (dimensions) that were added as the model as it was created.  To properly access and change these parameters, the parameter references in the macro must match the parameter references in the model exactly.

The macro presumes that the first sketch it will create will be "Sketch1" and the first feature will be “Extrude1”.  If a feature or sketch once existed, and was later deleted, this will throw the parameter references off of what is expected, and the macro will fail.  I wanted to get beyond this problem.  What I needed to do was get the sketch and feature names that are created by the macro.

The prefix (D1, D2, etc) of these parameter references point to the dimension number in the sketch or feature.  Since I am only adding dimensions, these prefixes should not change.  The suffix (Sketch1, Extrude1, etc…) is what causes the problem because they point to the sketches and features in the model.

While you are in a sketch it is active, this is the best time to get its name.  Searching thru the SolidWorks Add-ins and API Help file, I found I could use “Part.GetActiveSketch2” and “Sketch.Name” to get the name of the active sketch.  Here is how I got the sketch name as soon as it was created:
  Part.InsertSketch2 True
  Set swSketch = Part.GetActiveSketch2
  fb_ExtrSketch = swSketch.Name
  Set swSketch = Nothing

You can’t get the feature name until after it’s created, and once it’s created, it is not active.  Looking in the SolidWorks Add-ins and API Help file I also found I could use “Part.FeatureByPositionReverse(0)” to get the name of the last feature created.  Here is how I retrieved the name of the feature.
  Set theFeature = Part.FeatureByPositionReverse(0)
  fb_ExtrFeature = theFeature.Name
  Set theFeature = Nothing

I incorporated capturing these names into the appropriate places in the BuildModel routine of my macro.  I saved the names to variables for later use.  Now I needed to change the parameter references to access the features and sketches that were created by the macro.  To do this, I needed to find all existing parameter references and incorporate the variables containing the feature and sketch names.  References to "D1@Sketch1" were changed to "D1@" & fb_ExtrSketch, and so on.

Now, it does not matter how many times you run the macro in the same model, and delete all of the geometry, this macro will work as intended.

Whether or not this macro is done is still unknown.  It all depends on what I want or need it to do in the future.  Who knows?  I may visit it again in the future.

You can download accompanying macros here.

Once again, good luck.

September 24, 2007

Macro Tutorial – Visibility Toggles

I have recently written a couple of, what I call, “Quick and Dirty” macros.  These are so quick, all you have to do is make a selection and run the macro.   In this article, I am going to discuss some of the thoughts and development processes behind writing one of these macros.

Please keep in mind that not all of the information you need is included in this article.  There may be a few cases where I jumped to the code that I used without a thorough explanation of how I go there.  The information provided here should be a good guideline for

The Setup:

SolidWorks allows you to have multiple visibility (display) schemes that allow you to change many of the visibility properties of components within an assembly.  You can use DisplayStates to do this, but for the purposes of this article, we will be showing and hiding components within the current DisplayState of the current assembly.

There are many instances where you may want to show or hide various components in the assembly.  Currently, when you need show or hide components, you need to select some components and show them, then select more components and hide them.  This is a four (4) step (select, hide, select, show) process.  Let’s see if we can get that down to two (2) steps (select, show/hide).

If you would like to follow along with what I did, you can download the sample macros here.  Please note that this macro was written in SolidWorks 2007.  It has been tested in SolidWorks 2006 after the SolidWorks Type Libraries have been changed.  In the Macro Editor, click on the “References” menu and select the SolidWorks 2006 Type Libraries, then resave the macro.

Phase 1 – Record a Macro:

First thing we need to do is figure our how the SolidWorks API selects a component, shows a components and hides a component.  This is a great time to use the macro recorder.  Here is how we will capture what we need to know.

  • Load an assembly into SolidWorks.
  • Turn on the Macro Recorder.
  • Select a visible component.
  • Hide the component.
  • Select a hidden component.
  • Show the component.
  • Stop the Macro recorder and save the new recorded macro.

When we edit the recorded macro, we get something very similar to the following:

' ******************************************************************************
' VisibilityToggle.swb - macro recorded on 09/24/07 by lkikstra
' ******************************************************************************
Dim swApp As Object
Dim Part As Object
Dim SelMgr As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Dim Feature As Object
Sub main()

Set swApp = Application.SldWorks

Set Part = swApp.ActiveDoc
Set SelMgr = Part.SelectionManager
boolstatus = Part.Extension.SelectByID2("
Part1-1@Assem1", "COMPONENT", 0, 0, 0, False, 0, Nothing, 0)
Part.HideComponent2
Part.ClearSelection2 True
boolstatus = Part.Extension.SelectByID2("
Part1-2@Assem1", "COMPONENT", 0, 0, 0, False, 0, Nothing, 0)
Part.ShowComponent2
Part.ClearSelection2 True
End Sub

By looking at the above code, we can see that the macro attached to SolidWorks, then attached to the active document, enabled the selection manager, selected a component, hid it, selected the component again, displayed it, then ended.  These are the same steps we did when we initially recorded the macro.  So far, so good.

When you attempt to run this macro on the same assembly, nothing happens.  Why?  Because the display states of components were changed while you were recording the macro.  In order for the macro to work properly, the same conditions must exist in SolidWorks now, as they did when you initially recorded the macro.  Put the components back to the condition they were in prior to recording the macro.  Open the macro in the Macro Editor.  Use the [F8] key to step thru the macro line-by-line.  You can now watch as the macro executes each step and see that the macro does everything as recorded.  Now everything should work as expected.

As we step thru the macro, we can learn that the following:

  • boolstatus = Part.Extension.SelectByID2” selects the component.
  • Part.HideComponent2” will hide the component.
  • Part.ShowComponent2” will show the component.
  • Part.ClearSelection2 True” will clear the current selection

At this point, the macro will only work for an assembly that has the two components in with the display states that match the specific conditions when the macro was recorded.  If these components do not exist in the assembly, the macro will run, but nothing will happen.

Phase 2 – Modify the recorded macro for “universal” use:

We can modify this macro, or use what we learned, to build a new macro that will work on any assembly, and any mates, but before we can do that we need to decide how we want the macro to work.  Here are my thoughts:

  • Require user to select a component before running macro.
  • Check the visibility state of the selected component.
  • Toggle the visibility state.

We now have 2 things for us to learn and develop for this macro.  Component pre-selection and checking the current visibility state of the selected component.

From the original recorded macro, we can see that the macro enabled a selection manager (“Set SelMgr = Part.SelectionManager”) before selecting the mate.   We will need to add this line to our code because we need to access the selection made by the user.

The next thing we need to look at is how to access the user’s selection.  We know the line “boolstatus = Part.Extension.SelectByID2” makes the selection, but we don’t know the name of the component at this time, so we need to look for other ways to access the user’s selection.  In the SolidWorks API and Add-ins help file (API Help File), go to the “Index” tab and enter “Get” and start scrolling down the list to see if anything makes sense.  I do know from past experience that “GetSelectedObject6” works for our needs.  This brings us to the page “SelectionMgr::GetSelectedObject6”.  This is the same selection routine we used for the MateToggle tutorial. We can read this page for more information.  Because a selection set is lost after it is used, we can only work with the first selection in the set.

We will need to modify our selection to read as follows:
Set MySelection = SelMgr.GetSelectedObject6(1, -1)

To check the visibility state, we can go to the API Help File and search for “Visible”.  I found “Component2.Visible” and “Component2.GetVisibility”.  What’s the difference?  The “Component2.GetVisibility” collects and array of the component’s visibility state in various configurations of the assembly model.  For this “Quick & Dirty” macro, I am only concerned about the current configuration.  The “Component2.Visible” has an “Examples” link.  Let’s check them out.  The page “Make All Assembly Components Visible Example (VB)” shows us how to check the component’s visibility, and hide the component. Here are the lines we are going to borrow:
If swComponentHidden = swChildComp.Visible Then
  swChildComp.Visible = swComponentVisible
End If

I am going to modify these lines to correspond with my own code.  These lines will now look like this:
If MySelection.Visible = swComponentHidden Then
  MySelection.Visible = swComponentVisible
Else
  MySelection.Visible swComponentHidden
End If

You will notice that in the “If” line, I put the “swComponentHidden“ on the opposite side of the equal sign.  In most cases, this is unimportant.  I just like ordering the comparison statement in this manner: “What am I checking?” = “What value do I want it compare it to?”  By being consistent in my programming techniques, it makes easier for me, and others, to understand my macros.

Keep in mind, because a selection set is lost after it is used, we can get rid of the “Part.ClearSelection2 True” line. 

Our updated macro now looks like this:

' ******************************************************************************
' VisiblityToggle2.swb - macro modified on 09/24/07 by lkikstra
' ******************************************************************************
Dim swApp As Object
Dim Part As Object
Dim SelMgr As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Dim Feature As Object
Dim MySelection As Object
Sub main()
   
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
Set SelMgr = Part.SelectionManager
Set MySelection = SelMgr.GetSelectedObject6(1, -1)
If MySelection.Visible = swComponentHidden Then
  MySelection.Visible = swComponentVisible
Else
  MySelection.Visible swComponentHidden
End If
End Sub

It works pretty slick.  You can end the development here if you like because you now have a macro that does what you need.

Phase 3 – Optional Enhancements:

The macro works, but there are a few more things we need to consider:

What if the person selects a mate instead of a component?  What if nothing was selected?  In these cases, you can add filters between the selection, and the visibility check.  To check if something was selected, we can add a line testing the contents of  “MySelection”.  To ensure a component  was selected, we can add a line to check the type of “MySelection”.  The MateToggle3.swp macro illustrates how to do this.  Here is how that portion of the code looks:

  If Not MySelection Is Nothing Then        ' Is something selected
    If SelMgr.GetSelectedObjectType3(1, -1) = swSelCOMPONENTS Then
                                            ' Filter selection

      Set MySelection = SelMgr.GetSelectedObject6(1, -1)    ' Get selection
      If MySelection.Visible = swComponentHidden Then       ' Is it hidden?
       MySelection.Visible = swComponentVisible             ' Yes, Show it
      Else
        MySelection.Visible swComponentHidden               ' No, Hide It
      End If   

    Else
      MsgBox "No component selected."
    End If                                  ' Filter selection
  Else
    MsgBox "Nothing selected."
  End If                                    ' Is something selected

At this stage, I added message boxes to inform the user of improper selections that the macro will not handle.    I also indented the code so the user can see the nested statements, and I added comments at the end of a few lines.  Both of these techniques are not mandatory, but they do make the code a little easier to follow and understand. 

Because this macro should only work within a SolidWorks assembly, the macro should check to see if the current document is an assembly.

One final enhancement would be to make the macro work on more than one component at a time?  This does get tricky because a selection set is lost after it is used.  To keep track of all of the selections, we need to put them into a temporary placeholder, and then traverse thru them one at a time, checking and changing the suppression state.  In the case of improper selections, we can filter the selections before storing them.  This is a needed enhancement to the macro, and it was a big change to the code.  You can look at VisibilityToggle4.swp to for an example of how to do this.

Here are a few interesting notes about selections via the SolidWorks API.

  • Once a selection is used, it is cleared and cannot be reselected by the API.
  • Selections made via “SelectByID2” operate from the current document level and do not require setting an object, but they do require document level commands to modify.
  • Selections made via “GetSelectedObject6” do require setting an object for the selection set.  Selection set based commands are required to modify the objects in the selection set.

These differences in the selection sets, along with the enhancements I made to store multiple selections, and reselecting each component in the saved selection set, did require me to go back to using the “Part.ShowComponent2” and “Part.HideComponent2” commands in the first recorded macro.

Keep in mind that there may be more than one way to complete a task, as shown above.  If you are getting unexpected results, you need to look at other methods to accomplish your task.  Look at existing examples, and research the different methods before continuing on with your development.  This may help you to discover a more efficient method for completing the tasks you need done.

Don’t forget, if you would like to follow along with what I did, you can download the sample macros here

Even the “finished” macro is not complete.  This macro will only work if the components are selected in the feature manager at the left.  It may not work correctly if a component has been selected in the graphics window.  This macro also does not ensure that the user selected a component in the top level of the assembly.

Conclusion:

This is the second tutorial that stems from a discussion that brought on a few comments like “My recorded macro does not work when I run it again.” or “How and where do I start writing a macro?” and “Where can I find help on writing a macro for SolidWorks?”.

When you write a macro, follow these simple steps:

  • Record a macro to “discover” API calls you may need.
  • Study the recorded macro to “discover” how and when things happen.
  • Upgrade the recorded macro to make it more “universal” and capable of working with other models and features.
  • If you are getting unexpected results, you need to look at other methods to accomplish your task.
  • Add additional code to expand on the macro’s functionality. (ex: multiple pre-select)
  • Add your user interface, if needed.  Again, start small, test functions, and work your way up.
  • Add code to accommodate improper selections.
  • Let it loose and see how others use the macro.
  • Be ready to add updates as problems are “discovered”.

When is any macro actually done?  It can be done as soon as you get it to work as expected, or it may not be done until it has been “idiot-proofed” meaning that you have thought of, and added code to accommodate all of the potential ways the macro could be misused (intentional or not).  This decision is up to the developer, the user(s), and the environment the macro will be used (or abused) in.  Keep in mind that changes to the SolidWorks API, due to SolidWorks upgrades, may force you to make additional changes to the macro.

If you look at the two tutorials, MateToggle and VisibilityToggle, and examples closely, you will see that about 90-95% of these macros are identical.  We could have easily modified the MateToggle macro to serve a different purpose, and create the new VisibilityToggle macro.  Once again, proof that old macros don’t die!

You can find a few more macros built on this concept by going to the “Quick and Dirty” (http://www.lennyworks.com/solidworks/default.asp?ID=44) macro page on my website.

September 05, 2007

Macro Tutorial – Mate Toggles

I have recently written a couple of, what I call, “Quick and Dirty” macros.  These are so quick, all you have to do is make a selection and run the macro.   In this article, I am going to discuss some of the thoughts and development processes behind writing one of these macros.

Please keep in mind that not all of the information you need is included in this article.  There may be a few cases where I jumped to the code that I used without a thorough explanation of how I go there.  The information provided here should be a good guideline for

The Setup:

SolidWorks allows you to have multiple mating schemes that allow you to show multiple positions of a component, within an assembly.  You can use configurations to do this, but for the purposes of this article, we will be suppressing and unsuppressing mates within a single configuration of the assembly.

Currently, when you need to toggle mates to move a component from one position to another, you need to select some mates and suppress them, then select more mates and unsuppress them.  At this time, the component will move to the new position.  This is a four (4) step (select, suppress, select, unsuppress) process.  Let’s see if we can get that down to two (2) steps (select, (un)suppress).

If you would like to follow along with what I did, you can download the sample models and macros here.  Please note that this macro was written in SolidWorks 2007.  It has been tested in SolidWorks 2006 after the SolidWorks Type Libraries have been changed.  In the Macro Editor, click on the “References” menu and select the SolidWorks 2006 Type Libraries, then resave the macro.  The models have been created in SolidWorks 2003.

Phase 1 – Record a Macro:

First thing we need to do is figure our how the SolidWorks API selects a mate, suppresses a mate and unsuppresses a mate.  This is a great time to use the macro recorder.  Here is how we will capture what we need to know.

  • Load an assembly into SolidWorks.
  • Turn on the Macro Recorder.
  • Select an unsuppressed mate.
  • Suppress the mate.
  • Select a suppressed mate.
  • Unsuppress the mate.
  • Stop the Macro recorder and save the new recorded macro.

When we edit the recorded macro, we get something very similar to the following:

' ******************************************************************************
' MateToggle.swb - macro recorded on 09/04/07 by lkikstra
' ******************************************************************************
Dim swApp As Object
Dim Part As Object
Dim SelMgr As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Dim Feature As Object
Sub main()

Set swApp = Application.SldWorks

Set Part = swApp.ActiveDoc
Set SelMgr = Part.SelectionManager
boolstatus = Part.Extension.SelectByID2("Parallel1", "MATE", 0, 0, 0, False, 0, Nothing, 0)
Part.EditSuppress
Part.ClearSelection2 True
boolstatus = Part.Extension.SelectByID2("Parallel2", "MATE", 0, 0, 0, False, 0, Nothing, 0)
Part.EditUnsuppress
Part.ClearSelection2 True
End Sub

By looking at the above code, we can see that the macro attached to SolidWorks, then attached to the active document, enabled the selection manager, selected a mate, suppressed it, selected another mate, unsuppressed it, then ended.  These are the same steps we did when we initially recorded the macro.  So far, so good.

When you attempt to run this macro on the same assembly, nothing happens.  Why?  Because the suppression states of mates were changed while you were recording the macro.  In order for the macro to work properly, the same conditions must exist in SolidWorks now, as they did when you initially recorded the macro.  To see that above macro will work, suppress the “Parallel2” mate and unsuppress the “Parallel1” mate and launch the macro again.  Now everything should work as expected.

To see the macro in action, put the mates back to their original status and open the macro in the macro recorder.  Press the [F8] key to step thru the macro line-by-line.

As we step thru the macro, we can learn that the following:

  • boolstatus = Part.Extension.SelectByID2” selects the mate.
  • Part.EditSuppress” will suppress the mate.
  • Part.EditUnsuppress” will unsuppress the mate.
  • Part.ClearSelection2 True” will clear the current selection

At this point, the macro will only work for an assembly that has the “Parallel1” mate unsuppressed, and “Parallel2” mate suppressed.  If these mates do not exist in the assembly, the macro will run, but nothing will happen.

Phase 2 – Modify the recorded macro for “universal” use:

We can modify this macro, or use what we learned, to build a new macro that will work on any assembly, and any mates, but before we can do that we need to decide how we want the macro to work.  Here are my thoughts:

  • Require user to select a mate before running macro.
  • Check the suppression state of the selected mate.
  • Toggle the suppression state

We now have 2 things for us to learn and develop for this macro.  Mate pre-selection and checking the current suppression state of the selected mate.

From the original recorded macro, we can see that the macro enabled a selection manager (“Set SelMgr = Part.SelectionManager”) before selecting the mate.   We will need to add this line to our code because we need to access the selection made by the user.

The next thing we need to look at is how to access the user’s selection.  We know the line “boolstatus = Part.Extension.SelectByID2” makes the selection, but we don’t know the name that at this time, so we need to look for other ways to access the user’s selection.  In the SolidWorks API and Add-ins help file (API Help File), go to the “Index” tab and enter “Get” and start scrolling down the list to see if anything makes sense.  I do know from past experience that “GetSelectedObject6” works for our needs.  This brings us to the page “SelectionMgr::GetSelectedObject6”.  We can read this page for more information.  Because a selection set is lost after it is used, we can only work with the first selection in the set.

We will need to modify our selection to read as follows:
Set MySelection = SelMgr.GetSelectedObject6(1, -1)

To check the suppression state, we can go to the API Help File and search for “Suppress”.  While cruising thru the list, I found the page “Assembly and Mate Traversal”.  On the API Help File page, I see a reference to “Component2::IsSuppressed”, and on the page “Configuration::SuppressNewFeatures”, I see that the same setting affects features and mates.  It appears that the assembly mates are features in the assembly.  It might be a leap, but let’s try it.

To check for the suppression state, we can use “MySelection.IsSuppressed”.  To be able to react properly to this state, we need to modify the suppress/unsuppress, we need to add the following lines:

If MySelection.IsSuppressed Then
  Part.EditUnsuppress
Else
  Part.EditSuppress
End If

Because a selection set is lost after it is used, we can get rid of the “Part.ClearSelection2 True” line. 

Our updated macro now looks like this:

' ******************************************************************************
' MateToggle2.swb - macro modified on 09/04/07 by lkikstra
' ******************************************************************************
Dim swApp As Object
Dim Part As Object
Dim SelMgr As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Dim Feature As Object
Dim MySelection As Object
Sub main()
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
Set Sel Mgr = Part.SelectionManager
Set MySelection = SelMgr.GetSelectedObject6(1, -1)
If MySelection.IsSuppressed Then
  Part.EditUnsuppress
Else
  Part.EditSuppress
End If
End Sub

It works pretty slick.  You can end the development here if you like because you now have a macro that does what you need.

Phase 3 – Optional Enhancements:

Your macro works, but there are a few more things we need to consider:

What if the person selects a part instead of a mate?  What if nothing was selected?  In these cases, you can add a filters between the selection, and the suppression status check.  To check if something was selected, we can add a line testing the contents of  “MySelection”.  To ensure a mate was selected, we can add a line to check the type of “MySelection”.  The MateToggle3.swp macro illustrates how to do this.  Here is how that portion of the code looks:

  If Not MySelection Is Nothing Then        ' Is something selected
    If SelMgr.GetSelectedObjectType3(1, -1) = swSelMATES Then
                                            ' Filter selection
      If MySelection.IsSuppressed Then
        Part.EditUnsuppress
      Else
        Part.EditSuppress
      End If
    Else
      MsgBox "No mates selected."
    End If                                  ' Filter selection
  Else
    MsgBox "Nothing selected."
  End If                                    ' Is something selected

At this stage, I added message boxes to inform the user of improper selections that the macro will not handle.    I also indented the code so the user can see the nested statements, and I added a few comments at the end of a few lines.  Both of these techniques are not mandatory, but they do make the code a little easier to follow and understand. 

Because this macro should only work within a SolidWorks assembly, the macro should check to see if the current document is an assembly.

One final enhancement would be to make the macro work on more than one mate at a time?  This does get tricky because a selection set is lost after it is used.  To keep track of all of the selections, we need to put them into a temporary placeholder, and then traverse thru them one at a time, checking and changing the suppression state.  In the case of improper selections, we can filter the selections before storing them.  This is a needed enhancement to the macro, and it was a big change to the code. 

Don’t forget, if you would like to follow along with what I did, you can download the sample models and macros here

You can download the finished macro here

Even the “finished” macro is not complete.  This macro will only work if the mates are selected in the feature manager at the left.  It may not work if a mate dimension has been selected in the graphics window.  This macro also does not ensure that the user selected a mate in the top level of the assembly.

Conclusion:

This tutorial stems from a discussion that brought on a few comments like “My recorded macro does not work when I run it again.” or “How and where do I start writing a macro?” and “Where can I find help on writing a macro for SolidWorks?”

When you write a macro, follow these simple steps:

  • Record a macro to “discover” API calls you may need.
  • Study the recorded macro to “discover” how and when things happen.
  • Upgrade the recorded macro to make it more “universal” and capable of working with other models and features.
  • Add additional code to expand on the macro’s functionality. (ex: multiple pre-select)
  • Add your user interface, if needed.  Again, start small, test functions, and work your way up.
  • Add code to accommodate improper selections.
  • Let it loose and see how others use the macro.
  • Be ready to add updates as problems are “discovered”.

When is any macro actually done?  It can be done as soon as you get it to work as expected, or it may not be done until it has been “idiot-proofed” meaning that you have thought of, and added code to accommodate all of the potential ways the macro could be misused (intentional or not).  This decision is up to the developer, the user(s), and the environment the macro will be used (or abused) in.  Keep in mind that changes to the SolidWorks API, due to SolidWorks upgrades, may force you to make additional changes to the macro.

You can find a few more macros built on this concept by going to the “Quick and Dirty” (http://www.lennyworks.com/solidworks/default.asp?ID=44) macro page on my website.

June 12, 2007

Preparing macros for distribution

There are many macros on the internet that can be used within SolidWorks.  These macros cover many things from something as simple as adding named views to a SolidWorks model, or provide different methods of editing custom file properties, to some macros that are a bit more complex.

There are some SolidWorks users who have decided to make their macros available on the internet, for other SolidWorks users so they may be able to benefit from using these macros.  I myself have provided many macros on my website Lenny’s SolidWorks Resources

Throughout the life of any macro, the functionality of the macro may need to be refined to permit it to work with different models or document types.  Maybe the programmer’s techniques have changed and they found a better way for the macro to work.  Maybe something changed in the SolidWorks API and the macro needs to be changed so it will keep working, or work better. 

When writing a macro for use by other people, even those outside of where you work, there are a few things you need to consider.  Beyond the usual interface design and basic functionality, I have outlined some of these issues below.

SolidWorks Versions
Due diligence must be applied to ensure your macro is compatible with the current (or specific) version of SolidWorks.  You also need to consider the benefits of writing the macro so it will work with previous and future versions of SolidWorks.  The SolidWorks Help File identifies when a new API call was added.  You can use the “SldWorks::RevisionNumber” to detect what version of SolidWorks is in use, then have parallel routines to do the same task on each version of SolidWorks.  Depending on the API calls you are using, and the changes that happen to the API, your macro may work on several versions of SolidWorks without any changes.  If you can, test your macro on as many different versions of SolidWorks as you can.

Processes and Standards
Keep in mind that different companies have different processes and standards, and therefore they have different wants and needs.  Keep the macro generic in the sense that the macro should not force the user, or their models, to meet specific requirements just to use the macro.   Each user may have different settings enabled or disabled.  Your macro should be able to accommodate these different settings.  If you discover that you need to turn off a setting, to run more efficiently or reduce user prompts, read and save the current value of the setting, then set it to your macro’s needs, then be courteous and change the setting back.

Features and flexibility
Consider adding flexibility to your macro so users can customize the functionality to meet their needs.  This includes controlling the availability of these functions, or default settings.  My CommonNotes macro is a nice example.  In this macro, I have added the capability to number notes from the bottom up.  If a company standard does not permit numbering notes this way, the feature can be disabled via the settings file.  If a user always numbers notes from the bottom up, this feature can be turned on by default.  If you are retrieving data from the model for compiling by the user on a later date, consider adding a means for the user to identify what data they need to retrieve.  Remember, if a user can’t do what they need, they won’t use, promote or share your macro.

Enhancements
Be receptive and responsive to enhancement requests.  Another user may see a feature you haven’t thought of.  Get as much detail that you feel is necessary to write the new features into the macro, then give them the first opportunity to test the macro and provide additional feedback.  Keep my last comments on flexibility in mind and maintain/apply the flexibility where needed.

Durability
Test! Test! Test!  Before releasing a macro, apply due diligence to ensure all functionality works as intended.  If your macro provides multiple settings that control this functionality, test all combinations of these settings to ensure you didn’t miss anything.  It can be embarrassing when you release an updated macro just to find out that old functionality does not work anymore.

Comment your code
Comment your code as you are writing it.  These comments will remind you of your thinking while you were writing the macro.  These comments can be as simple or complex as you want. The comments are also useful when you are trying to find functionality you know you already added.

Documentation
Supply documentation with your macro.  This documentation should include some basic instructions on what the macro does and how it is intended on being used.  This documentation also needs to identify who wrote the macro, modified the macro, and any appropriate copyrights. 

Other
If you sell your macro, you will be obligated to provide a certain level of support when requested.  Depending on the demands and expectations of your customers, this could quickly become overwhelming.

If you provide the macro for free, you need to include appropriate warnings and disclaimers to protect yourself and your interests.

If you have a macro you would like to share with others, you can email it to me and I will post it in the “User Submitted Macros” page on my website.

April 24, 2007

Troubleshooting SolidWorks Macros

You can't expect every SolidWorks macro to work with every version of SolidWorks.  Although I have spent a lot of time and effort in developing many of the macros I have written, I cannot dream up all situations where my macros may be used or needed.  Your computer set up may be different than the one(s) I use, or test my macros on.  You may even be using a version of SolidWorks that I have not been able to test these macros on.  It is difficult for any one person (or even a group of people) to cover all situations that my macros (or someone else’s for that matter) will be subjected to.

Here are a few general guidelines for troubleshooting my macros, or someone else’s macros you may be attempting to use.  They may even help you during the development and use of your own macros.

Check external references.  External References are predefined libraries that allow macros to access various programs.  These libraries may be specific to a single program, or version of that program.  The SolidWorks Type Libraries are version specific.  Example: "SolidWorks 2006 Object Library".  The macro may also use references that may not be loaded on your computer.  Look at the macro documentation to determine what libraries you may need to install.  The word “MISSING” appearing in front of the library name may indicate what library that is needed.  Keep in mind that these external reference selections are specific to each macro.  These should also be checked and each time you upgrade to a new version of SolidWorks.  Here are a few simple steps to check or change these references.

  • Open the macro in the Visual Basic editor
  • Go to the “Tools | References” menu selection.
  • Select the type library for the SolidWorks version you are currently running.
  • Save macro after new selections are made.

What version of SolidWorks was the macro written for?  The macro you are using may make program calls to unsupported SolidWorks instructions.  This is typical if the macro was written for a version of SolidWorks that is newer than what you are using.  Look at the macro documentation to determine what version of SolidWorks it was written for.  You can use the [F8] key to step thru the code, line by line, until you get to the erroneous instruction.  In this case, you will have to re-write the portion of the macro that is causing the problem.

Where does the macro start?
When you “Run” a macro, by default, a .swp macro starts with the last procedure, in last inserted module.  There is no specific module name or procedure name.  If you are loading in existing modules to build a new macro, load the startup module last.  For macros I write, the word “Main” is usually contained within the name of the procedure.

For macros launched from the toolbar or a macro that is defined in the Tools/Macro pull down menu, the startup procedure must be specified when this “link” is created.

If you are using my MacroLaunch, the startup procedure and module must be specified in the MacroLaunch.ini file.

Rebuild the macro.  If for some reason the above methods still don’t resolve the problem, try rebuilding the macro to fix mismatched external references.

  • From SolidWorks, open the macro in the Visual Basic Editor.
  • Export each form and module.  Note what module is used to start the macro.
  • From SolidWorks, start a new macro in the Visual Basic Editor.
  • Import each form and module.  Import the module is used to start the macro, last.
  • Save the macro and test.

Copying code from online sources.  When copying code from a website, online forum, or other sources, you need to pay attention to line breaks.  For a long line of code to appear on a website, it will wrap around to display multiple lines. Copying code from these examples may result in the lines of code breaking apart when you paste it into your macro.  Watch the colors of the text in the VB editor.  Black text indicates a complete (but not necessarily correct) line of code, while red indicates that the line is not complete, or as expected.

More sources for help.  Contact the author of the macro.  If they can’t fix the problem, they might be able to point you in the right direction to solve the problem. 

If you are having problems while writing your own macro, you can find information on the SolidWorks API in the SolidWorks Add-Ins and API Help file.  For help on Visual Basic or VBA, go to the Microsoft Visual Basic Help file, which is accessible from the VB Editor.  There are many examples in the API section on SolidWorks’ website.  You can also post a question to online forums or newsgroups.  Someone may post an example in response to your question.

April 11, 2007

How hard is it to write a macro? Learning Paths

These paths may not be complete or the best for everyone, and they probably won’t make you a professional programmer, however, they are intended to guide people in the right direction to learn more about writing macros and programs.  To determine where to start, look at your own skills, and compare them with each of the outlines below.  Start at the outline that best fits your current programming knowledge and skill level.  When you are comfortable with the level you are in, move on to the next level and take on a few more challenges.

Starting from scratch:

  • You have the longest road ahead of you, but don’t get discouraged.
  • Try creating a few flow charts as mentioned under “Think Logically” in my previous article.  This should give you a better idea of the logic you need to understand for writing programs.
  • Go to the library and borrow (no cost) a book on Visual Basic programming.  You can find a few sample chapters of various books on SAMS Publishing’s website.  Find a program near the beginning of the book, then trace thru the program and see if you can understand what the program is doing while it works to complete it’s task.  Take a look at a few more programs.  You can also look at Visual Basic tutorials on the internet.  If you can understand these programs, try writing a few of your own.
  • Look in the Visual Basic help file (or the book, or online tutorials) for examples.  Write a few of these examples and run them, see how they work.  Repeatedly pressing “F8” will step you thru the program one line at a time so you can see and follow what is happening.  Change the examples and see what affect that has on how the program runs or the output of the program.  To see this help file without loading SolidWorks or the Visual Basic editor, search for the file “vbui6.chm” on your computer.
  • If you feel comfortable, move on to the section “Need to learn the SolidWorks API”.  You can always come back of you need more time here.

Written formulas for spreadsheets:

  • Know that this is more than just adding and subtracting values in cells or groups of cells.  If you have not even used the “IF” statement, drop back to “Starting from scratch”.
  • Take a spreadsheet formula and see if you can write a program to do the same function.  Try this with a few different formulas.  The section “Starting from scratch” lists a few places where you can find useful help.
  • If you are having problems, don’t get discouraged.  Go to “Starting from scratch” for additional guidelines.
  • If you feel comfortable, move on to the section “Need to learn the SolidWorks API”.  You can always come back of you need more time here.

Background in other programming languages:

  • Keep in mind, that programming languages do have similarities, but each language has a different way of doing things. You need to focus on the differences in the languages, the command structure and syntax.  Search the internet and look for Visual Basic tutorials, or look at the Visual Basic help file.  To see this help file without loading SolidWorks or the Visual Basic editor, search for the file “vbui6.chm” on your computer.
  • Take a simple program written in a language you are familiar with, and rewrite that program in Visual Basic.  Do this with a few more programs for the practice and learning experience.
  • If you feel comfortable, move on to the section “Need to learn the SolidWorks API”.  You can always come back of you need more time here.

Need to learn the SolidWorks API:

  • Use the Macro Recorder in SolidWorks to record a few of the functions you want to control with your macro, then open the recorded macro in the macro editor and look for SolidWorks API calls.  Sometimes this code may be able to give you a "clue" to what you are actually looking for. 
  • Go to the SolidWorks help file “SolidWorks and Add-ins and API Help Topics” to learn more about the API calls.  This help file lists the all of the SolidWorks API commands, and how to use them.  To see this help file without loading SolidWorks, search for the file “sldworksapi.chm” on your computer.
  • A few things you will need to initially concentrate on are accessing SldWorks as an application object and the SolidWorks API Object Model Diagram.  Look at the “Accessors” for help on how to gain access to the object you need, then look at the “Methods” for information on how to read or change those objects.
  • Look at and try the examples that are included in the help file.  Some of these examples may give you clues on how to get what want to go, or provide information on how to get where you want to go.
  • Go to the API sections on SolidWorks’ website and try out the many examples you will find there.

Regardless of your programming level, always start with something simple or just plain experiment with the possibilities of what you can do.  I learned a lot just by experimenting with “what if…” scenarios.

When you do get started on writing a macro or program.  Try these out:

  • Always work in small “byte-sized” chunks.  Test each chunk of code to ensure it functions as expected before moving on to the next chunk.  If you try to write that big macro or program on your first shot, you will just set yourself up for failure.
  • Know how the code functions before you modify it.  Many programmers call common subroutines from other routines.  An improperly modified subroutine may cause unexpected results.
  • Record a few steps using the macro recorder. Modify the recorded code to meet your needs and integrate the new code into your big program, then retest.
  • Find and use existing code instead of trying to write new code from scratch.  This saves time and effort.  Many Visual Basic websites contain sample code you can access for free.  SolidWorks’ website also contained many examples that use/access the SolidWorks API.

If you are looking for an environment to write, test, and run programs, I recommend downloading and installing Microsoft Visual Studio Express Editions that are available for free download and use.  I recommend downloading and installing the Visual Basic 2005 Express.  This will provide a programming environment, much like the VB Editor in SolidWorks, where you can learn and experimenting with programming in Visual Basic.

You get out of it, what you put in it.

In other words, you won’t learn how to write programs unless you put the time and effort into learning how, and actually writing programs.  There is a curve to learning how to write programs.  You need to start small, get comfortable, then keep working your way up the curve.

I did most of my learning by hacking (I did say I was not a professional programmer) away at little chunks of code, testing different scenarios with a lot of trial and error.  Then suddenly, voila, it works as I wanted it to.

Don't write that big macro right away.  Check out the "Toggle" macros in the "Quick & Dirty Macros" section of my website for simple to use macros that do only what they were written to do.  I have added some selection filtering to these macros to reduce problems when running, but that's it.

Please keep in mind that this series of articles is primarily intended on getting users inspired to look into the possibilities of creating their own macros for SolidWorks, and also give them a “taste” of things that need to be considered when writing or modifying macros and programs.  These articles do not (nor ever intended to) cover everything there is to know or consider when writing macros or programs.

Good Luck!

April 02, 2007

How hard is it to write a macro?

In preparation to write this article, I thought back to my experiences in writing programs for various computers, which started in 1981.   Most of my earlier experience as been programming as a hobbyist while I was learning how to do what I want on the computer.  I learned BASIC programming and began building and improving my programming skills.  Only recently (in the last 10 years) has this experience been work or CAD related.  I do not consider myself a professional programmer.  I write programs as a hobby, to get my computer to do what I wanted it to do.  I also enjoy the challenge of writing new programs.

This evaluation did bring me to the realization that I had more programming experience than I initially thought, which brings up the question: How hard is it to learn how to write a macro?  This also leads me to wonder if my background is causing me to be delusional in thinking that learning how to write programs is easy.

Please don’t get discouraged by what you are going to read next.  If you are interested in learning or writing macros for SolidWorks, or any other application, please take the time to read the rest of the article.

YES! I do agree that writing programs (macros, applications, utilities or otherwise) for a computer can be more difficult than most people initially think.  This is based on the complexity of the program that is going to be written, as well as the experience and knowledge of the programmer.  Here is where much of that difficulty may lie:

  • Learn the programming language.
  • Accommodate all possible actions that the user may take when using the program.
  • Accommodate for improper or unexpected data as it is being processed.
  • Accommodate the inexperienced user. (Ease of use)
  • Develop error trapping routines and make decisions based on those errors.  Some errors may have to be communicated to the user and wait for a response.
  • Make decisions based on user inputs or the data received.  In other words, “this happened, now what?”
  • There can be huge liabilities associated if data or files that may already be, or may become corrupt.  You then have the burden to prove your program did not cause the corruption.
  • In the case of writing macros to control applications, the programmer needs to learn how to communicate with the program, and learn the proper syntax of the various commands.
  • Supporting the program when it is distributed to multiple users and companies.
  • There is more to writing programs than those listed above, including meeting specifications, performance, form design and controls, and compatibility with the operating system, network and other applications.

YES! This can become a very cumbersome task, BUT DON’T LET THAT STOP YOU from wanting or trying to learn how to write a program.  After all, what are we trying to do here?  We want to write a few simple macros to complete a few simple tasks, to make our work a little easier

Some beginner stuff:

A program is a list of instructions that tell a computer (or another program) how to complete the process you need done.  The computer will follow those instructions in the order they are appear in the program.  When you write programs, you are writing those instructions.

Learning to write a program is a skill that is acquired by trial and error, and learning from your mistakes.  It’s much like walking, riding a bicycle, swimming, skating (which I still can’t do), dancing (with 2 left feet?), etc….  It doesn’t get any easier if you don’t keep trying, but you do get better as you continue to learn and write more programs.

Think Logically:

Do you (or can you) think logically?  You don’t have to be Mr. Spock, but you do need to be able to take simple problems and define logical steps on how solve the problem.  To test this, think of a task where there are multiple steps involved, and multiple possible results at the completion of each step.  Create a flow chart showing these steps and multiple results.  Provide additional steps for each result and so on.  If you can create this flow chart without any problems, then you have a good chance of understanding the logic that is necessary to write a program.

Object Oriented Programming:

Do you understand Object Oriented Programming?  In it’s simplest form, you need to understand that objects have properties, and there are different methods to access those properties.  Think of the automobile (the object) and how you would identify what color it is.  First of all, you would need to get to the exterior (another object). Then you would use your eyes (access) and compare what you see with your knowledge of colors.  Now consider how you would change that color.  You need to apply (method) paint to change the color.  You also need to consider that there may be a specific process to do this task.  Even the paint is an object, and it also has properties (color, sheen, base).

Object Oriented Programming works the same way, and so to objects in SolidWorks.  I  this example we wan to change the border of all of the balloons so they match the preset in SolidWorks drawing.  Thru the API, you need to connect to SolidWorks, access the drawing, get the sheet, then the drawing view, then collect all the annotations.  For each annotation, you need to determine if it is a BOM balloon, then set the border to match the document default.  Then you need to move to the next view until all views on this sheet are done, then move on to the next sheet, and get the views again, etc….  Everything you access here (SolidWorks, drawing, sheet, view, annotation, etc…) are objects. I know I may have missed an object level in somewhere in this example, but this should give you an idea of how to get there.

Controls on program interfaces (a.k.a. forms) are also objects, and each of these objects has properties, and some of them can hold other objects.  You can also program what happens when someone clicks on or modifies these controls.

How hard is it?

This depends upon the student, their learning ability, what they want to achieve and the path they take (or need to take) to get there.  You will need to spend time researching and exploring Visual Basic and the SolidWorks API.  You will also spend time writing, testing and debugging your program.  You will also discover that there are better ways to do what you want, and you will rewrite portions of your program.  This is the way it has always been and will continue to be.

--- --- ---

In the next article I will talk about learning path for those of you who are looking for some guidance on how or where to get started.

I do know there are more experienced programmers out there that do occasionally read this blog.  I do not intend on taking anything away from them, or make their job look any easier than it actually is.  I do applaud them for taking on the challenges of writing much more complex programs than I have, or currently intend on doing.  I actually invite them to post some of their experiences and any comments they may have in getting users to at least look into the possibilities of writing their own macros for SolidWorks.

March 26, 2007

Macro Example – Framed Box

If you have seen any presentation on VB and the SolidWorks API, you have probably seen a simple demonstration that uses the macro recorder to create a simple flat part.  The presenter then went ahead and created a form that allows the user to specify the sizes of the flat part.  This example is similar, but takes it another step by adding a few more features to the part.

In this example, I started a new part and turned on the macro recorder and created a cube.  I then created a sketch on one of the existing planes, used the offset entities, then cut extrude thru all.  I repeated the Sketch/Offset//Cut two (2) more times.  The final result is a frame created from the original cube.

To reuse this macro, start a new part first then run the macro.  When you run the macro, it will automatically create the model for you.  If you have the option “Input dimension value” turned on, you will be prompted twice to enter the values for the twp (2) dimensions in the sketch.  You can hit enter for these prompts.  If you enter a value, the macro will still build a 3” x 3” x 3” box.

This works fine, but:

  • Can we get rid of the annoying prompts if the “Input dimension value” turned on?
  • Can we make a 4” x 4” x 4” cube or 2” x 3” x 4” block instead?
  • Can we make a thicker or thinner frame?

The answer is yes for all of these.

When editing the macro, we can see that all of the code is in a single module.  In examining the code, you will see all of the necessary Visual Basic code and the SolidWorks API instructions to do the work.  We will start with this code and modify it to suit our needs.

First, let’s turn off that pesky “Input dimension value” while we are creating the model.  This is a simple user preference toggle.  So we don’t alienate the user, we need to retrieve and save the current setting, set the toggle to off/false, complete the work, then set the toggle back to the original setting.  To do this, we need to put the following code (save the setting and turn it off) at the start of the routine:

  • DimValuePreset = swApp.GetUserPreferenceToggle(swInputDimValOnCreate)
  • swApp.SetUserPreferenceToggle swInputDimValOnCreate, False

then add this code (change the setting back) at the end of the subroutine.

  • swApp.SetUserPreferenceToggle swInputDimValOnCreate, DimValuePreset

In this example, we created the variable “DimValuePreset” so we can hold the current “Input dimension value” setting until we are done.

Next, we need to create a simple form and decide what information we need to get from the user.  In this example, we need the user to define the Width, Height, and Depth of the cube, and the frame thickness.  Don’t forget to add the Create and Close buttons.  The Create button is used to launch the custom code, while the Close button gives the user a clean way of getting out of making the part.

Once the form is created, we need to move some code around and link the user data into the right places in the existing code.  While viewing the form, double click on the “Create” button.  This will create the subroutine “CommandCreate_Click” .  Go to the “Main” module and cut the code between the “Set swApp = Application.SldWorks” line and the next “End” line.  Paste this code between the “ButtonCreate_Click()” and the “End line”  This forces the user to enter the data in the form before the recorded code is executed.

Back in the “Main” module we need to make some changes.  First of all, we need to make the variables global (defined in the whole macro, not just this module).  At the top of the main module, change the word “Dim” to “Global”.

Next, we need to be able to display the form to the user.  In the “Sub Main()” routine, add the following line right after “Set swApp = Application.SldWorks” to show the user form.

  • UserForm1.Show

Back in the form, we need to link the form fields to various places I the recorded macro code.  If you attempt to change the values as the model is being created, you may notice that the macro may abort while creating the sketches and offsets.  This is because of selections made on the screen.  We don’t want to interfere with these screen selections so we will use the “Part.Parameter” feature to change the dimensions after the model is created.  Because there are 6 dimensions, we need to add 6 “Part.Parameter” lines at the end of the “CommandCreate_Click” routine.

  • Part.Parameter("D1@Sketch1").SystemValue = TextBoxHeight.Value / 25.4
  • Part.Parameter("D2@Sketch1").SystemValue = TextBoxWidth.Value / 25.4
  • Part.Parameter("D1@Extrude1").SystemValue = TextBoxDepth.Value / 25.4
  • Part.Parameter("D1@Sketch2").SystemValue = TextBoxFrameWidth.Value / 25.4
  • Part.Parameter("D1@Sketch3").SystemValue = TextBoxFrameWidth.Value / 25.4
  • Part.Parameter("D1@Sketch4").SystemValue = TextBoxFrameWidth.Value / 25.4

To get the correct dimension parameters, go to an automatically created model and display the dimensions.  You can right click on each dimension to get the appropriate parameters from the “Full Name” field in the dimension properties dialog.  We will also need to add the appropriate “TextBox???.Value” for retrieving numerical values from the form.  Don’t forget, if you are working in inch units, you need to convert the value from the form to metric, since SolidWorks values are always entered/received in metric units. 

The last steps we need to do are rebuild the model, redraw the graphics, and show the model in Isometric, and zoom to fit just so the user can see everything when we are done.  We can also close the macro so the user can’t run it again.  This is easily done by adding the following lines at the end of the routine.

  • Part.ForceRebuild3 True
  • Part.GraphicsRedraw2
  • Part.ShowNamedView2 "*Isometric", 7
  • Part.ViewZoomtofit
  • End

At this point, we need to test the macro to see that it works as expected.  Go ahead and start a new part, go to the “Main” module, hit “F5” to run the macro, enter the desired values, and see what happens.  I you did everything right, you should see the geometry recreated with the values entered when the macro was run.

In doing this macro, we started with the macro recorder.  Upon customizing the macro to accommodate user defined sizes, we kept it simple.  To reduce potential problems with using this macro in the future, you will want to consider adding the following functionality:

  • Add code in the “Main” routine that checks to see if the active document is a part.  If a part is found, it then shows the form and waits for user input.  This simple code prevents a user from trying to run the macro within an assembly or drawing.
  • Check the part to see if there is any mass.  If you find mass, this could indicate that a body already exists in the model.  In this case, you should prompt the user before showing the form.
  • In the form, you should run a check to insure that all textboxes have valid entries, before creating the geometry. If there is a problem, tell the user what they need to fix.  You should check the frame thickness to ensure that the offsets can be modified without causing errors.
  • Check your units.  As written, my macro works in inch units.  All values entered into the form will have to be converted to meters when they are placed into the code.  Remember, SolidWorks values are entered/received in metric units.  You can always read the unit settings in the model and then process the input values accordingly.

You can get the sample macros, and model here.  This archive includes the recorded macro, updates as defined above, and a more robust version that includes many of the additional checks I mentioned near the end of this article. 

Is this macro done?  Not really.  It all depends on your experiences while using the macro.  In the future you may realize that you could add a few new features that will make this macro even better than what it is now.

Between the time I initially created this macro and blog, I have since added code (see FrameBox4.swp macro) to do the following:

  • Allow the user to keep changing the values, and re-applying those values to the model when the user hits the “Create” button.  To do this, I checked the mass property again.  If mass existed, then I skipped the recorded portion of the macro and went right to applying the dimensions to the model.
  • If there are no documents active in SolidWorks, this macro will load the default part (if properly defined in the Tools/Options/Default Templates).

This is an example of how a macro can keep evolving as you continue to use it, and another example how Old Macros Don’t Die…

Once again, good luck.

March 25, 2007

Getting started using the Macro Recorder.

When I first write a macro, it is for a specific function that meets a specific need.  It’s short, sweet, to the point, and gets the job done.  Nothing more, nothing less.  This is what you get when you use the macro recorder.

If you are unsure how to begin writing the macro, you can use the macro recorder to record the steps you want your macro to do.  To use the macro recorder, start it from the macro toolbar, then complete the steps you want the macro to follow.  When you are done, stop the recorder and save the macro.  Once the macro is saved, you can play (launch) the macro and watch the macro do the work you just recorded.  Each time you run the macro it will complete the same steps every time.

You can also load the recorded macro into the macro editor and look at the Visual Basic (VB) code and Application Programming Interface (API) calls that are necessary to repeat the tasks that were recorded.  This new macro can then be modified to meet a variety of needs.  You can allow user input via a form and provide additional features and improved functionality to suit your current and future needs.

When you are learning how to write macros, start the macro recorder and do something you usually do, or something you want to learn how to do with a macro.  Save the macro then load it into the VB editor and see how it works.  Remember, this is a learning experience and the best way to learn is to explore what you don’t already know.

As time permits, I may add some macro examples to this area of my blog.

March 22, 2007

Learning Resources for Writing Macros!!

In an effort to help interested and curious readers, I have compiled a list of resources for learning more about writing programs and macros for SolidWorks.  Most of the SolidWorks links were included in my previous post “Old macros don't die...” but I thought it would be helpful to also include them here.

Installed with SolidWorks:

The single, most helpful resource, in learning about the SolidWorks API is the “SolidWorks and Add-Ins API Help Topics” under the Help menu in SolidWorks.  This resource is very helpful in explaining all of the SolidWorks API commands and syntax.  It also provides many easy to use examples of SolidWorks API specific commands.

You can find help on Visual Basic specific commands in the “Microsoft Visual Basic Help” is available under the Help menu in the Macro Editor.  This help file also includes examples.

Please note: The VBA, that is included with SolidWorks, is based on Visual Basic 6.0, so if you are going to be doing your programming within the macro editor, look for tutorials on this version.

SolidWorks’ Website:

SolidWorks provides a few pages on their website that have many working examples.

There are even a few tips in the SolidWorks Express newsletter.  You will need to go to the Archives and look under API.

There is an API section in the SolidWorks forum where you can get help and find examples.

SolidWorks API related websites:

These websites feature macros that can be used in SolidWorks and/or provide SolidWorks API programming tutorials and/or examples.

Visual Basic programming related websites:

It is difficult to identify the useful websites for Visual Basic tutorials, samples or source code because there are so many sites on the internet.  Some are free, and some require registration or subscriptions.  Each site also explains the basics of writing programs in Visual Basic a bit differently, and every student has different learning needs.  You should do some exploration to see what tutorial sides meet your needs.  Here are a few websites that feature Visual Basic tutorials, programming tips & tricks, and/or sample programs that are written in Visual Basic.

Great Visual Basic Resources:

Visual Basic Tutorials

Visual Basic ebooks

Visual Basic Source Code (Samples)

Programming Environment:

As I mentioned before, Visual Basic for Applications (VBA) is installed with SolidWorks.  This gives you an environment for writing macros for SolidWorks, and can be used for learning more about programming Visual Basic.

Microsoft has made Visual Studio Express Editions available for free download and use.  I recommend downloading and installing the Visual Basic 2005 Express.  This will provide a programming environment where you can learn and experimenting with programming in Visual Basic.  Microsoft also provides Virtual Labs for Visual Studio.

March 19, 2007

Why write a macro?

There are many reasons why someone would want to write a macro.  Here are just a few examples:

  • Automate common and repetitive tasks by making SolidWorks do those tasks.  If it’s always done the same way, every time (or at least most of the time), you can write a macro that tells SolidWorks how to do it for you. 
  • Automate tasks to reduce user input.  If you always making the same selections over, and over, and over again, you can write a macro and have SolidWorks make some of the selections for you.
  • Automating specific tasks.  Tell SolidWorks what to do, how to do it, and then let SolidWorks do the work as fast as your computer can get it done.
  • Design optimization.  Let SolidWorks optimize the design for you.  With use of a few inputs from the user, and a macro automate the process, you can have SolidWorks create and analyze design iterations and output the data of each variation for you.
  • Develop special tools that can do things to help you better visualize your designs.
  • Develop special tools to analyze your design to see if it meets your specific needs.
  • Consistently retrieve or export data that already exists in the SolidWorks documents.
  • Increases productivity, save time and money, and helps standardize procedures.

What you need?

There are a few things you need, and need to consider, before you get started.

Your programming experience will be the biggest factor in writing the macro.  You need the ability to understand program logic (why does this happen, and how can I do this, know what to expect).  If you have done some programming in the past, even if it was writing some batch programs for DOS, or a lisp routine for AutoCAD, you have a foundation for getting started.  If you have written programs in Visual Basic, or macros for Word and/or Excel, then writing a macro for SolidWorks is going to be easier than you think.

You will need a programming environment.  Here are two options.

  • Visual Basic for Applications (VBA) is installed on your computer when you install SolidWorks (2003 and later).  Macros are saved as a single *.swp file.  Must launch VBA editor from within SolidWorks, to create/edit SolidWorks macros.
  • To write stand-alone applications, you will need to invest in programming environment like Visual C++.Net, Visual Basic.Net., Visual C++, Visual Basic, Visual Studio, etc… that have built-in compilers.  Compiling programs for stand-alone applications is the best way to protect your code from prying eyes.  Stand-alone applications can launch SolidWorks and are required for creating DLL’s and SolidWorks Add-Ins.

Before you start.

Try recording your steps with the macro recorder, then play it back.  This may be the quickest and easiest way to get the automation you need. 

Search the internet to see if someone already wrote a macro do to what you need, or does something similar.  You may want to contact a few programmers to see if they have done something similar, or have something that could help you get started.  The worst they can say is no.

Evaluate your reasons, and the projected time it would take, for writing a macro, and compare that against and the expected increase in productivity you think the new macro will bring.  If it’s something you may only use a couple of times a year, you may end up spending more time writing and debugging the macro, than what you will actually save in using it.

However you proceed, start small then work your way up.  Test each new routine to ensure it works as expected.  One of the worst things you can do is write the whole macro, then hit a number of bugs when you first try to run it.

Good Luck,

March 12, 2007

Old macros don't die...

A recent visitor to my website, Lenny’s SolidWorks Resources, had made a few suggestions for adding some features to one of my macros.  I consider every suggestion that comes in, and any functionality that I feel many people can use, has a good chance of making it into the macro.  In this case, I knew that the functionality already existed, because I was using it.  The first thing I always suggest, when this happens, is for the user to make sure they are using the latest version of the macro that can be downloaded from my website.  They already had the latest version from the website, but not the functionality.  I suddenly realized that I was using an updated version of the macro, and I had not yet updated the macro on my website.  OOPS!

This event prompted me look thru the toolbox of macros that I am using, and others that I have created.  In doing so, I discovered a few macros that were written in late 2005 thru early 2006, that I do use, but did not even exist on my website.  Over the course of a couple of evenings, and a weekekd, at home, I looked at each macro and compared the version on my website, against the version I was using.  In most cases, they were the same.  In a few cases, I had to get the macro on the website updated.

While doing this comparison, I discovered that I had macros written as far back as 2001.  One of hese macros is ISOViews, which creates 4 named isometric views in the model.  Except for the addition of the creation of 4 dimetric views, and building a .swp version, this macro has remained unchanged since it was originally written in 2001.

A little history…

Since it’s early development, SolidWorks has provided an Application Programming Interface (API).  This interface is necessary to allow other programs and add-ins like PDMWorks and COSMOSWorks to access SolidWorks functionality.  This also opened access to people who want/need to write their own programs to access SolidWorks data, or control (tell SolidWorks what to do and how to do it) SolidWorks.

Early versions of SolidWorks had capabilities to run macros via a subset of commands derived from Visual Basic.  This allowed macros and external programs to access and control SolidWorks, however macros still needed to remain simple, meaning that all routines needed to be in a single module, and there was no way to create/use forms in your macros.  The ISOViews macro started in this generation of SolidWorks macros. This was fine, because the macro did not need any user input to do the work.

There were some programs in existence at that time that gave users access SolidWorks and SolidWorks data.  Many of these programs were custom property editors where the user was presented with a form to fill in the appropriate data.  These programs were fine, but required the program to be written outside of SolidWorks and be compiled.  Compiling the program provided a stand alone executable for people to use, without needing Visual Basic or Visual Studio programming environment on their computer.  These programs were generally launched from outside of SolidWorks, but you could have written a simple macro to launch them from within SolidWorks.

When Visual Basic for Applications (VBA) was added to SolidWorks 2003, a new door was opened, because now an easily accessible programming environment was included with SolidWorks that invited everyone to write macros that run within SolidWorks.  With VBA, you can write macros that have multiple modules, you can add forms (each form is a separate module), you don’t need to compile the macro, and everything is saved in one simple “.swp” (SolidWorks Program) file.

The addition of this single feature in SolidWorks has led me to the creation of many macros, over the past few years, that access and sometimes control, SolidWorks.  These macros can be as simple as the ISOViews macro that just goes in and does the work, to something specialized that requires user input prior to completing a task, to something more complex as my AssemblyBOM macro which can retrieve a Bill of Materials from the assembly.

The only reasons at this point to write external executable programs is for program speed, (a macro is not compiled and requires an interpreter while running and is therefore slow, whereas an external program is compiled into a language that the computer can easily understand and therefore it runs faster.), and securing the source code (a macro’s source code can be viewed/edited during runtime, whereas the code for an external program can only be viewed/edited in it’s native programming environment, before compiling.)  Keep in mind, that there are some API functions that are only accessible from an external program, such as event triggers, that can run subroutines when certain events happen in Solidworks.

Back on track…

When a macro is first written, all attempts are made to ensure proper function for the current version of SolidWorks.  It is up to the programmer whether or not the macro will work in previous versions of SolidWorks. Whether or not the macro will work in the future versions of SolidWorks is based upon what changes SolidWorks does to the API.  Sometimes, the programmer has access to a beta copy of the next release of SolidWorks, and can then program their macro to work with multiple versions.

For many macros I have seen, there has not been much change needed to keep it working with newer versions of SolidWorks as they are released.  Thankfully, SolidWorks still retains much of the older API functionality throughout newer versions of SolidWorks’.  If there is a need to update the macro, the programmer now needs to decide whether or not to write a new macro, drop support for older SolidWorks versions, or update the existing macro to work with the new version of SolidWorks.  Writing a new macro could be an easy way to go, but that requires maintaining multiple macros, which could be a problem if you wanted to add new capabilities to the macro(s).  I don’t like dropping support for older versions because there are some users that are the last ones to upgrade, or may be a full release (or more) behind the current version of SolidWorks.  SolidWorks API does provide “SldWorks::RevisionNumber” that allows the macro to determine what version of SolidWorks the macro is running on.  Using this allows the programmer to write parallel routines to do the same task, and provide a single macro that is capable of being run on multiple versions of SolidWorks. 

This is an easy to breath new life to an old macro, and teach an old macro, new tricks.

This does not say that all of my macros will work in all versions of SolidWorks.  I still have to work for a living, I have to do this stuff on my own time, and still live what I hope is somewhat of a “normal” life.

If you are having problems getting one of my macros to work please read the text files included within the macro file.  You may also need to change the reference libraries in the VBA to get it to work properly.

SolidWorks provides a few pages on their website that provides working examples.
http://www.solidworks.com/pages/services/APISupport.html?pid=383
http://www.solidworks.com/pages/services/APIDownloads.html?pid=121

Here are some links to websites featuring macros that can be used in SolidWorks.

Lenny’s SolidWorks Resources:
http://www.lennyworks.com/solidworks/
NHCAD website w/ tutorials:
http://www.nhcad.com/sw_macros/index.html
Stefan Berlitz (Germany):
http://swtools.cad.de/macros.htm
Matt Lombard (SolidWorks Guru):
http://mysite.verizon.net/mjlombard/
Matt Lorono’s (Best of Macros) website:
http://sw.fcsuper.com/
Markku Lehtola’s website:
http://www.markkulehtola.net/wb/pages/solidworks/swxx-tools.php
Sean Dotson’s Forum at MCAD:
http://www.mcadforums.com/forums/viewforum.php?f=34
SolidWorks Tips & Things
http://www.solidworkstips.com/

I’m sorry if I missed some sites.  I primarily wanted to list sites that provided FREE macros, since all of the macros I provide are free.