You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CATIA宏代码优化需求:实现可见部件的反向选择

解决方案:仅对可见部件执行反向选择

原代码中oGroup.FillSelWithInvert会对整个装配体执行反向选择,要实现仅针对可见部件的反向选择,需要先筛选出当前可见的部件集合,再排除原选中的内容,最后选中剩余的可见部件。以下是优化后的代码:

Sub CATMain()
    Dim selection1 As Selection
    Set selection1 = CATIA.ActiveDocument.Selection
    
    If selection1.Count > 0 Then
        ' 保存原选中的部件到集合,用于后续排除
        Dim originalSel As New Collection
        Dim i As Integer
        For i = 1 To selection1.Count
            originalSel.Add selection1.Item2(i)
        Next i
        
        ' 获取当前装配体的根产品
        Dim rootProd As Product
        Set rootProd = CATIA.ActiveDocument.Product
        
        ' 遍历所有部件,筛选出可见的部件
        Dim visibleParts As New Collection
        Call GetVisibleComponents(rootProd, visibleParts)
        
        ' 从可见部件中排除原选中的内容,得到要反向选择的集合
        Dim targetSel As New Collection
        Dim comp As Object
        Dim isInOriginal As Boolean
        For Each comp In visibleParts
            isInOriginal = False
            For Each origComp In originalSel
                If comp Is origComp Then
                    isInOriginal = True
                    Exit For
                End If
            Next origComp
            If Not isInOriginal Then
                targetSel.Add comp
            End If
        Next comp
        
        ' 清空原选择并选中目标部件
        selection1.Clear
        For Each comp In targetSel
            selection1.Add comp
        Next comp
    Else
        MsgBox "No components selected", vbExclamation, "Isolate Components"
        Exit Sub
    End If
End Sub

' 递归遍历装配体,收集所有可见的部件
Sub GetVisibleComponents(prod As Product, col As Collection)
    Dim childProd As Product
    ' 检查当前产品是否可见
    If prod.Visible Then
        col.Add prod
    End If
    ' 递归遍历子部件
    For Each childProd In prod.Products
        Call GetVisibleComponents(childProd, col)
    Next childProd
End Sub

关键改动说明

  • 保存原选中集合:先把用户初始选中的部件存入集合,用于后续排除操作
  • 递归筛选可见部件:通过GetVisibleComponents子过程遍历整个装配体,只收集Visible属性为True的部件
  • 反向选择逻辑:从可见部件集合中移除原选中的内容,剩余部分就是需要选中的反向结果
  • 替换原生方法:不再使用oGroup.FillSelWithInvert,而是通过手动筛选实现精准的可见部件反向选择

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:25:02