MACRO LIBRARY

Get distance between two largest planar faces in a body

Free public access. No account or subscription required.

Files

Get distance between two largest planar faces in a body

Code

Module: mMain

Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim swBody As SldWorks.Body2
    Dim swSelMgr As SldWorks.SelectionMgr
    
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swSelMgr = swModel.SelectionManager
    Set swBody = swSelMgr.GetSelectedObject6(1, -1)
    
    If swBody Is Nothing Then
        MsgBox "Please select a body."
        Exit Sub
    End If
    
    Debug.Print GetDistanceBetweenTwoLargestPlanarFaces(swModel, swBody)
End Sub
    
Private Function GetDistanceBetweenTwoLargestPlanarFaces(swModel As SldWorks.ModelDoc2, _
    swBody As SldWorks.Body2) As Double
    
    Dim vFaces As Variant
    Dim swFace As SldWorks.Face2
    Dim swLargestPlanarFaces(1) As SldWorks.Face2
    Dim swSurf As SldWorks.Surface
    Dim i As Integer
    
    vFaces = swBody.GetFaces
    
    If IsEmpty(vFaces) Or UBound(vFaces) < 1 Then
        GetDistanceBetweenTwoLargestPlanarFaces = -1
        Exit Function
    End If
    
    For i = 0 To UBound(vFaces)
        Set swFace = vFaces(i)
        Set swSurf = swFace.GetSurface
        If swSurf.IsPlane Then
            If swLargestPlanarFaces(0) Is Nothing Then
                Set swLargestPlanarFaces(0) = swFace
            Else
                If swLargestPlanarFaces(1) Is Nothing Then
                    Set swLargestPlanarFaces(1) = swFace
                Else
                    If swFace.GetArea > swLargestPlanarFaces(0).GetArea Then
                        Set swLargestPlanarFaces(1) = swLargestPlanarFaces(0)
                        Set swLargestPlanarFaces(0) = swFace
                    Else
                        If swFace.GetArea > swLargestPlanarFaces(1).GetArea Then Set swLargestPlanarFaces(1) = swFace
                    End If
                End If
            End If
        End If
    Next i
    
    If swLargestPlanarFaces(0) Is Nothing Or swLargestPlanarFaces(1) Is Nothing Then
        GetDistanceBetweenTwoLargestPlanarFaces = -1
    Else
        Dim swEnt As SldWorks.Entity
        Set swEnt = swLargestPlanarFaces(0)
        swEnt.Select False
        Set swEnt = swLargestPlanarFaces(1)
        swEnt.Select True
        
        Dim swMeasure As SldWorks.Measure
        Set swMeasure = swModel.Extension.CreateMeasure
        swMeasure.Calculate Nothing
        GetDistanceBetweenTwoLargestPlanarFaces = swMeasure.Distance
    End If
End Function