MACRO LIBRARY

Get assembly's maximum depth

Free public access. No account or subscription required.

Files

Get assembly's maximum depth

Code

Module: mMain

'Returns the maximum assembly depth
    
'Modified by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
'Preconditions: Document is open.
'Results: Assembly depth is returned. If a drawing or part, 0 is returned.
    
Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    
    If swModel Is Nothing Then Exit Sub
    
    Debug.Print mTraverse.GetMaxDepth(swModel)
End Sub

Module: mTraverse

Dim intMaxCompLevel As Integer
    
Function GetMaxDepth(swModel As SldWorks.ModelDoc2) As Integer
    If swModel.GetType <> swDocASSEMBLY Then
        GetMaxDepth = 0
        Exit Function
    End If
    
    Dim swRootComp As SldWorks.Component2
    Set swRootComp = swModel.ConfigurationManager.ActiveConfiguration.GetRootComponent3(True)
    
    intMaxCompLevel = 0
    
    If swModel.GetType = swDocASSEMBLY Then Call TraverseComponent(swRootComp, 1)
    
    GetMaxDepth = intMaxCompLevel - 1
End Function
    
Private Sub TraverseComponent(swComp As SldWorks.Component2, nLevel As Long)
    Dim vChildComp As Variant
    Dim swChildComp As SldWorks.Component2
    Dim i As Long
    
    vChildComp = swComp.GetChildren
    For i = 0 To UBound(vChildComp)
        Set swChildComp = vChildComp(i)
        Call TraverseComponent(swChildComp, nLevel + 1)
    Next i
    
    If nLevel > intMaxCompLevel Then intMaxCompLevel = nLevel
End Sub