MACRO LIBRARY

Rename solid bodies after rebuild

Free public access. No account or subscription required.

Files

Rename solid bodies after rebuild

Code

Module: mMain

'Regeneration post-notify example. In this example, post-regen the body names _
    will always be Body#, where # equals the list location
'Preconditions: Part is open. Run macro, which creates a "listener" for rebuild _
    notification. Rename code is executed upon rebuild of document.
    
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
'Change prefix here
Const BODY_NAME_PREFIX As String = "Body"
    
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim rebuild_listener As clsRebuildListener
    
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    
    Set rebuild_listener = New clsRebuildListener
    rebuild_listener.connect swApp, swModel, BODY_NAME_PREFIX
End Sub
    
'Notes: Solid body items may change list location on rebuild or rollback.

Class: clsRebuildListener

Dim WithEvents swPart As SldWorks.PartDoc
Dim strBodyNamePrefix As String
    
Public Sub connect(swApp As SldWorks.SldWorks, swModel As SldWorks.ModelDoc2, _
    bodynameprefix As String)
    Set swPart = swModel
    
    strBodyNamePrefix = bodynameprefix
    
    Debug.Print "listener on"
End Sub
    
Private Function swPart_RegenPostNotify2(ByVal stopFeature As Object) As Long
    Dim swBody As SldWorks.Body2
    Dim swBodyFolder As SldWorks.BodyFolder
    Dim swFeat As SldWorks.Feature
    Dim vBodies As Variant
    Dim i As Integer
    
    Set swFeat = swPart.FirstFeature
    Do While Not swFeat Is Nothing
        If swFeat.GetTypeName2 = "SolidBodyFolder" Then Exit Do
        Set swFeat = swFeat.GetNextFeature
    Loop
    
    Set swBodyFolder = swFeat.GetSpecificFeature2
    vBodies = swBodyFolder.GetBodies
    If IsEmpty(vBodies) = False Then
        For i = 0 To UBound(vBodies)
            If swPart.FeatureManager.IsNameUsed(swBodyName, strBodyNamePrefix & i + 1) = False Then _
                vBodies(i).Name = strBodyNamePrefix & i + 1
        Next i
    End If
End Function
    
'Note: When you edit a sketch, a rebuild notification is fired.