Macros 201 - How To Register Your SolidWorks Macro To Receive Notifications For SolidWorks Events

November 1, 2007

Why Should I Learn How To Register My Macros To Register For Notifications From SolidWorks? 

The common Macros that you see floating around the SolidWorks community are many and most of them are useful.  However, most of those Macros run only when explicitly commanded to do so by the user.  This is great for most Macros but there are times when it is nice to have some of your code run every time a certain event happens in SolidWorks.  For example, what if you want to have SolidWorks filenames determined based on your company’s part-numbering scheme, which is pulled from a database?  Wouldn’t it be nice to have the situation where every time SolidWorks prompts you to save a file, the filename box was pre-populated with the next number in the sequence? 

You might be thinking, why not just write a regular Macro that will retrieve a part number from a database and then save the active file with that number as the filename?  Well, that works great if and only if your users remember to always use the Macro to save the files.  In this case it is better to have the user be “automagically reminded” when they attempt to save the file.  To do something like this, you need to register your Macro to receive notifications from SolidWorks.  This is not extremely hard to do if you know how but if you don’t know how, then the SolidWorks API Help isn’t very helpful on this topic; hence the post. 

Note:  This particular example may be a moot point for you if you have a PLM tool that takes care of this for you.  If that is your situation, then be thankful but don’t rub it in.  The general concept will still apply though albeit with a different concrete example. 

 For the Macro to accompany this post, I was going to do the scenario above but I saw a post on SolidWorks Community’s Q&A page that made me decide to do the example below.  However, if there appears to be much interest in the auto-numbering Macro then I might post that one also.

What Does This Macro Do?

 This Macro will “listen” for SolidWorks to open SolidWorks files.  When this happens, the Macro will populate the document with a custom property (”sw_version”) that contains the SolidWorks version (e.g. 2007 SP4.0) used to open the file.  If the user saves the file after opening it, you know without opening the file what version of SolidWorks last saved the file.  If the user doesn’t save the file after opening it, then the custom property isn’t added or modified.  You will need to run the Macro exactly once, each time you open SolidWorks.  From then until you close SolidWorks, the Macro will monitor all SolidWorks files being opened. 

 How Hard Is This To Do?

This article assumes you know how to write simple Macros.  You should know how to create and initialize objects and call functions.  As the title suggests, this is not a freshman class on SolidWorks Macros but rather a sophomore class.

 I Don’t Want To Learn Anything, Can I Just Have The Finished Macro?

Yes.  You may download the Macro from here.  Warning:  No warranty is either expressed or implied for this Macro and the Macro is not in any way supported.  By downloading the Macro, you assume all responsibility for running the Macro.

What Version Of SolidWorks Was This Macro Written For?

