Why do you want automation in CAD?

With automation you can rationalize repetitive common tasks to increase speed and accuracy, or as a skilled employee transfer knowledge to juniors by making tools which they can use.

Automation possibilities in V5

V5 has several possibilities for automation/customization.

  • Macros
    • CATScript
    • VB Script
    • VBA
  • Knowledgeware
  • CAA

In this blog post, we will look into macros. Knowledgeware is based on geometry for building smartness into the model. CAA stand for Component Application Architecture and is a C++ interface for advanced users.

CATScript is a legacy language kept for compatibility and is converted to VB Script. We are not spending time on that.

VB Script is a simple sequential language with very simple user interface in form of message boxes, file selection boxes and input boxes. It can be handy when you have small automation tasks which contains a sequential process and does not require an advanced user interface. Only message boxes, input boxes and file selection is available.

VBA stands for Visual Basic for Application and is common in Office application and other major software packages. With VBA you are creating macros inside an application, but you can also access other application. For example, you can call Word or Excel from Catia to fulfill your goal. VBA creates an event driven program – the user decides in which order the program is executed.

Accessing macrosmacros

In Catia, you can access macros by tools->macro->macros…, or Alt+F8, or you can select Alt+F11 for open the editor directly.
By clicking Macro libraries… you can create a library for your macros. Two different libraries are available, directories and VBA library. Directories contains VBScript and VBA library is for VBA projects.

.

editor.

Basics functions and objects in VB

When you open a project in VBA, you are accessing the editor. In left view, you have an overview of your modules and forms. Forms are for user interfaces (UI) and can contain your complete code. Modules can both contain complete macros without UI, or subroutines or functions called from forms. Will be beneficial if you develop functions which is standardized and used in several forms/modules.

.

.

.

Objects

Objects are the bricks in programming. You will constantly work with objects. Even if you don’t know it. Objects are created from Classes, which defines the object. A form is an object, a filesystem or a data access system is an object. An object can contain several other objects. With objects, you can reuse your code to build complete applications. An object will have properties, variables, procedures and events. Objects created from the same class, will share the same characteristics and capabilities. A collection is several objects grouped together. To assign an object, you must use set, like this:

Set myObject = CATIA.ActiveDocument, compared to assigning a value to a variable which you will write as this: myVariable = 12

Formstoolbox

When you create a userform in the editor, you will have an empty form which you can modify to suit your needs. Since a form is an object, it has some properties, like name and caption. Name is what you are using when accessing the object in code and not visible to the user when macro is running. Caption is what shows up in top of the form, presenting information to the user. Some useful properties and methods are:

  • Caption – Header of the form, visible to the user
  • name – Name of the form, not visible to the user
  • Userform_Initialize() – Is read when the form is executed

In the form, you can add other objects like textboxes, buttons, pictures, labels, check boxes etc. from the toolbox.

Labelslabels

Labels are used for information to the user, like a header above a textbox to inform the user which kind of information is expected in the textbox. User cannot change a label, but you can change the label in code depending of user action if you will have a more interactive user interface.

  • Caption – Content of the label, text presented to the user.
  • Name – Name of the label, used in code

Textboxestextboxes

Textboxes is used for input from the user. Commonly used properties for textboxes are:

  • Text – content of the textbox, can contain a default value or left blank for user input.
  • Name – Name of the textbox, used in code to access object.
  • .

ComboBoxescomboboxes

ComboBoxes let the user select different predefined values. You can also allow the user to input his/her own values by typing another alternative into the ComboBox.

  • Name – Name of the box
  • AddItem – Add text to the drop down menu (method)
  • Text – Preselected value
  • Value – Selected value
  • MatchRequired – This is a Boolean variable, which can either be true or false. Set to false allows the user to select his/her own value, not one from the dropdown menu and set to true, you have to select one from the list.

Listboxeslistboxes

Listboxes work much like ComboBoxes, but present a list in a scrollable window.

  • Name – Name of the list
  • AddItem – Add text to the list (method)
  • Text – Selected value

Checkboxescheckboxes

Checkboxes is used for additional choices and multiple checkboxes can be selected simultaneously, or not at all.

  • Caption – Content of the label
  • Name – Name of the Checkbox, used in code
  • Value – Boolean value. True if checked, else false

OptionButtonoptionbutton

OptionButtons are giving the user multiple choices and only one choice can be selected.

  • Caption – Content of the label
  • Name – Name of the OptionButton, used in code
  • Value – Boolean value. True if checked, else false

If you will have multiple set of OptionButtons in a form, you must use frames to group they together

Statements

Statements in VB is a complete instruction. Two different types of statement exist.

  • Declaration statements
  • Executable statements

Declaration statements are like when you are naming a variable, constant or a procedure and can also specify a data type. Executable statements initiate actions, like calling a method or function and can loop through a block of code.

