AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79541100
Accepted
New User With you
New User With you
Asked: 2025-03-28 18:00:48 +0800 CST2025-03-28 18:00:48 +0800 CST 2025-03-28 18:00:48 +0800 CST

CATIA - Operação de espessura MACRO

  • 772

Eu desenvolvi uma macro que pode criar uma operação de espessura em um sólido colado de outro Catpart. Está funcionando, mas o problema que estou enfrentando é que os IDs de faces que tenho neste código às vezes não estão alinhados com o que tenho na operação. Existe uma maneira de evitar IDs de faces e capturar todas as faces automaticamente do sólido colado e fazer a operação de espessura. No código abaixo, você pode ver muitos IDs de faces, às vezes funciona, às vezes Catia pergunta sobre faces ausentes. Muito obrigado

insira a descrição da imagem aqui

Sub ThicknessOP()
    Dim partDocument1 As Object
    Set partDocument1 = CATIA.activeDocument

    Dim part1 As Object
    Set part1 = partDocument1.part

    Dim bodies1 As Object
    Set bodies1 = part1.bodies

    ' Modify input body name and thickness name here
    Dim bodyName As String
    Dim thicknessName As String

    bodyName = "FOAM_HOLES" ' Change this to the desired body name
    thicknessName = "ThicknessOperation" ' Change this to the desired thickness name

    Dim body1 As Object
    Set body1 = bodies1.Item(bodyName)

    Dim shapes1 As Object
    Set shapes1 = body1.Shapes

    ' Try to retrieve the thickness shape
    Dim thickness1 As Object
    On Error Resume Next ' Enable error handling
    Set thickness1 = shapes1.Item(thicknessName)
    On Error GoTo 0 ' Disable error handling

    ' Check if the thickness has been retrieved
    If thickness1 Is Nothing Then
        MsgBox "Error: " & thicknessName & " not found in " & bodyName & ". Please verify the name.", vbExclamation
        Exit Sub
    End If

    Dim solid1 As Object
    Dim solidFound As Boolean
    solidFound = False

    ' Loop through all solids in the body to find the desired solid
    Dim i As Integer
    For i = 1 To shapes1.Count
        Set solid1 = shapes1.Item(i)
        If solid1.Name Like "Solid.*" Then
            solidFound = True
            Exit For
        End If
    Next i

    If Not solidFound Then
        MsgBox "Error: Solid not found in " & bodyName & ". Please verify the name.", vbExclamation
        Exit Sub
    End If

    Dim faceIds As Variant
    faceIds = Array(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38) ' Face IDs from 4 to 38
    
    Dim successfullyAdded As Integer
    Dim failedIds As String
    successfullyAdded = 0
    failedIds = ""

    ' Try to add each face to the thickness operation
    For i = LBound(faceIds) To UBound(faceIds)
        Dim reference As Object
        On Error Resume Next ' Enable error handling
        Set reference = part1.CreateReferenceFromBRepName("RSur:(Face:(Brp:(" & solid1.Name & ";%" & faceIds(i) & ");None:();Cf11:());WithTemporaryBody;WithoutBuildError;WithSelectingFeatureSupport;MFBRepVersion_CXR15)", solid1)
        If Err.Number = 0 Then
            thickness1.AddFaceToThicken reference
            successfullyAdded = successfullyAdded + 1
        Else
            failedIds = failedIds & faceIds(i) & ", "
        End If
        On Error GoTo 0 ' Disable error handling
    Next i

    ' Update the thickening object
    part1.UpdateObject thickness1
    part1.Update

    ' Provide feedback on the operation
    If successfullyAdded > 0 Then
        MsgBox successfullyAdded & " face(s) added to the thickness operation." & vbCrLf & _
               "Failed face IDs: " & IIf(failedIds = "", "None", Left(failedIds, Len(failedIds) - 2)), vbInformation
    Else
        MsgBox "No faces were successfully added to the thickness operation." & vbCrLf & _
               "Failed face IDs: " & IIf(failedIds = "", "None", Left(failedIds, Len(failedIds) - 2)), vbExclamation
    End If

End Sub
vba
  • 1 1 respostas
  • 53 Views

1 respostas

  • Voted
  1. Best Answer
    Shrotter
    2025-03-28T21:37:24+08:002025-03-28T21:37:24+08:00

    Você pode obter as faces cilíndricas de um corpo selecionando o corpo e procurando pelas faces. Ao fazer um loop sobre as faces e verificar o tipo, você pode escolher as faces certas.

    Um exemplo de código:

    Sub CATMain()
    
    Dim oPartDoc As Document
    Dim oSel As Selection
    Dim oPart as Part
    Dim oBody as Body
    Dim oShapeFactory As Factory
    Dim oThickness As Thickness
    Dim i as Long
    Dim bodyName as String
    
    'start
    bodyName = "FOAM_HOLES"
    
    Set oPartDoc = CATIA.ActiveDocument
    Set oSel = oPartDoc.Selection
    Set oPart = oPartDoc.Part
    Set oShapeFactory = oPart.ShapeFactory
    
    'get body
    Set oBody = oPart.Bodies.Item(bodyName)
    
    'select body and search for faces
    oSel.Clear
    oSel.Add oBody
    oSel.Search "Topology.CGMFace,sel"
    
    'create thickness and add cylindrical faces
    If oSel.Count2 <> 0 Then
        oPart.InWorkObject = oBody
        Set oThickness = oShapeFactory.AddNewThickness(nothing, 5.000000)
    
        For i = 1 to oSel.Count2
            if oSel.Item2(i).Type = "CylindricalFace" Then
                oThickness.AddFaceToThicken oSel.Item2(i).Value  'or .Reference
            end if
        Next
        
        oPart.UpdateObject oBody
    
    End If
    
    End Sub
    
    • 0

relate perguntas

  • Pesquise e formate texto entre parênteses

  • Atribuindo formas a um grupo no PowerPoint usando VBA

  • Word VBA, mova o cursor para o início do próximo número em uma lista numerada

  • Execute uma regra do Outlook para cada conta usando macro vba

  • Extrair arquivos de um objeto OLE do Access

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve