You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用VBA导出CATIA的STP文件时遇编译错误:用户定义类型未定义

解决CATIA VBA编译错误:用户定义类型未定义(Product)

出现这个错误是因为Product是CATIA专属的对象类型,VBA编辑器默认未识别到它,有两种解决方式:

方法一:添加CATIA类型库引用

  • 打开CATIA的VBA编辑器(按Alt+F11)
  • 点击顶部菜单栏的【工具】→【引用】
  • 在弹出的引用列表中,找到并勾选CATIA V5 Object Library(不同版本名称可能略有差异,比如包含"Automation"字样)
  • 点击【确定】,此时VBA就能识别Product类型,编译错误会消失。

方法二:改用通用对象类型(无需添加引用)

如果不想添加类型库引用,直接把代码中所有Product类型声明替换为Object即可,修改后的代码如下:

Sub CATMain()
    
    'Error handling in case of empty CATIA window, no open objects.
    On Error Resume Next
    Set currDocument = CATIA.ActiveDocument
    
    If Err.Number <> 0 Then
        Err.Clear
        MsgBox "An assembly file needs to be opened and active for this macro.", vbCritical, "Wrong context"
        Exit Sub
    End If  

    If InStr(CATIA.ActiveDocument.Name,".CATProduct") Then
        sFilePath = CATIA.ActiveDocument.Path & "\"
        ExportNextProduct CATIA.ActiveDocument.Product, sFilePath
    Else
        MsgBox "An assembly file needs to be opened and active for this macro.", vbCritical, "Wrong context"
    End If
    
    MsgBox "STP file export complete.", vbInformation, "Finished"   
    
End Sub

Sub ExportNextProduct(oCurrentProduct As Object, sFilePath As String)
    Dim oCurrentTreeNode As Object
    Set FileSys = CATIA.FileSystem
    
    For i = 1 To oCurrentProduct.Products.Count
        Set oCurrentTreeNode = oCurrentProduct.Products.Item(i)
        sFileName = oCurrentTreeNode.Nomenclature & " " & oCurrentTreeNode.DescriptionRef & ".stp"    

        If oCurrentTreeNode.Source = catProductMade And oCurrentTreeNode.Definition <> "ASM" Then
            If FileSys.FileExists(sFilePath & sFileName) = False Then
                oCurrentTreeNode.ReferenceProduct.Parent.ExportData sFilePath & sFileName, "stp"
            End If
        End If
        
        If oCurrentTreeNode.Products.Count > 0 And oCurrentTreeNode.Definition = "ASM" Then
            ExportNextProduct oCurrentTreeNode, sFilePath
        End If
    Next    

End Sub

额外提示

  • 代码里把字符串连接符+改成了&,避免因变量类型混合导致的意外错误
  • 统一了IF的写法为If,符合VBA的编码规范

内容的提问来源于stack exchange,提问作者Lyrk

火山引擎 最新活动