Examples of Declaration statements are:

  • Dim myText as TextBox
  • Dim myString as String
  • Dim i as integer

Examples of Executable Statements are:

  • For … Next
  • If Then Else
  • Select Case

We will show you examples where we use executable statements and explain how they work.

For … Next

For next loops are used to execute something a specific number of times. In the following example, we are executing a messagebox 10 times.

Dim Counter as integer

For Counter =1 to 10

Msgbox(“We are now in the “ & Counter & “ loop”)

Next

Dim Counter as integer, just tell the compiler that Counter can take integers (1,2,3…) and it is a declaration statement.

Next line says as long as Counter is less than or equal to 10, then do this. We give Counter an initial value to 1.

Msgbox outputs a messagebox and for example when Counter=4 the following text will pop up: We are now in the 4 loop. & is just for concatenate strings. “+” can also be used, but take care since variables declared as numbers will try to add them together. Above loop will give error with “+” since Counter is integer. You could concatenate two strings by using “+” like this:

Dim myString as String

myString = ”Hello”

Dim mySecondString as String

mySecondString = “World”

Msgbox(myString + mySecondString)

Will give the following output: HelloWorld.

Next tell the program to go to: For Counter=1 to 10 again. For Counter=1 to 10 is evaluated again and if it’s still true, it will continue with the next value of Counter. It will continue as long as Counter is less or equal to 10.

If Then Else

If Then Else is evaluating the condition. I it is true, it is executing the following statements, if it’s not, it’s going to the Else block.

Dim Counter as integer

Counter = 4

if Counter = 4 then

msgbox(“Hey, the value of Counter is: “ & Counter)

else

msgbox(“Counter is not equal to 4, it is: “ & Counter)

end if

If Counter is equal to 4, the first block of code is executed, if it is not, then the second is executed. An If Then Else statement is executed only once. End if is ending the if statement.

Select case

A select Case is selecting between several condition. Only one Case can be true.

Select case Textbox.Text

Case “Yes”:

Msgbox(“You wrote yes”)

Case “No”:

Msgbox(“You wrote no”)

Case else:

Msgbox(“I don’t understand what you wrote”)

End select

First sentence: Select case indicate a “select case” statement. Textbox.text is the value you try to match.

Case “Yes”: this action is chosen if the text is exactly “Yes”. Please note it is case sensitive.

Case else: is chosen if none of the above fits and End Select ends the Select Case statement.

Catia specific objects

Until now, we have discussed general VB functionality. It is common for all application which is using VBA. For an overview of objects in V5, you can refer to V5Automation.chm which in default installation is located in “C:\Program Files\Dassault Systemes\ Bxx\win_b64\code\bin\V5Automation.chm” where Bxx is replaced by your installation level. If you are using 32 bits windows, you have to replace win_b64 with intel_a. Below you will see an overview of available objects in V5.

catiav5_objects

As you see, from the application (Catia), the following objects are available:

  • Documents
  • Windows
  • Printers
  • Filesystem
  • Etc

Challenge

We will take a closer look at parts, and how we can create a pad. We will try to solve the following scenario:

  1. Create a new part
  2. Sketch a circle where user can decide radius
  3. Exit sketch and create a pad with user decided length
  4. Create the same pad with 50 mm horizontal distance four more times, totally five pads.

Proposal to solution

Open macro window and enable VBA as default macro library. Start recording a macro and create a pad. You will have something like this:

 

Sub CATMain()

Dim partDocument1 As PartDocument

Set partDocument1 = CATIA.Documents.Add(“Part”)

Dim part1 As Part

Set part1 = partDocument1.Part

Dim bodies1 As Bodies

Set bodies1 = part1.Bodies

Dim body1 As Body

Set body1 = bodies1.Item(“PartBody”)

Dim sketches1 As Sketches

Set sketches1 = body1.Sketches

Dim originElements1 As OriginElements

Set originElements1 = part1.OriginElements

Dim reference1 As Reference

Set reference1 = originElements1.PlaneXY

Dim sketch1 As Sketch

Set sketch1 = sketches1.Add(reference1)

 

Dim arrayOfVariantOfDouble1(8)

arrayOfVariantOfDouble1(0) = 0#

arrayOfVariantOfDouble1(1) = 0#

arrayOfVariantOfDouble1(2) = 0#

arrayOfVariantOfDouble1(3) = 1#

arrayOfVariantOfDouble1(4) = 0#

arrayOfVariantOfDouble1(5) = 0#

arrayOfVariantOfDouble1(6) = 0#

arrayOfVariantOfDouble1(7) = 1#

arrayOfVariantOfDouble1(8) = 0#

Set sketch1Variant = sketch1

sketch1Variant.SetAbsoluteAxisData arrayOfVariantOfDouble1

part1.InWorkObject = sketch1

