MACRO LIBRARY

Equation-Triggered Macro Utility

Free public access. No account or subscription required.

Learn more about equation-triggered macros in this blog post.

Files

Equation-Triggered Macro Utility

Code

Module: mMain

'This module demonstrates how ETMUtil can be used. You can modify this macro to accomplish
'what you need, or you can export ETMUtil and import it into your own macro.
    
'Instructions for ETMUtil are in the comments in the ETMUtil class.
    
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim utilworker As ETMUtil
    
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set utilworker = New ETMUtil
    
    If swModel Is Nothing Then End
    If swModel.GetType = swDocDRAWING Then End
    
    'Modify the ETMUtil arguments here
    utilworker.connect swModel, True, True, 0, True
    
    'DO YOUR WORK HERE
End Sub

Class: ETMUtil

'Equation-Triggered Macro (ETM) Utility
'by Keith Rice
'CADSharp.com
'Last modified: 10/24/13
    
'Using equations to run macros allows for powerful integration of macros within models. The
'ETMUtil class makes it easier to use embedded or linked macros in conjunction with
'this technique.
    
'Instructions:
    
'<> For use in parts and assemblies only since drawings do not have equations.
    
'<> An equation must exist in the model that either runs a macro in the Design Binder (embedded)
'   or a macro on the user's hard-drive or network (referenced).
    
'   EMBEDDED
'   "Var1"= 1::swApp.RunAttachedMacro "<macro name>.swp", "<owning module>", "<sub procedure>"
'   For example:
'   "Var1"= 1::swApp.RunAttachedMacro "macro.swp", "mMain", "main"
    
'   REFERENCED
'   "Var2"= 1::Dim lngErr As Long::swApp.RunMacro2 "<macro name>.swp", "<owning module>", "<sub procedure>", swRunMacroDefault, lngErr
'   For example:
'   "Var2"= 1::Dim lngErr As Long::swApp.RunMacro2 "C:\macro.swp", "mMain", "main", swRunMacroDefault, lngErr
    
'<> Modify this macro to include the code you want run when the model rebuilds. Do not
'   modify the ETMUtil class. The only part of mMain you should modify is the
'   end of the main() sub procedure. You can add all of your code here or simply add
'   some calls to other modules and classes. If you want this macro to simply run an
'   external macro, the only code you need to add at the bottom of main() is the
'   ISldWorks::RunMacro2 method.
    
'<> The ETMUtil class comes with five arguments:
    
'   RunOnceOnOpen - if true, the only time the macro will run is when the part is opened.
    
'   AlwaysRunOnOpen - if true, the macro will always run when a part is opened. Otherwise,
'       the macro will never be run again after it is initially run (unless the equation
'       that triggers execution is unsuppressed). Possibly useful in part templates.
    
'   WaitTime - if you want the macro to run consistently while you work, but only once
'       within a certain time period (seconds). For example, entering "10" means that the
'       macro will never run more than once every 10 seconds. Also note that RunOnceOnOpen
'       must be set to False for this option to have any noticeable effect. Finally, a
'       value of zero means that the macro will run every time the equation evaluates.
    
'   DeleteTempFiles - when a macro is run from the Design Binder, a local copy is created
'       in C:\Users\<user>\AppData\Local\Temp. SolidWorks never deletes these, so they can
'       build up over time. If you want Backpack Utility to delete these files for you
'       automatically, make this option True. If you choose False, you will need to manually
'       delete the local files, should you choose to delete them at all. Set this to False
'       if you are running an externally referenced macro.
    
'##### VARIABLES #####
    
Dim m_app As SldWorks.SldWorks
Dim m_model As SldWorks.ModelDoc2
Dim WithEvents m_part As SldWorks.PartDoc
Dim WithEvents m_assy As SldWorks.AssemblyDoc
    
Dim m_alwaysRunOnOpen As Boolean
    
'##### CONNECT ######
    
