vb.net how to exit recursive loop

Viewed 353

I'm making a code for a 3D Program CATIA and the code runs through all tree with recursive loop. I would like to exit the recursive loop, after it find a specific product. But my code keeps running , even though he found it. I wrote roughly meins. What did I make a mistake in there?

Private Sub TestMain
   .....
   call TestMainChildren
   .....
End Sub

Private Sub TestMainChildren
  For Each item In product
      .....
      If itemName = "SearchName" then
         MsgBox("Found!")
         Exit Sub
      End if
      ......
      Call TestMainChildren
   Next
End Sub

enter image description here

2 Answers

place

exit for

after fulfilled condition inside loop

edited//

Private Sub TestMain
 .....
 call TestMainChildren
 .....
End Sub

Private Sub TestMainChildren
   For Each item In product
    .....
     If itemName = "SearchName" then
      MsgBox("Found!")
      Exit for
  End if
  ......
  'Call TestMainChildren - delete this
   Next
End Sub

To make this recursive you need to pass a starting object to the function, in this case products. Then while you are looking at child objects, only pass product collections recursively.

Private Sub TestMain    
    Dim searchName As String
    searchName = "SearchName"

    ' Start with the selected object
    Dim doc As Document
    Set doc = CATIA.ActiveDocument
    Dim prod As Product
    Set prod = doc.Product

    Dim foundItem As Object
    foundItem = TestMainChildren(doc.Selection.Item(1).Value, searchName)

    MsgBox "Found: " & foundItem.Name
End Sub

Private Function TestMainChildren(ByRef catiaObject As Object, ByVal searchName As String) As Object
    Dim item As Object
    For Each item In catiaObject.Items
        If item.Name = "SearchName" then
            Set TestMainChildren = item
            Exit For
        End if

        Dim catiaType As String
        catiaType = TypeName(item)
        If catiaType = "Product" Then
            TestMainChildren item, searchName
        End If
    Next
End Sub

WARNING: This is completely untested vaporware. You will have to modify it to fit your environment, and requirements. Then do proper testing and debugging.

Related