Traverse features in order using recursion

You need to be logged in to view this content. Please login or become a member.

 Rick Barry Womens Jersey

5 Comments

  1. Bernd

    Hi. I have a question. When I traverse through the components, how can I get access to a custom property of the actual component?

  2. Harvard

    Thought this might be helpful to others using this for anything that will have more then 255 lines printed. This takes what would be printed to the Immediate Window and puts it in a text file. The text file needs to be saved and the location needs to be put into the string after Open.

    ‘Demonstrates how to traverse the feature tree of any SolidWorks document _
    in order using a single recursive function.

    ‘Preconditions: Document is open.
    ‘Results: Names and types of all features are printed in the order they appear _
    in the feature tree, with exceptions: _
    a. Lightweight components or any other type of component not fully loaded _
    into memory cannot have some or all features traversed. _
    b. Smart fasteners may be listed in the tree after the component they are _
    fastened to rather than after the Smart Fasteners folder. _
    c. This macro only traverses true features. Not all items listed in the _
    feature manager tree are true features. Use IFeature::GetSpecificFeature2 _
    to get access to a feature’s underlying items.

    ‘Written by Keith Rice
    ‘CADSharp LLC
    ‘www.cadsharp.com

    ‘======================= With Printing to .txt file!!!! ==========================

    Dim n As Integer
    Dim s As String

    Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2

    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc

    n = FreeFile()
    Open “====File Location Here====” For Output As #n

    s = “Active model: ” & swModel.GetTitle
    Print #n, s

    TraverseModel swModel, 1
    End Sub

    Private Sub TraverseModel(model As Object, nLevel As Integer)
    Dim swFeat As SldWorks.Feature
    Dim swSubFeat As SldWorks.Feature
    Dim swComp As SldWorks.Component2
    Dim strPad As String

    For i = 1 To nLevel
    strPad = strPad & vbTab
    Next i

    Set swFeat = model.FirstFeature

    Do While Not swFeat Is Nothing
    s = strPad & swFeat.Name & ” (” & swFeat.GetTypeName & “)”
    Print #n, s

    If swFeat.GetTypeName = “Reference” Then
    Set swComp = swFeat.GetSpecificFeature2
    TraverseModel swComp, nLevel + 1
    Else
    Set swSubFeat = swFeat.GetFirstSubFeature
    Do While Not swSubFeat Is Nothing
    s = strPad & vbTab & swSubFeat.Name & ” (” & swSubFeat.GetTypeName & “)”
    Print #n, s
    Set swSubFeat = swSubFeat.GetNextSubFeature
    Loop
    End If

    Set swFeat = swFeat.GetNextFeature
    Loop
    End Sub

Questions and Comments

You must be logged in to post a comment.