Sub connect(model As SldWorks.ModelDoc2, RunOnceOnOpen As Boolean, AlwaysRunOnOpen As Boolean, WaitTime As Integer, DeleteTempFiles As Boolean)
    Dim m_waitTime As Long
    Dim m_lastRunTime As Long
    Dim m_currentRunTime As Long
    m_waitTime = WaitTime
    
    m_alwaysRunOnOpen = AlwaysRunOnOpen
    
    Set m_app = Application.SldWorks
    Set m_model = model
    If model.GetType = swDocPART Then
        Set m_part = model
    Else
        Set m_assy = model
    End If
    
    'When a part first loads, the equations are executed before the feature tree is loaded. _
        During this time, however, equations cannot be suppressed and we cannot write to _
        attributes. Consequently, the "work code" is executed twice. To prevent this _
        redundant execution, we can test whether the attribute created by CreateInstance5 _
        is nothing. If it is then we know the feature tree isn't loaded, so we'll just _
        end the macro.
    If JustOpened(m_currentRunTime) Then End
    
    'Quit macro if wait time between executions has not been met
    If WaitTime <> 0 Then
        m_currentRunTime = Timer
        m_lastRunTime = GetLastRunTime
        If m_lastRunTime <> 0 Then
            'ensure that we didn't pass midnight between executions
            If m_currentRunTime < m_lastRunTime Then m_lastRunTime = m_lastRunTime + 86400   'add seconds in a day
            
            If m_currentRunTime < m_lastRunTime + m_waitTime Then
                'wait time has not elapsed; end macro
                End
            Else
                SetRunTime m_currentRunTime 'reset the run time
            End If
        Else
            SetRunTime m_currentRunTime  'set run time for first time
        End If
    End If
    
    'Kill local copies
    If DeleteTempFiles = True Then KillTempFiles
    
    'Allow macro to only run once (when the part is opened)
    If RunOnceOnOpen = True Then SetEqnSuppression False
End Sub
    
Private Function JustOpened(currentRunTime As Long) As Boolean
    JustOpened = False
    
    Dim m_attDef As SldWorks.AttributeDef
    Dim m_att As SldWorks.Attribute
    Dim m_param As SldWorks.Parameter
    Dim m_feat As SldWorks.Feature
    Dim m_featCount As Integer
    
    If m_part Is Nothing Then
        Set m_feat = m_assy.FeatureByName("LastRunTimeAtt")
    Else
        Set m_feat = m_part.FeatureByName("LastRunTimeAtt")
    End If
    If m_feat Is Nothing Then
        'If attribute doesn't exist, create new instance
        Set m_attDef = m_app.DefineAttribute("LastRunTimeAttDef")
        m_attDef.AddParameter "LastRunTime", swParamType_e.swParamTypeDouble, currentRunTime, 0
        m_attDef.Register
        Set m_att = m_attDef.CreateInstance5(m_model, m_model, "LastRunTimeAtt", 1, swAllConfiguration)
        If m_att Is Nothing Then JustOpened = True
    End If
End Function
    
'##### KILL LOCAL COPIES #####
    
'Remove locally-saved copies of the macro run from the design binder. These are _
    normally placed in C:\Users\<name>\AppData\Local\Temp. They are named swMacro<#>.
'Only delete macros beginning with "swMacro" and only begin deleting them if 10 or more _
    exist in the current folder. This greatly reduces the likelihood of a non_temporary _
    macro ever getting deleted.
