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

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
Set TestMainChildren = TestMainChildren(item, searchName)
End If
Next item
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With