MACRO LIBRARY

Add, subtract, or combine two selected bodies

Free public access. No account or subscription required.

Files

Add, subtract, or combine two selected bodies Test part

Code

Module:

'Demonstrates using IBody2::Operations2 to add, subtract, and intersect bodies. How the _
    bodies are affected depends on which body is specified as the main body vs tool body.
    
'Preconditions: Part with two bodies is open and they are both selected in FM tree. The _
    body selected first is the main body, the other selection is the tool body.
'Results: Original bodies are made invisible and resulting bodies are visible and green.
    
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim swSelMgr As SldWorks.SelectionMgr
Dim swBody1 As SldWorks.Body2
Dim swBody2 As SldWorks.Body2
Dim swFinalBody As SldWorks.Body2
Dim vBodies As Variant
Dim lngErrors As Long
Dim i As Integer
    
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swSelMgr = swModel.SelectionManager
    
    Set swBody1 = swSelMgr.GetSelectedObject6(1, -1)
    swModel.HideSolidBody
    Set swBody1 = swBody1.Copy
    
    Set swBody2 = swSelMgr.GetSelectedObject6(2, -1)
    swModel.HideSolidBody
    Set swBody2 = swBody2.Copy
    
    'Add
    'vBodies = swBody1.Operations2(SWBODYADD, swBody2, lngErrors)
    
    'Subtract
    vBodies = swBody1.Operations2(SWBODYCUT, swBody2, lngErrors)
    
    'Intersect
    'vBodies = swBody1.Operations2(SWBODYINTERSECT, swBody2, lngErrors)
    
    If lngErrors <> 0 Then
        Debug.Print "Error code: " & lngErrors
        Exit Sub
    End If
    
    If IsEmpty(vBodies) Then
        Debug.Print "Number of result bodies: 0"
    Else
        Debug.Print "Number of result bodies: " & UBound(vBodies) + 1
        
        For i = 0 To UBound(vBodies)
            Set swFinalBody = vBodies(i)
            swFinalBody.Display3 swModel, RGB(0, 255, 0), 0
            Set swPart = swModel
            swPart.CreateFeatureFromBody3 swFinalBody, False, 0
        Next i
    
    End If
    
    Set swFinalBody = Nothing
    Set swBody1 = Nothing
    Set swBody2 = Nothing
    
    swModel.EditRebuild3
End Sub
    
'Notes:
'For two non-intersecting bodies...
    'Add: No errors, main body is the result
    'Cut: No errors, main body is the result
    'Intersect: No errors, no result bodies
    
'Operations2 makes the main and tool IBody2 pointers invalid immediately after use.