Private Sub KillTempFiles()
    On Error Resume Next
    Dim strFile As String
    Dim intCount As Integer
    intCount = 1
    
    strFile = Dir(m_app.GetCurrentMacroPathFolder & "\" & "*.swp", vbNormal)
    Do While strFile <> ""
        If Left(strFile, 7) = "swMacro" Then
            intCount = intCount + 1
            If intCount >= 10 Then Kill m_app.GetCurrentMacroPathFolder & "\" & strFile
        End If
        strFile = Dir
    Loop
End Sub
    
'##### PREVENT REDUNDANT EXECUTIONS #####
    
'Use a timer to prevent multiple executions that might occur within a certain span of time. _
    Store the value in an attribute created directly on the model (invisible to user).
Private Sub SetRunTime(currentRunTime As Long)
    Dim m_attDef As SldWorks.AttributeDef
    Dim m_att As SldWorks.Attribute
    Dim m_param As SldWorks.Parameter
    Dim m_feat As SldWorks.Feature
    Dim m_featCount As Integer
    
    If m_part Is Nothing Then
        Set m_feat = m_assy.FeatureByName("LastRunTimeAtt")
    Else
        Set m_feat = m_part.FeatureByName("LastRunTimeAtt")
    End If
    If Not m_feat Is Nothing Then
        'If attribute exists, change existing value
        Set m_att = m_feat.GetSpecificFeature2
        Set m_param = m_att.GetParameter("LastRunTime")
        m_param.SetDoubleValue2 currentRunTime, swInConfigurationOpts_e.swAllConfiguration, Empty
    Else
        'If attribute doesn't exist, create new instance
        Set m_attDef = m_app.DefineAttribute("LastRunTimeAttDef")
        m_attDef.AddParameter "LastRunTime", swParamType_e.swParamTypeDouble, currentRunTime, 0
        m_attDef.Register
        Set m_att = m_attDef.CreateInstance5(m_model, m_model, "LastRunTimeAtt", 1, swAllConfiguration)
        If m_att Is Nothing Then End
    End If
End Sub
    
'Gets the time elapsed since the last running of the macro. If less than m_waitTime then _
    do not run the macro again.
Private Function GetLastRunTime() As Long
    Dim m_feat As SldWorks.Feature
    Dim m_att As SldWorks.Attribute
    Dim m_param As SldWorks.Parameter
    
    If m_part Is Nothing Then
        Set m_feat = m_assy.FeatureByName("LastRunTimeAtt")
    Else
        Set m_feat = m_part.FeatureByName("LastRunTimeAtt")
    End If
    If m_feat Is Nothing Then
        GetLastRunTime = 0
        Exit Function
    End If
    
    Set m_att = m_feat.GetSpecificFeature2
    Set m_param = m_att.GetParameter("LastRunTime")
    GetLastRunTime = m_param.GetDoubleValue
End Function
    
'##### EXECUTE CODE ONLY ONCE, WHEN PART IS OPENED #####
    
Private Sub SetEqnSuppression(active As Boolean)
    Dim m_eqnMgr As SldWorks.EquationMgr
    Dim i As Integer
    
    Set m_eqnMgr = m_model.GetEquationMgr
    For i = 0 To m_eqnMgr.GetCount - 1
        'use upper case because API calls don't "snap" to proper case in equation editor
        If InStr(1, UCase(m_eqnMgr.Equation(i)), "RUNATTACHEDMACRO") <> 0 Then
            'MsgBox m_eqnMgr.Suppression(i)
            If active Then
                m_eqnMgr.Suppression(i) = 0     'true
            Else
                m_eqnMgr.Suppression(i) = -1    'false
            End If
            'MsgBox m_eqnMgr.Suppression(i)
        End If
    Next i
End Sub
    
'##### TURN EQUATION BACK ON WHEN SAVED #####
    
Private Function m_part_FileSaveNotify(ByVal FileName As String) As Long
    If m_alwaysRunOnOpen = True Then SetEqnSuppression True
End Function
    
Private Function m_part_FileSaveAsNotify2(ByVal FileName As String) As Long
    If m_alwaysRunOnOpen = True Then SetEqnSuppression True
End Function
    
Private Function m_part_FileSavePostNotify(ByVal saveType As Long, ByVal FileName As String) As Long
    If m_alwaysRunOnOpen = True Then SetEqnSuppression False
End Function
    
Private Function m_assy_FileSaveNotify(ByVal FileName As String) As Long
    If m_alwaysRunOnOpen = True Then SetEqnSuppression True
End Function
    
Private Function m_assy_FileSaveAsNotify2(ByVal FileName As String) As Long
    If m_alwaysRunOnOpen = True Then SetEqnSuppression True
End Function
    
Private Function m_assy_FileSavePostNotify(ByVal saveType As Long, ByVal FileName As String) As Long
    If m_alwaysRunOnOpen = True Then SetEqnSuppression False
End Function