CATIA macro selection is a very important topic and concept to learn when automating CATIA processes. The following example will show you several useful CATIA programming basics, including:
1. Prompt the user to select multiple parts
2. Search selected parts for a specific element
3. Copy and paste the element into a new part
As usual, I have inserted my comments in the code to help you follow along.
‘Every CATScript begins with this statement
Sub CATMain()
‘start by declaring the selection
Dim oSel As Selection
Set oSel = CATIA.ActiveDocument.Selection
‘Create an array for CATParts
ReDim strArray(0)
strArray(0)=”Part”
‘Display a messagebox prompting the user to select CATIA parts
Dim sStatus As String
Msgbox “Please select parts to join.”
‘SelectElement3 is used to allow user to select multiple parts from the spec tree or the Interactive area
sStatus = oSel.SelectElement3(strArray, “Select parts”, False, CATMultiSelTriggWhenUserValidatesSelection, false)
‘CATMultiSelTriggWhenUserValidatesSelection option displays the following handy little toolbar:
‘Count the number of selected parts
iCount = oSel.Count
‘Create a For…Next loop to cycle through all selected parts
‘Isn’t vb scripting fun?
For i= 1 to iCount
Dim myObject2
Set myObject2 = oSel.Item(i).value
‘Search only the selected objects for the object named “PartBody”
oSel.Search “Name=PartBody,sel”
‘now we take all the PartBody objects found and copy them
ReDim copies(iCount)
For k=1 to iCount
Set copies(k)=oSel.Item(k).Value
oSel.Add copies(k)
oSel.Copy
‘close the loops
Next ‘k
Next ‘i
‘Now use CATIA scripting basics to create a new part
Dim part2
Set part2 = CATIA.Documents.Add(“CATPart”)
Dim partDocument2 As PartDocument
‘rename the new part
part2.Product.PartNumber = “My New Part”
‘optional step: create a new geometrical set and rename it
Dim GSet1 As HybridBody
Set GSet1 = part2.Part.HybridBodies.Item(1)
GSet1.Name = “My Geometry”
‘set the newly create part to the active document
Set partDocument2= CATIA.ActiveDocument
Dim ActSel As Selection
Set ActSel=partDocument2.Selection
ActSel.Add GSet1
‘paste special the PartBody objects from the orginial file and paste ‘as result without link
ActSel.PasteSpecial(“CATPrtResultWithOutLink” )
‘clear the selection
ActSel.Clear
End Sub
Concluding Thoughts
In this CATScript tutorial you learned several CATIA V5 scripting basics including: how to select multiple objects, how to create a new CATPart, how to create a new geometrical set, how to rename a part, how to rename a geometrical set, how to copy and paste, how to paste special result without link. Please use the contact form if you have any questions.
Is there a way to do the selection of the PartBodies without using the selection….oSel.Search “Name=PartBody,sel”
if each part contains a silly amount of geometries and/or bodies … this process will take a long time..
Thanks for your time!
Each part can contain only one PartBody (it will always be at the top of the spec tree, it cannot be reordered). If you want to always collect the PartBody you can use oPartBody = oPart.Bodies.Item(1)
ummmmm, is this line correct????
Set myObject2 = oSel.Item(i).value
and this one?
Dim myObject2 [as what????]
Yes , if you don’t use .value the object will be set as the selection, not the selected object. So if you select Line.1 and Set oLine = oSel.Item(i) then oLine.Name would be something like “catSelection1”. But if you Set oLine = oSel.Item(i).Value then oLine.Name would be “Line.1”. You don’t want to set it to the selection, you want to set it to what is in the selection.
As far as “Dim oSomeObject As SomeObjectType”, CATScript and catvbs are Late-Bound scripting languages, which means the compiler determines the item type on-the-fly, as the script runs…hence you do not need the item type.
Hi,
help please,
How to save as selecteds parts in tree in a other directory with selectelement3.
This is muy code, but is not work
Sub CATMain()
Dim oSel As Selection
Set oSel = CATIA.ActiveDocument.Selection
Dim filter(0)
filter(0) = “Product”
Dim myParts
myParts = oSel.SelectElement3(filter, “Select the part(s) “, False,CATMultiSelTriggWhenUserValidatesSelection, False)
For i = 1 to oSel.Count2
myObject2 = oSel.Item(i).value
myObject2.SaveAs (“C:\” & myObject2 & “.CATPart”)
Next
End Sub
Hi Wiyyat,
Where does the code stop working at? Are you getting any error messages?
Thanks,
Emmett
The selection filter is a product but they are saving a CATPart…unless they anticipate selecting Part instances? Also, It looks like in the 3rd to last line…myObject2 is not a string so they need the .Name property
myObject2.SaveAs (“C:\” & myObject2.Name & “.CATPart”)
Hi:
First of all congrats for your website, is great!
In regards to this particular article Im having this error:
Compile error:
Function or interface marked as restricted, or the function uses an automation type not supported in Visual Basic.
Im pretty sure this code works (since I used it before), then what can be wrong now?
Hi John, thanks for the kind words. What specific line of code are you getting that error?
Wiyyat & John
To avoid that error, declare OSel as follow:
Dim oSel
Set oSel = CATIA.ActiveDocument.Selection
Hope it helps.
Hi John.
This is probably helpful as well:
http://v5vb.wordpress.com/2010/07/29/restricted-interfaces/
Hi
I find your code very helpful in my study, but one thing I need more:
How can I rename copied PartBodies before I paste it in new part?
Let’s assume that PartBody1 comes out Part1, PartBody2 from Part2 and so on – how can I set PartBody name to it’s “parent” name?
If you have already set the oPartBody variable, you should be able to use this:
sName = oPartBody.Parent.Name
That should give you the name of the part that the Part Body is in.
To change the name use:
oPartBody.Name = sName
I believe sName = oPartBody.Parent.Name will return the Bodies collection.
You would need to use sName = oPartBody.Parent.Parent.Name
Hi,
I have to create a clipped view on a drawing because of a projected product is big. The function DefinePolygonalExactClippingView doesn’t clip if a model is CGR. Therefor I use the function DefinePolygonalClippingView, but it leaves a clipping frame. How can I select the lines of a frame to delete them.
Thanks
This site was my salvation, great job! I want to select products also..any idea?
Thanks for the kind words, Sebastian! What do you mean by select products? CATProducts? Before macro is started or while running?
I already did it and works great. So, it´s not a problem any more. I have another problem now, may be you can help me. I usually design with excel tables that gives certain characteristics to the created components. I’ve made a macro to create personalized parts and products (linked with the design table, with specific geometrical sets, etc). I want to know how to call the design table window (in CATIA) to select the PartNumber from the design table while the macro is running. Do you know some piece of code to do something like this?
There is a chapter in my book dedicated to import and exporting from CATIA to Excel and Excel to CATIA: https://www.scripting4v5.com/books/vb-scripting-for-catia-v5/
Hi
Can I select a point and draw a line with this point and other point,
How can make a macro like this?
Yes, that is possible to do. You could try using the macro recorder to help if you’re stuck.
I didn’t test this but this should let you pick 2 points then draw a line be tween them and add it to the geoset the first point is in.
Sub CATMain()
Dim oSelection as Selection
Set oSelection = CATIA.ActiveDocument.Selection
Dim oSelectionLB ‘Late bound variable needed for interactive selection
Set oSelectionLB = oSelection
Dim oLineGeoset As HybridBody
Dim oPoint1 ‘Don’t give an item type because there are many types of points you can select
Dim oPoint2 ‘Don’t give an item type because there are many types of points you can select
Dim oLinePtPt As HybridShapeLinePtPt
oSelection.Clear
Dim oSelectionFilter(0) ‘only one filter needed to pick anything
oSelectionFilter(0) = “ZeroDim” ‘Forces you to pick only points and verticies
sSelectionMessage = “Select 2 points to draw a line between”
msgbox sSelectionMessage, vbInformation, “Name of your macro”
‘Check if they only selected 2 points
iCounter = 1
Do While oSelection.count 2
oSelectionLB.SelectElement3 oSelectionFilter, sSelectionMessage, True, CATMultiSelTriggWhenUserValidatesSelection, False
iCounter = iCounter + 1
If iCounter = 5
Msgbox “You can only pick 2 points, exiting macro”
end Loop
End if
Loop
‘Check that only points are selected
If Instr(Typename(oSelection.Item(1).Value), “HybridShapePoint”) and Instr(Typename(oSelection.Item(2).Value), “HybridShapePoint”)
Set oPoint1 = oSelection.item(1).Value ‘Set point 1
Set oPoint2 = oSelection.item(2).Value ‘Set point 2
Set oLineGeoset = oPoint1.Parent.Parent ‘Get the geoset the first point is in
oPart.InWorkObject oLineGeoset ‘Make the geoset the in work object
Set oLinePtPt = oFactory.AddNewLinePtPt(oPoint1, oPoint2) ‘Create the line in memory
oLineGeoset.AppendHybridShape oLinePtPt ‘add the line to the spec tree
oLinePtPt.Compute ‘Local update the new line
Else
Msgbox “Vertices are not allowed, exiting macro”
end sub
End if
End sub
Hi,
Thank you for this useful website, I have a question/problem : Is it possible to realise a MultiSelection for several Circles by using SelectElement3 ? My code doesn’t seem to recognise them as Circle.
If not is there another solution to reach my aim ?
Sorry for my English (i’m French)
I believe what you are asking is “can you force someone to only pick a circle” the answer is YES.
You need to set up a “selection filter” with each item type in the filter…or allow them to select anything and sort through what they selected later.
The code below uses a selection filter
Dim oSelection as Selection
Set oSelection = CATIA.ActiveDocument.Selection
Dim oSelectionLB ‘Late bound variable needed for interactive selection
Set oSelectionLB = oSelection
oSelection.Clear
Dim oSelectionFilter(7) ‘Array for 8 types of circles (0-7)
oSelectionFilter(0) = “HybridShapeCircle2PointsRad”
oSelectionFilter(1) = “HybridShapeCircle3Points”
oSelectionFilter(2) = “HybridShapeCircleBitangentPoint”
oSelectionFilter(3) = “HybridShapeCircleBitangentRadius”
oSelectionFilter(4) = “HybridShapeCircleCtrPt”
oSelectionFilter(5) = “HybridShapeCircleCtrRad”
oSelectionFilter(6) = “HybridShapeCircleCenterTangent”
oSelectionFilter(7) = “HybridShapeCircleTritangent”
sSelectionMessage = “Select circle(s)”
msgbox sSelectionMessage, vbInformation, “Name of your macro”
oSelectionLB.SelectElement3 oSelectionFilter, sSelectionMessage, True, CATMultiSelTriggWhenUserValidatesSelection, False
This code gives you an idea on how to process objects after they are selected
Dim oSelection as Selection
Set oSelection = CATIA.ActiveDocument.Selection
Dim oSelectionLB ‘Late bound variable needed for interactive selection
Set oSelectionLB = oSelection
Dim cElements as New Collection
oSelection.Clear
Dim oSelectionFilter(0) ‘only one filter needed to pick anything
oSelectionFilter(0) = “AnyObject”
sSelectionMessage = “Select circle(s)”
msgbox sSelectionMessage, vbInformation, “Name of your macro”
oSelectionLB.SelectElement3 oSelectionFilter, sSelectionMessage, True, CATMultiSelTriggWhenUserValidatesSelection, False
For i = 1 to oSelection.Count
If Instr(Typename(oSelection.Item(i).Value), “HybridShapeCircle”) 0 Then ‘Check if it is a circle
‘Do something
Else
‘Do nothing
End if
Next
please provide with power point presentation it s good looking easy to understand
Ravi, I share all my powerpoints on SlideShare here: http://www.slideshare.net/emmettross/getting-started-with-catia-v5-macros
Hello,
I saw your post about how select this on CATIA tree. I am working on a script(vb.net) to read all products and parts in a CATIA tree and then populate a treeview and show me the mass and surface area for all treeview nodes. All this things I already done, the problem is that now I would like to select a treeview node on my form and select the correspondent node on CATIA node. I already used the search method but I have a lot of instances on my assembles and when I use the search method all instances become highlighted instead only the correspondent selected node. On my treeview the the name(or key in vba) is the full path on the tree, for example the key word of part1 is product1 (product1.1)/product2 (product 2.1)/product 3 (product 3.1)/part1 (part1.1). Do you know if on CATIA I can search a specific node using the full path? Thanks for you help and for the website!
Hi, i was wondering if it’s possible to ask CATIA to copy a datum publication from a part [containing datums only] and paste special it with link in a part contained in a sub-product. I mean, my tree looks like this
PRODUCT
|- DatumCurves.catpart
|- DatumPlanes.catpart
|- PROJECT.catprod
|-STRUCTURE.catproduct
|-Part-001
|-Part-002
|-Part-003
|-PANELS.catproduct
Where in DatumCurves.catpart i have “Curve-001”, “Curve-002”, “Curve-003” as publications, and in DatumPlanes.catpart i have “Plane-001”, “Plane-002”, “Plane-003”.
I wondered if it was possible to ask CATIA to copy Curve-001 and Plane-001 from their catparts and “paste special with link” them to Part-001, then do it with 002, 003 and so on..
I’m desperately trying to paste them but i still can’t do it.. (I even tried to recorder a simple copy-pastespecial macro with the macro recorder in CATIA to have a look to the output code, but in the resulting macro there’s no pastespecial part.. just like i simply didn’t do it.
I also tried with different macros but looks like my CATIA has some problems with “ActSel” and I can’t figure out why.. Can somebody help me?
Hi Sir,
I want to get a curve as user input. when i tried the below array statement, it doesnt works
Usersel(0)=”Curve”
please help
Can u help me to fix please ??
sub copyOperationsAlteredValueZ()
Dim i, ii As Integer
Dim procces1 As ProcessDocument
Dim mfgdoc1 As PPRDocument
Dim manufacturingProgram1 As ManufacturingProgram
Dim manufacturingOperation1 As ManufacturingOperation
Dim selection1 As Selection
Dim ActivityRef As AnyObject
Dim childs As Activities
‘Dim Fase As Activity
Dim CurrentSetup As ManufacturingActivity
Dim ProgramList As MfgActivities
Dim CurrentProgram As ManufacturingActivity
Dim ActivityList As MfgActivities
Dim currentActivity As ManufacturingActivity
Dim CurrentSetupMP As ManufacturingSetup
Dim CurrentProgramMP As ManufacturingProgram
Dim ProgramListMP As MfgActivities
Dim ActivityListMP As Activities
Set procces1 = CATIA.ActiveDocument
Set mfgdoc1 = procces1.PPRDocument
Set ActivityRef = procces1.GetItem(mfgdoc1.Processes.Item(1).Name)
Set childs = ActivityRef.ChildrenActivities
Set Fase = childs.Item(2)
Set CurrentSetup = Fase
Set ProgramListMP = CurrentSetup.Programs
Set CurrentProgramMP = ProgramListMP.GetElement(1)
Set ActivityListMP = CurrentProgramMP.ChildrenActivities
Dim USel As Selection
Dim uselLB, nSel
Dim InputObject(0), myarray(0)
Dim oStatus, iStatus
Dim length1 As Length
Dim parameters1 As Parameters
Set manufacturingProgram1 = ProgramListMP.GetElement(1)
myarray(0) = “AnyObject”
InputObject(0) = “AnyObject”
Set nSel = CATIA.ActiveDocument.Selection
Set USel = CATIA.ActiveDocument.Selection
Set uselLB = USel
nSel.Clear
MsgBox “Selecciona las operaciones a copiar y luego pulsa la bolita verde” & vbCrLf & vbCrLf & “Maximo 100 elementos. ”
USel.Clear
oStatus = uselLB.SelectElement3(InputObject, “Seleciona Operaciones a copiar”, False, CATMultiSelTriggWhenUserValidatesSelection, False)
If (oStatus = “Cancel”) Then
Exit Sub
Else
iCount = uselLB.Count
For i = 1 To nCopias
MsgBox (uselLB.Item(i).Value.Name)
Set manufacturingOperation1 = manufacturingProgram1.GetItem(uselLB.Item(i).Value.Name)
USel.Add manufacturingOperation1
USel.Copy
CATIA.ActiveDocument.Selection.Clear
MsgBox “Selecciona donde quieres pegar” & vbCrLf & vbCrLf
iStatus = nSel.SelectElement2(myarray, “Seleciona Operacionpara pegar”, False)
If (iStatus = “Cancel”) Then
Exit Sub
Else
USel.Paste
End If
Set ActivityRef = childs.Parent
Set parameters1 = ActivityRef.Parameters
On Error Resume Next
Set length1 = parameters1.Item(childs.Parent.Name & “\” & USel.Item(i).Value.Name & “\Geometry.1\Offset on Bottom”)
If Err.Number = 0 Then
Zbase = CInt(length1.Value)
length1.Value = Zbase + valorZ.Value
‘USel.Clear
End If
Next
‘nombres de las operaciones a copiar almacenados en USel.item(i).value.name
End If
end sub
Hi
I am trying to learn CATScript, and can you please help me to create a macro as below requirement.
Here I want to mainly learn how to allow user to select input from existing tree and use as input for further processing.
Please help on this topic
Macro requirement -> To create a sketch in which rectangle is predefined
Input- Macro to ask user to select Point and reference plane
Output required
1. With the input point & reference plane, create a new plane passing through input point and parallel to input reference plane
2. Using position sketch, create a sketch with rectangle. Length and breath to be asked as input
3. Please the sketch in the GS.
I wanted to create a macro that let’s the user select parts or products under a product tree by mouse and let the user enter a new part number and instance name in a loop. This macro will be very useful when we have a lot of parts in an assembly
i want to count oblong text in cat drawing is there any way we can select & count no of text with the specified frame by macro