vbacatia

How to the Part Number from Selection CATIA VBA? Error: Catastrophic failure


I would like to get the Part Number from Selection. I guess because I get the info from Enovia5 so I encounter an issue: some I can get the Part Number and some return Catastrophic failure. I ensure the selection always has 1 item only.

   CATIA.ActiveDocument.Selection.Item(1).LeafProduct.PartNumber '<~~~ sometimes works, sometimes does not. 

Note: I use TypeName to check what type of file gets selected, all return Document but the ones return error actually have .CATPart when I view their properties. Error mismatch will return if I try to declare it as Part or PartDocument.

Dim myPart as Part
Set myPart = CATIA.ActiveDocument.Selection.Item(1).value '<~~~ Mismatch
Set myPart = CATIA.ActiveDocument.Selection.Item(1).LeafProduct'<~~~ Mismatch

Dim myPartDoc as PartDocument
Set myPart = CATIA.ActiveDocument.Selection.Item(1).value '<~~~ Mismatch
Set myPart = CATIA.ActiveDocument.Selection.Item(1).LeafProduct'<~~~ Mismatch

Solution

  • LeafProduct does not return Part nor PartDocument. It returns Product object. In your example, you are filling variables with objects of wrong type.

    Product object is something like container around Part or Product(Product like assembly in catia)

    There can be several problems. At first, I'd try to work with selection object separately.

    Dim oDoc As Document
    Set oDoc = CATIA.ActiveDocument
    
    Dim oSel as Selection
    Set oSel = oDoc.Selection
    
    If oSel.Count = 1 Then
        Dim oProd as Product
        Set oProd = oSel.Item2(1).LeafProduct
    
        MsgBox oProd.PartNumber
    Else
        MsgBox "More objects selected!!!"
    End If
    

    Then if you want to get Part object from this product and you are sure it is product which is container around part and not around Product(Assembly), you can get it easily like that:

    Dim oPartDocument As PartDocument
    Set oPartDocument = oProd.ReferenceProduct.Parent
    
    Dim oPart As Part
    Set oPart = oPartDocument.Part    
    

    In your catia installation is file which can helps you to understand how to use API for automation. It is documentation for automation. You can find it here:

    enter image description here