Anda di halaman 1dari 2

Dim bodyCount As Integer

Sub CATMain()

'keep track of the number of bodies copied


bodyCount = 0

'get the root product of the assembly


Dim rootProduct As Product
Set rootProduct = CATIA.ActiveDocument.Product

'add a new part to the root of the assembly.


'randomize it's name so it always has a unique name, this avoids typical Catia
problems with
'deleting it and then trying to create a document with an already used name
Call Randomize
suffix = Rnd(1) * 10000
Dim newPartProd As Product
Set newPartProd = rootProduct.Products.AddNewComponent("Part", "ProductAsPart_" &
suffix)

Dim newPart As Part


Set newPart = newPartProd.ReferenceProduct.Parent.Part

'now loop though all the child products of the root product.
Dim subProduct As Product
For i = 1 To rootProduct.Products.Count
Set subProduct = rootProduct.Products.Item(i)

'call the (recursive) function to copy it's parts to the new part
Call CopySubProduct(subProduct, newPart)
Next

rootProduct.Update
MsgBox bodyCount & " Part Bodies copied"

End Sub

Sub CopySubProduct(aSubProduct As Product, targetPart As Part)

'if it is the target part itself, then skip it...


If aSubProduct.ReferenceProduct.Parent.Name = targetPart.Parent.Name Then
Debug.Print "Thats the target part..."
Exit Sub

' if it is a part, make sure the part body is published and then
' copy-paste-special-as-result the part body into the new part
ElseIf InStr(aSubProduct.ReferenceProduct.Parent.Name, ".CATPart") =
Len(aSubProduct.ReferenceProduct.Parent.Name) - 7 Then
Debug.Print aSubProduct.Name; " is a Part"
Call CopyPasteAsResultPartBody(aSubProduct, targetPart)

'if it is a sub assembly recursively call this subroutine on it


ElseIf InStr(aSubProduct.ReferenceProduct.Parent.Name, ".CATProduct") =
Len(aSubProduct.ReferenceProduct.Parent.Name) - 10 Then
Debug.Print aSubProduct.Name & " is a Product"
Dim subSubProduct As Product
For i = 1 To aSubProduct.Products.Count
Set subSubProduct = aSubProduct.Products.Item(i)
Call CopySubProduct(subSubProduct, targetPart)
Next
Else
Debug.Print "Component! Handle this somehow..."
End If
End Sub

'now the meat of the issue


Sub CopyPasteAsResultPartBody(sourcePartProduct As Product, targetPart As Part)

'make sure the part body is published

'get the selection object


Dim sel As Selection
Set sel = CATIA.ActiveDocument.Selection

'get the part


Dim thePart As Part
Set thePart = sourcePartProduct.ReferenceProduct.Parent.Part

'get the part body to copy. It must be published. Because you never go to the
Part object (via product.referenceproduct.parent.part)
' the publication allows you to keep the instance-ism of each part intact.
sel.Clear
Dim j, k As Integer
For j = 1 To sourcePartProduct.Publications.Count

sel.Add sourcePartProduct.Publications.Item(j)
On Error Resume Next
sel.Copy
sel.Clear

sel.Add targetPart
On Error Resume Next
sel.PasteSpecial ("CATPrtResult")
sel.Clear

Next
bodyCount = bodyCount + 1

End Sub