Dim factory2D1 As Factory2D

Set factory2D1 = sketch1.OpenEdition()

Dim geometricElements1 As GeometricElements

Set geometricElements1 = sketch1.GeometricElements

Dim axis2D1 As Axis2D

Set axis2D1 = geometricElements1.Item(“AbsoluteAxis”)

Dim line2D1 As Line2D

Set line2D1 = axis2D1.GetItem(“HDirection”)

line2D1.ReportName = 1

Dim line2D2 As Line2D

Set line2D2 = axis2D1.GetItem(“VDirection”)

line2D2.ReportName = 2

Dim point2D1 As Point2D

Set point2D1 = factory2D1.CreatePoint(30, 40)

point2D1.ReportName = 3

Dim circle2D1 As Circle2D

Set circle2D1 = factory2D1.CreateClosedCircle(30, 40, 19.576243)

circle2D1.CenterPoint = point2D1

circle2D1.ReportName = 4

sketch1.CloseEdition

part1.InWorkObject = sketch1

part1.Update

Dim shapeFactory1 As ShapeFactory

Set shapeFactory1 = part1.ShapeFactory

Dim pad1 As Pad

Set pad1 = shapeFactory1.AddNewPad(sketch1, 20#)

Dim limit1 As Limit

Set limit1 = pad1.FirstLimit

Dim length1 As Length

Set length1 = limit1.Dimension

length1.Value = 34#

part1.Update

End Sub

We will now modify the code to try to solve the task:

  1. Create a new part. By looking into code, we see that

    Set partDocument1 = CATIA.Documents.Add(“Part”)

    solves our first task. We add a document (Part) to our collections of documents. We can also see that variables for known features are created, like bodies and sketches. Some references are also created, since we must use reference to a plane when creating a sketch and not the plane.

  2. Sketch a circle where user can decide radius. The following sentence creates the circle:

    Set circle2D1 = factory2D1.CreateClosedCircle(30, 40, 19.576243)

    By checking Automation reference or by just start editing, you will see that last input is radius. Because creating an inputbox inside this will be messy, we will create a variable and use the following code:

    Dim dblRadius As Double

    dblRadius = InputBox(“Enter radius of diameter”, “MyMacro”, 50#)

    Set circle2D1 = factory2D1.CreateClosedCircle(30, 40, dblRadius)

    We declare the variable as double, since radius can be a decimal number. First part of the inputbox is the text, next is the header of the box and last is a default value. We can choose if we are using all inputs. In editors help we find the following syntax for inputbox:

    Inputbox(Prompt,[Title],[Default],[XPos],[YPos],[Helpfile],[Context]) as string

    Input in [] is optional, so only required input is Prompt. “as String” shows us that returned variable is String. We are forcing this returned string into a double.

  3. Exit sketch and create a pad with user decided length. sketch1.CloseEdition will close the sketch. To create a pad with user decided length: As we can see from code, Catia first creates a pad with length 20 and later on changes this to 34. We can solve this in two different ways, either make an inputbox on the change length by this:

    length1.Value = inputbox(“Length of pad”, “MyMacro”, 50#)
    or by the following code:

    Dim dblLength As Double

    dblLength = InputBox(“Length of pad”, “MyMacro”, 50#)

    Set pad1 = shapeFactory1.AddNewPad(sketch1, dblLength)

Dim limit1 As Limit

Set limit1 = pad1.FirstLimit

Dim length1 As Length

Set length1 = limit1.Dimension

length1.Value = 34#
Notice then we can delete five lines. We could also have combined the inputbox into the pad, but its creates a less readable code, but we avoid creating a new variable. Then it could look like this:
Set pad1 = shapeFactory1.AddNewPad(sketch1, InputBox(“Length of pad”, “MyMacro”, 50#))

  1. We are now going to create four more pads with 50mm horizontal distance. Because we don’t want to input circle radius and length more than once, me move the definition of radius and length to the top of the code. Then we can create a for .. next loop without resetting those variables. By browsing through code, we see that we need a new sketch for each pad, so we add a for … next sentence before we create the sketch, like this:

Dim reference1 As Reference

Set reference1 = originElements1.PlaneXY

For i = 0 To 4

Dim sketch1 As Sketch

Set sketch1 = sketches1.Add(reference1)

Since we would like to duplicate everything else, we are putting in the required “next” sentence in the bottom, before End Sub. To increment circle center, we can see that circle center is linked to a point,
circle2D1.CenterPoint = point2D1
so we manipulate this point to increase horizontal location:
Set point2D1 = factory2D1.CreatePoint(30# + i * 50, 40#)
We can just add i to X coordinate since we are looping from i=0 to 4 instead of i=1 to 5
Finally, we would like to check if we are in the first loop, so we could present the input boxes only once:

Dim circle2D1 As Circle2D

If i = 0 Then

dblRadius = InputBox(“Enter radius of circle”, “MyMacro”, 50#)

End If

Set circle2D1 = factory2D1.CreateClosedCircle(30#, 40#, dblRadius)
and

Dim pad1 As Pad

If i = 0 Then

dblLength = InputBox(“Length of pad”, “MyMacro”, 50#)

End If

Set pad1 = shapeFactory1.AddNewPad(sketch1, dblLength)

 

That’s all. Tasks completed. Final code would look like something like this:

Sub CATMain()

Dim dblRadius As Double                                        ‘ Moved outside the for i=0 to 4 loop

Dim dblLength As Double

Dim partDocument1 As PartDocument

Set partDocument1 = CATIA.Documents.Add(“Part”)

Dim part1 As Part

Set part1 = partDocument1.Part

Dim bodies1 As Bodies

Set bodies1 = part1.Bodies

Dim body1 As Body

Set body1 = bodies1.Item(“PartBody”)

Dim sketches1 As Sketches

et sketches1 = body1.Sketches

Dim originElements1 As OriginElements

Set originElements1 = part1.OriginElements

Dim reference1 As Reference

Set reference1 = originElements1.PlaneXY

For i = 0 To 4                                                              ‘ loop to create several pads

Dim sketch1 As Sketch

Set sketch1 = sketches1.Add(reference1)

Dim arrayOfVariantOfDouble1(8)

arrayOfVariantOfDouble1(0) = 0#

arrayOfVariantOfDouble1(1) = 0#

arrayOfVariantOfDouble1(2) = 0#

arrayOfVariantOfDouble1(3) = 1#

arrayOfVariantOfDouble1(4) = 0#

arrayOfVariantOfDouble1(5) = 0#

arrayOfVariantOfDouble1(6) = 0#

arrayOfVariantOfDouble1(7) = 1#

arrayOfVariantOfDouble1(8) = 0#

Set sketch1Variant = sketch1

sketch1Variant.SetAbsoluteAxisData arrayOfVariantOfDouble1

part1.InWorkObject = sketch1

Dim factory2D1 As Factory2D

Set factory2D1 = sketch1.OpenEdition()

Dim geometricElements1 As GeometricElements

Set geometricElements1 = sketch1.GeometricElements

Dim axis2D1 As Axis2D

Set axis2D1 = geometricElements1.Item(“AbsoluteAxis”)

Dim line2D1 As Line2D

Set line2D1 = axis2D1.GetItem(“HDirection”)

line2D1.ReportName = 1

Dim line2D2 As Line2D

Set line2D2 = axis2D1.GetItem(“VDirection”)

line2D2.ReportName = 2

Dim point2D1 As Point2D

Set point2D1 = factory2D1.CreatePoint(30# + i * 50, 40#)

point2D1.ReportName = 3

Dim circle2D1 As Circle2D

If i = 0 Then

dblRadius = InputBox(“Enter radius of circle”, “MyMacro”, 50#)

End If

Set circle2D1 = factory2D1.CreateClosedCircle(30#, 40#, dblRadius)

circle2D1.CenterPoint = point2D1

circle2D1.ReportName = 4

sketch1.CloseEdition

part1.InWorkObject = sketch1

part1.Update

Dim shapeFactory1 As ShapeFactory

Set shapeFactory1 = part1.ShapeFactory

Dim pad1 As Pad

If i = 0 Then

dblLength = InputBox(“Length of pad”, “MyMacro”, 50#)

End If

Set pad1 = shapeFactory1.AddNewPad(sketch1, dblLength)

Dim limit1 As Limit                                                    ‘ lines deleted

Set limit1 = pad1.FirstLimit                                      ‘ lines deleted

Dim length1 As Length                                             ‘ lines deleted

Set length1 = limit1.Dimension                              ‘ lines deleted

length1.Value = 34#                                                 ‘ lines deleted

part1.Update

Next

End Sub

User exercisemymacro

If you have found this guide interesting, I encourage you to expand your macro into a nicer user interface. We are now adding form to our macro, which will be event driven instead of sequential.

  • Create a userform like shown and add names to textboxes and buttons. Copy your created macro into the userforms OK button. Copy only the text between Sub CATMain() and End Sub. Double click OK button to access code and paste your code between Private Sub Comma…. and End Sub
  • Remove inputboxes and use textboxes from form instead.
  • For Cancel button, double click and write: unload me
  • Use the debug menu to step through your code to observe what code is creating what.
  • Why can you delete those two If … Then sentence to check which loop we are in?
  • Why and how can you remove those two variables we stored our length and radius in?
  • Try entering text into text fields and observe the error generated from compiler. How could you check input before the compiler generates an error? Decide if you stop the macro, or force the user to enter correct values.
  • How can you add default values to your input form to help user understand input type?
  • Stop the macro after its done.