如何在CATIA宏中获取几何坐标?代码无输出问题求助
CATIA VBA代码无输出问题修复
你的代码没弹出MsgBox是因为存在多处语法和逻辑错误,导致代码无法正常执行,以下是问题点和修正方案:
主要问题点
- 变量未声明:
Separator、arrXYZ、bb、s等变量未提前声明,CATIA VBA默认隐式变量会引发潜在错误。 - 循环变量覆盖:先将
cc赋值为HybridShapes集合,循环里又把cc改成单个HybridShape对象,第二次循环时cc.Count直接报错,中断代码执行。 - 语法不完整:
If strReturn = "Normal" Then缺少对应的End If,代码无法运行。 - 坐标数组未初始化:调用
GetCoordinates前未声明arrXYZ为Variant类型,无法存储坐标值。
修正后的代码
Option Explicit Sub CatMain() Dim varFilter(1) As Variant Dim objSel As Selection Dim objSelLB As Object Dim strReturn As String Dim strMsg As String Dim bb As Object ' 存储选中的Body或HybridBody Dim hybridShapes As HybridShapes ' 几何对象集合 Dim targetShape As Object ' 单个几何对象 Dim arrXYZ As Variant ' 坐标数组 Dim s As Integer ' 循环计数器 Const Separator As String = " | " ' 定义分隔符常量 varFilter(0) = "Body" varFilter(1) = "HybridBody" Set objSel = CATIA.ActiveDocument.Selection Set objSelLB = objSel strMsg = "Select a body or geometrical set…" objSel.Clear strReturn = objSelLB.SelectElement2(varFilter, strMsg, False) If strReturn = "Normal" Then If objSel.Count2 > 0 Then Set bb = objSel.Item(1).Value ' 区分HybridBody和Body的不同处理逻辑 If TypeName(bb) = "HybridBody" Then Set hybridShapes = bb.HybridShapes For s = 1 To hybridShapes.Count Set targetShape = hybridShapes.Item(s) targetShape.GetCoordinates arrXYZ MsgBox targetShape.Parent.Name & Separator & targetShape.Name & Separator & _ arrXYZ(0) & Separator & arrXYZ(1) & Separator & arrXYZ(2) & vbLf Next s ElseIf TypeName(bb) = "Body" Then Dim bodyShapes As Shapes Set bodyShapes = bb.Shapes For s = 1 To bodyShapes.Count Set targetShape = bodyShapes.Item(s) targetShape.GetCoordinates arrXYZ MsgBox targetShape.Parent.Name & Separator & targetShape.Name & Separator & _ arrXYZ(0) & Separator & arrXYZ(1) & Separator & arrXYZ(2) & vbLf Next s End If End If End If ' 补充缺失的闭合语句 End Sub
额外说明
- 加入
Option Explicit强制变量声明,提前排查未定义变量的错误。 - 区分
HybridBody(几何集)和Body(实体)的处理逻辑,因为两者获取几何特征的属性不同。 - 用不同变量名存储集合和单个对象,避免循环中覆盖变量导致的错误。
- 提前定义
Separator常量,避免未定义变量的问题。
内容的提问来源于stack exchange,提问作者Salome
相关产品推荐
相关产品推荐

