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

如何编写CATIA VBA宏实现工程图指定文本搜索替换?

CATIA VBA宏:批量替换工程图中的特定文本

嘿,作为CATIA VBA新手,能想着用宏来自动化更新图纸文本真的超赞!我特意给你写了一段带详细注释的代码,完全适配你的需求——搜索工程图里的DD/MM/YYY文本,替换成你输入的内容。

完整代码

Sub UpdateDateText()
    Dim catDoc As Document
    Dim drawingDoc As DrawingDocument
    Dim drawingSheet As DrawingSheet
    Dim drawingText As DrawingText
    Dim userInput As String
    Dim foundCount As Integer
    
    ' 初始化找到的文本数量
    foundCount = 0
    
    ' 检查当前是否打开了CATIA文档
    On Error Resume Next
    Set catDoc = CATIA.ActiveDocument
    On Error GoTo 0
    
    If catDoc Is Nothing Then
        MsgBox "请先打开一个CATIA工程图文档!", vbExclamation
        Exit Sub
    End If
    
    ' 确认当前文档是工程图
    If catDoc.Type <> "DrawingDocument" Then
        MsgBox "当前打开的不是工程图文档,请切换到.CATDrawing文件!", vbExclamation
        Exit Sub
    End If
    
    Set drawingDoc = catDoc
    
    ' 弹出输入框让用户输入要替换的文本
    userInput = InputBox("请输入要替换成的文本:", "替换文本输入", "")
    ' 如果用户取消输入,直接退出
    If userInput = "" Then
        MsgBox "未输入替换内容,宏已终止。", vbInformation
        Exit Sub
    End If
    
    ' 遍历所有图纸页面
    For Each drawingSheet In drawingDoc.Sheets
        ' 遍历当前页面的所有文本元素
        For Each drawingText In drawingSheet.Views.ActiveView.DrawingTexts
            ' 检查文本内容是否包含目标字符串"DD/MM/YYY"
            If InStr(1, drawingText.Text, "DD/MM/YYY", vbTextCompare) > 0 Then
                ' 替换文本
                drawingText.Text = Replace(drawingText.Text, "DD/MM/YYY", userInput, , , vbTextCompare)
                foundCount = foundCount + 1
            End If
        Next
    Next
    
    ' 提示结果
    If foundCount > 0 Then
        MsgBox "成功替换了" & foundCount & "处文本!", vbInformation
    Else
        MsgBox "未找到任何包含""DD/MM/YYY""的文本。", vbInformation
    End If
End Sub

新手操作步骤

  • 打开CATIA,按下Alt+F8打开宏管理器
  • 点击「新建」,给宏起个名字(比如UpdateDateText),选择保存位置(建议存在CATIA的默认宏路径)
  • 把上面的代码复制粘贴到宏编辑器里,点击保存
  • 确保你已经打开了目标工程图,然后点击宏管理器里的「运行」,跟着提示输入替换文本就行!

小提示(针对新手)

  • 如果需要精确匹配DD/MM/YYY(而不是包含它的文本),把代码里的InStr(...) > 0改成drawingText.Text = "DD/MM/YYY"就行
  • 代码里的vbTextCompare是不区分大小写的匹配,如果要严格区分大小写,改成vbBinaryCompare
  • 运行前记得备份你的工程图,万一操作失误还能恢复~

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

火山引擎 最新活动