This Macro was written for SolidWorks 2007 but should run on 2008 as well.

 How Do You Do It (High-Level)?

  1.  Open a new Macro.  
  2. Add a new class to “listen for events”
  3. Declare a class-level sldworks.sldworks variable for the new class like this:  “Private WithEvents sldworks.sldworks”
  4. Register methods in the new class to be notified by SolidWorks when those events occur.
  5. Register a method in the new class to be notified by VBA when the class is initialized.  Make sure that class initializes a sldworks.sldworks variable that is declared at the class level.
  6. Add a method to perform the desired work and add a call to it from the method registered in step 4, above.
  7. Add a public (i.e. global) variable to your main module that represents the event listener class.
  8. Add code to the main procedure in your main module to initialize the public event listener class.
  9. Debug endlessly until it “works”

 How Do You Do It (Detailed)?

  •  Open a new Macro.  
    • You should already know how to do this step.
  • Add a new class to “listen for events”
    • Insert Class
    • Call the class “clsEvents”
  • Declare a class-level sldworks.sldworks variable for the new class like this:  “Private WithEvents swApp as sldworks.sldworks”
    • WithEvents
  • Register methods in the new class to be notified by SolidWorks when those events occur.   The drop down box on the right with events only appears after you declare your swApp variable “WithEvents.”  Also, you must have the left drop-down box set to swApp to see the events for swApp.  If you have the left drop-down box set to Class, then you will see only the class events in the right drop-down box. 
    • Available Notifications
  • Register a method in the new class to be notified by VBA when the class is initialized.  Make sure that class initializes a sldworks.sldworks variable that is declared at the class level.  NOTE:  In this case, you must have the left drop-down box set to Class in order to have the right drop-down box show Class events.
  • Add a method to perform the deisred work and add a call to it from the method registered in step 3, above.
    • I like to put in a simple msgbox() and verify that it is getting called appropriately before I complicate things by adding my worker method.
  • Add a public (i.e. global) variable to your main module that represents the event listener class.
    • This class will be loaded into SolidWorks memory for the duration of the SolidWorks session.
  • Add code to the main procedure in your main module to initialize the public event listener class.
    • Initialize Event Listener
  • Debug endlessly until it “works”
    • I would start out by making sure that my msgbox is called first and foremost.
    • msgbox called
    • Once the msgbox pops up consistently, then I would add the worker method.
    • Here is the worker method that I employed:
      Sub writeVersion()
      Dim swDoc As SldWorks.ModelDoc2
      Dim bSetProp As Boolean
      Dim longstatus As Long, longwarnings As Long
      Dim swxFormattedRevision As String
      Dim swxRevisionVar As Variant
      Dim versions(8 To 16) As swxVersion
      Dim swDocExt As SldWorks.ModelDocExtension
      Dim swPropMgr As SldWorks.CustomPropertyManager
      Dim i As Integer
      For i = 8 To 16
          versions(i).id = i
          Select Case i
              Case 8
                  versions(i).majorVersion = “2000″
              Case 9
                  versions(i).majorVersion = “2001″
              Case 10
                  versions(i).majorVersion = “2001plus”
              Case 11
                  versions(i).majorVersion = “2003″
              Case 12
                  versions(i).majorVersion = “2004″
              Case 13
                  versions(i).majorVersion = “2005″
              Case 14
                  versions(i).majorVersion = “2006″
              Case 15
                  versions(i).majorVersion = “2007″
              Case 16
                  versions(i).majorVersion = “2008″
              Case Else
                  MsgBox (”Version not recognized”)
                  Exit Sub
          End Select
      Next i
          Set swApp = Application.SldWorks
         
          swxFormattedRevision = swApp.RevisionNumber
         
          If Len(swxFormattedRevision) > 0 Then
              swxRevisionVar = Split(swxFormattedRevision, “.”)
              For i = 8 To 16
                  If versions(i).id = swxRevisionVar(0) Then
                      Set swDoc = swApp.ActiveDoc
                      Set swDocExt = swDoc.Extension
                      Set swPropMgr = swDocExt.CustomPropertyManager(”")
                      swPropMgr.Delete (”sw_version”)
                      bSetProp = swPropMgr.Add2(”sw_version”, SwConst.swCustomInfoText, versions(i).majorVersion & ” SP” & swxRevisionVar(1) & “.” & swxRevisionVar(2))
                      Exit Sub
                  End If
              Next i
          Else
              MsgBox (”Version not recognized”)
              Exit Sub
          End If
      End Sub

If you enjoyed this post, make sure you subscribe to my RSS feed!

Comments

10 Responses to “Macros 201 - How To Register Your SolidWorks Macro To Receive Notifications For SolidWorks Events”

  1. dmctiernan on November 4th, 2007 6:53 pm

    Hi Jeff,
    I personally would be grateful if you could post your auto-numbering macro. I am trying to develop something myself, with limit success.

    Keep up the good work, I always look forward to your posts.

  2. Jeff on November 4th, 2007 11:18 pm

    dmctiernan,

    I will do my best to get something up soon but I am looking down the barrel of a rough week so it might be a little while. If you can’t wait, you might be able to modify what I already provided. In any case, thanks for the kind words.

    Jeff

  3. Josh on November 6th, 2007 1:50 am

    dude, jeff, this is great. you’ve laid this out beautifully and make it look eeeeasy. thanks!

  4. HoffY on November 7th, 2007 9:17 am

    Jeff, well done. If i had time i know where to come to get some well written information!

    PS> I would also love to try out your auto numbering macro as i’m wanting to try a similar thing out but have virtually no macro writing abilities aside from the *very* basic.

  5. Extensible By Design » Extensible By Design on February 9th, 2008 12:04 am

    [...] not so long ago I posted a Macro & tutorial on how to register for SolidWorks events.  One application of that technique that I mentioned was to automatically generate document numbers [...]

  6. Anne on March 13th, 2008 3:36 am

    I had this macro code and I am not sure why it can’t work..

    ———————————————————–
    Option Explicit

    Dim SwApp As SldWorks.SldWorks
    Dim Part As SldWorks.ModelDoc2
    Dim SelMgr As SldWorks.SelectionMgr
    Dim boolstatus As Boolean
    ———————————————————–

    It says that User-defined type not defined and the SwApp As SldWorks.SldWorks is highlighted. I am unsure why too. Can you help?

    I am using SW 2008 with VB6

  7. Jeff on March 22nd, 2008 1:39 am

    Hi Anne,

    I am really sorry for the slow response. The problem is that you are using a DIm statement outside of a function or procedure. Inside of procedure you declare a variable using the Dim statement but outside of a procedure you use either the Public or Private statements depending on what access you want to the variable.

    Try this:

    Option Explicit

    Private SwApp As SldWorks.SldWorks

    Let me know if that helps. If not, then make sure that you have a reference to the SldWorks Type Library under Tools, References.

    May the force be with you,
    Jeff

  8. marco on April 24th, 2008 11:28 am

    How can set this macro autorun ?

  9. Jeff on April 24th, 2008 4:06 pm

    Hi Marco,

    The only way I know of to do what you want is to turn this Macro into a SolidWorks Add-in.

    Jeff

  10. Brian on September 23rd, 2008 8:53 pm

    Hi Jeff,
    I just began studying your work, very nice. If you could help a newbie… in this macro, my machine reports a compile error, sub or function not defined on the “Call writeVersion” line. Is there something I don’t have turned on or installed? I’m still using SW2007×64 sp5.0. Thanks.
    Brian

Got something to say?