VB Scripting For CATIA V5 Ebook
VB Scripting For CATIA V5 Ebook
For CATIA V5
Nick Weisenberger
Contents
Copyright Information.................................................................................................... 5
Disclaimer....................................................................................................................... 5
Chapter 1: Getting Started..................................................................................................... 6
What is a Macro and why do we use them?.................................................................. 6
What is VB script? .......................................................................................................... 6
How to Create Macros ................................................................................................... 7
How to Add an Existing Macro Library........................................................................... 7
How to Open and Run Macros....................................................................................... 8
Create an Icon for each Macro....................................................................................... 8
How to Record a Macro ................................................................................................. 8
Fundamentals for Creating Custom Macros .................................................................. 9
VB Script Syntax ...........................................................................................................10
Programming Concepts: The CATIA Object .................................................................11
Introductory Example ..................................................................................................13
Chapter 2: Fundamentals.....................................................................................................14
Structure ......................................................................................................................14
The Selection Object ....................................................................................................14
Documents versus Windows........................................................................................16
Subroutines and Functions ..........................................................................................16
Save and Save As..........................................................................................................17
Get Workbench ............................................................................................................18
Work with Collections: Count and Item.......................................................................18
Simple Viewer Commands ...........................................................................................19
Chapter 3: Building Blocks ...................................................................................................21
Error Handling ..............................................................................................................21
Create a Yes/No Message Box .....................................................................................24
Working with Parameters ............................................................................................24
2
Nick Weisenberger
For Loop .......................................................................................................................24
Changing the Background ............................................................................................26
Example: Display the Density of a Part ........................................................................27
Chapter 4: Additional Tools..................................................................................................28
The Object Browser......................................................................................................28
Windows Explorer ........................................................................................................28
User Forms ...................................................................................................................28
Design Mode ................................................................................................................29
Parts and Products .......................................................................................................30
Export to Image format................................................................................................31
2D Drawing Viewers.....................................................................................................32
Activation State............................................................................................................32
Measurement Macros..................................................................................................33
Dealing with Different Versions of CATIA ....................................................................34
Chapter 5: Export to Excel....................................................................................................35
How to export to Excel.................................................................................................35
Launching Excel from CATIA.........................................................................................36
Screen Updating and Excel Visibility ............................................................................37
Entering Cell Values......................................................................................................37
Excel Formulas .............................................................................................................38
Defining Excel Constants..............................................................................................39
Inserting Rows and Columns........................................................................................41
Sorting the Excel Spreadsheet .....................................................................................41
Deleting Rows and Columns.........................................................................................42
Formatting Excel ..........................................................................................................42
Chapter 6: Export to PowerPoint .........................................................................................45
Chapter 7: Additional Information, Help, and Examples .....................................................48
Useful Windows Functions...........................................................................................48
Complete Macro Examples ..........................................................................................48
Return the Parent Name ..............................................................................................48
3
Step-by-step Tutorials...60
Workshop 1: Fundamentals
Workshop 2: Creating Your Own VBA Modules and Classes
Workshop 3: Creating a Basic VBA Program from Scratch
Workshop 4: Objects in CATIA VBA
Workshop 5: Navigating a Part Document with Error Handling
Workshop 6: Creating Sketch Geometry
Workshop 7: Using Forms in CATIA VBA
Nick Weisenberger
Copyright Information
Copyright 2012 by Nick Weisenberger
All rights reserved. No part of this book may be reproduced or transmitted in any
form or by any means, electronic or mechanical, including photocopying, recording,
or by any information storage and retrieval system, without permission in writing
by the author. The only exception is by a reviewer, who may quote short excerpts in
a review.
Cover and book design by Nick Weisenberger.
No affiliation with, or endorsed by anyone associated, or in any way connected with
Dassault Systemes, Microsoft Corporation, UNIX, or any of their fantastic products.
Disclaimer
Through a series of example codes and tutorials Ill explain how to use and
create CATScript macros for CATIA V5. No programming experience is required!
This information is not featured in the user help documentation. The purpose of this
text is to show beginners how they can approach different problems and for users to
rewrite code shown in the examples to suite their specific needs.
There are many CAD engineers, designers, and technicians who want to
write macros but simply dont have time to sit down and learn everything they need
to know. This text will cover those core items to help teach beginners important
concepts needed to create custom CATScript macros.
What is a Macro and why do we use them?
What is a macro? If you perform a task repeatedly, you can take advantage
of a macro to automate the task. A macro is a series of functions, written in a
scripting language, that you group in a single command to perform the requested
task automatically. Macros use programming but you dont need to be a
programmer or have programming knowledge to use them (though it definitely
helps).
Macros are used to save time and reduce the possibility of human error by
automating repetitive processes, standardization, improving efficiency, expanding
CATIAs capabilities, and by streamlining tasks.
What is VB script?
Nick Weisenberger
(Excel, Word, CATIA, etc.), VBScript, JavaScript, Visual Basic 6.0, Microsoft
Developers Studio.NET, and others. For CATIA V5 running on UNIX, emulators
allow for VBScripts to be run with no interface building tools. Some CATScripts
from this text may work under UNIX OS but not all due to differences between the
two systems. However, this will not be covered in this text.
How to Create Macros
One method for creating macros is by recording your mouse actions. A few
things to keep in mind when recording a macro:
1.
2.
3.
4.
5.
6.
8
Nick Weisenberger
Always UNDO what you just recorded and run the macro. If the macro
works from within CATIA and repeats what you just did, then the macro obviously
works fine. If it does NOT work from within CATIA, you need to fix it. If it does
NOT work from within CATIA it will NOT work once you cut and paste it into a
VB application.
Look through the recorded macro. Many times extra lines of code are added
which are not necessary. This is based on the order of steps that you do as you
record the macro. These unnecessary lines can be removed.
For example, if I record a macro to zoom in and then zoom out I might get the
following code:
Dim viewpoint3D As Viewpoint3D
Set viewpoint3D = viewer3D.Viewpoint3D
Viewer3D.ZoomIn
Set viewpoint3D = viewer3D.Viewpoint3D
Viewer3D.ZoomOut
Set viewpoint3D = viewer3D.Viewpoint3D
Notice how the Set Viewpoint command appears multiple times? This is
unnecessary in this situation. The viewpoint only needs to be set once after the Dim
statement. Did I lose you yet? Dont worry; setting and declaring will be explained
in more detail in the upcoming pages.
Often times you might record a macro with a CATPart active and open it in
its own window. All goes smoothly and the macro replays fine. Then, the next day
you replay the macro again but this time you may have some other document type
open or maybe a part is open but it is in a product assembly. Usually, the macro
will fail because when the code was recorded a part was the active document but
now it is not. This is one advantage to writing custom code and knowing the
fundamentals of VB scripting.
Fundamentals for Creating Custom Macros
(single, double, integer, string, etc.) or an object type (more complex). Strings are
especially useful because they hold text. Message boxes are frequently used to
display strings to users while the program is running. Looping is often used to
perform iterative actions
Object An entity (in CATIA or VB). Points, Pads, Parameters, etc. are
all examples of CATIA objects.
Property A characteristic of an object. For example, the name of a
PartDocument is a property of that object.
Method An action that an object can perform. For example
PartDocument.SaveAs() is an action that the object can perform.
Collection A group or list of similar objects which are put together for
a specific reason.
Object oriented programming came about due to the need to represent more
complex ideas within a program. For example, you could say that a person is
described by his height, weight, and hair color, and that every person has certain
actions that they can perform, such as walking, eating, and sleeping. These
properties and methods make up the class called Person. Objects of this
class can then be used in a program to represent individual people.
VB Script Syntax
Syntax is defined as the ordering of and relationship between the words and
other structural elements in phrases and sentences. Each scripting language is
composed of its own syntax. Learning the syntax of each programming language is
crucial to creating successful macros. Here are some of the key features of VB
Scripts syntax:
Indentation: Indent or out dent script to reflect the logical structure and nesting
of the statements.
Parentheses: To achieve the desired result and to avoid errors, it is important to
use parentheses () correctly in any statement.
Text Strings: When a value is entered as a text string, you must add quotation
marks before and after the string.
Case Sensitivity: By default, VBScript is not case sensitive and does not
differentiate between upper-case and lower-case spelling of words, for example,
in variables, object and method names, or constants.
10
Nick Weisenberger
Spaces: Add extra blank spaces to your script to improve clarity. These spaces
are ignored by VBScript.
Comments: Add comments to your statements using an apostrophe ('), either at
the beginning of a separate line, or at the end of a statement. It is recommended
that you add comments wherever possible, to make your scripts easier to
understand and maintain, especially if another user has to make changes to it
later on down the road.
Naming: Avoid naming conflicts. Two variables cannot have the same name.
To return a single quotation mark which does not indicate a comment,
needed in a formula for example, youll have to use the Chr function. Chr() is a
built-in VBA function that returns the character that corresponds to the numeric
value of its argument, using the ASCII coding scheme. If you provide Chr with an
integer value (such as 39) it will report back the character that corresponds to
that value. The ASCII value of 39 is the single quote mark. Chr(34) is for the
double quote mark.
The CATIA object is usually the first object that is referenced in any
CATIA macro. This object represents the CATIA application itself, from which the
macro is run. The CATIA object has many properties. For instance, it has a
property called FullName which is a string. Another property is called
ActiveDocument. This property is an object itself, and even more specifically, it
is a Document object. More about that later.
The CATIA object is dimmed or declared as it exists by default. The
purpose of declaring and setting variables is to hold the properties of an object.
Variables that hold objects require the Set keyword. The properties of objects can
be accessed using the notation: Object.Property. Here is an object property example
using the FullName property:
11
Sub CATMain()
Dim strFullName as String
strFullName = CATIA.FullName
Dim doc1 as Document
Set doc1=CATIA.ActiveDocument
End Sub
-or-
12
Nick Weisenberger
Sub CATMain()
Display a message box with the full name of the
document
Msgbox CATIA.ActiveDocument.FullName
Display a message box with the number of
selections in the document
Msgbox CATIA.ActiveDocument.Selection.Count
End Sub
Introductory Example
The following code will display a message box with the text "Hello.
strHello is a variable declared as a string (or text) object. strHello is then defined.
Every Sub must end with "End Sub".
Sub CATMain()
Dim strHello As String
strHello = "Hello"
MsgBox strHello
End Sub
Congratulations! Youve just created your first CATIA V5 macro! Youre
on your way to automating complex and time consuming tasks. Well continue with
more programming fundamentals in chapter two.
Workshhop Tutorial 1: It is recommended that you now flip to the back of
this book and walk through workshop number 1, a step-by-step tutorial which will
walk you through some of the concepts just explained in chapter one.
13
Chapter 2: Fundamentals
Structure
If nothing is selected then the selection is empty. If one or more objects are
selected then the selection contains those one or more objects. To add an element to
the selection:
14
Nick Weisenberger
A good practice is to always clear the selection before and after you use it.
To check what has been selected you could use the following code, which will loop
through all selected objects and display the name in a message box for each one:
For I = 1 to oSel.Count
Msgbox oSel.Item(i).Value.Name
Next i
You can search through selections by several different methods, including
searching by name, type, color, etc. Once the search command has been issued, you
then need to loop through the selection object to get the items that have been found.
The selection object can also be used for a variety of other tasks:
15
There are two main collections under the CATIA application object:
Documents - There are many types of documents that are used in V5:
CATPart, CATProduct, CATProcess, CATDrawing, CATAnalysis, etc.
These are all housed in the Documents collection and they contain all
geometry, process, and product information.
Windows This collection contains information about how the data from
the documents collection will be seen in the CATIA window. It controls
items such as:
Subroutines and functions are good for encapsulating code that needs to be
called repeatedly. Functions return a value, subroutines do not. Arguments may
be passed in as ByRef or ByVal (ByVal is the default). The following code is
16
Nick Weisenberger
another example of how to display a Hello message box using multiple sub
statements.
Sub CATMain()
Dim strMessage as String
CallMe strMessage
MsgBox strMessage
End Sub
The Document object includes the Save and Save As methods. The Save
method takes no arguments and returns nothing.
CATIA.ActiveDocument.Save
17
Get Workbench
Collections are special kinds of objects that hold a list of objects of a certain
class. The property Count and the method Item() are frequently used on
collections in CATIA. For example:
Sub CATMain()
'Count the number of open documents
Dim docs1 as Documents
Set docs1 = CATIA.Documents
MsgBox The number of open documents is & docs1.Count
'Accessing the first Document object in the collection
Dim doc1 as Document
Set doc1 = docs1.Item(1)
MsgBox The FullName of the first document is & doc1.FullName
End Sub
18
Nick Weisenberger
There are a few steps and methods to change the viewpoint of a CATIA
document. First, we need to access the 3D viewer from the current CATIA window:
objViewer3D.Viewpoint3D = Camera3D.Viewpoint3D
Once you access the ActiveViewer of the current window you can also control
many other display properties:
Dim objViewer As Viewer3D
Set objViewer = CATIA.ActiveWindow.ActiveViewer
Translating the view
objViewer.Translate(translationVector)
Rotating the view:
objViewer.Rotate(axisOfRotation, rotationAngle)
19
tree
and
the
20
Nick Weisenberger
Now its time to build upon the fundamentals weve learned to make our
programs more complex and robust.
Error Handling
When writing CATScripts, its a good idea to avoid all errors at all cost. Don't
let your users think, they are "only users". Write them out of the equation. It is
important to debug your programs to avoid errors & program crashes. Trust me, its
not much fun if another user runs my code and tells me Hey, your code doesnt
work. Thus, my goal is to never have a code break because of a run-time error. If
you can't avoid an error then use some form of error handling.
Even if the program you write has the correct syntax, it may still encounter a
run time error as it is running. This is why error handling is necessary. For
example, the following code would produce an error if the ActiveDocument in
CATIA was a product document and not a part document.
Sub CATMain()
Dim pdoc1 as PartDocument
Set pdoc1 = CATIA.ActiveDocument
MsgBox pdoc1.FullName
End Sub
The program would stop at the third line of the above code. By using the
statement On Error Resume Next, the program will ignore errors that are
generated and proceed through the subsequent lines. However, in this example
where an error is ignored and the program proceeds, another error is generated on
the next line. This is because the variable pdoc1 is Nothing. It wasnt
successfully Set in the previous line.
21
The behavior of the program can be made even more intelligent by using the
Err object, which is an object that exists in every VBA program. The Err object
holds information regarding errors that have been generated. The number
property of the Err object indicates whether an error has been generated or not.
Sub CATMain()
On Error Resume Next
Dim pdoc1 as PartDocument
Set pdoc1 = CATIA.ActiveDocument
If Err.Number = 0 Then
MsgBox pdoc1.FullName
Else
MsgBox Active document is not a part document!
End If
End Sub
Calling the Clear method on the Err object sets the Number property of
the Err object to zero (clean slate, as they say).
22
Nick Weisenberger
Sub CATMain()
On Error Resume Next
Insert various programming statements here along with
logic and conditionals that deal with errors that are
generated. Assume Err.number is not zero after these
statements run
Err.Clear
Proceed with the error number cleared
(Err.number is now zero)
End Sub
The command On Error Goto 0 sets the execution of the program so that
errors arent ignored for the subsequent lines.
Sub CATMain()
On Error Resume Next
=====================================
If a runtime error occurs here, the program
proceeds
=====================================
On Error Goto 0
=====================================
Now when a runtime error occurs, the program
will stop
End Sub
23
Use the following code to create a pop-up message box with the option to click
Yes or No:
If MsgBox ("To export results to PowerPoint click
Yes. Otherwise click No.", vbYesNo) = vbYes Then
Else
End If
To create a parameter:
Dim objParm As Parameter
Set objParm=objParameters.CreateDimension(Name,Length,10.0)
For Loop
Just like any other part of CATIA, there are multiple methods to accomplish
the same task. One example of this in VB scripting is the For Loop. A for-each loop
can be used to iterate through most collections in CATIA.
24
Nick Weisenberger
Method 1:
Sub CATMain()
Dim documents1 as Documents
Set documents1 = CATIA.Documents
Dim doc1 as Document
For Each doc1 in documents1
MsgBox doc1.Name
Next
End Sub
Method 2:
Sub CATMain()
Dim documents1 as Documents
Set documents1 = CATIA.Documents
Dim doc1 as Document
Dim i As Integer
For i = 1 To CATIA.Documents.Count
Set doc1 = CATIA.Documents.Item(i)
MsgBox doc1.Name
Next
End Sub
25
Background Color can be set by passing values to or from an array. One use
of changing the background color may be to take a screen capture with a white
background for easy printing (and using less ink)! Use this code to change the
background color to white:
26
Nick Weisenberger
The & symbol works much the same as the concatenate formula in
Microsoft Excel by combining multiple elements. For example, if you want a pop
up message box to read The density is 55 where 55 is a variable which will
update with the part try this code:
Sub CATMain()
Dim productDocument1 As Document
Set productDocument1 = CATIA.ActiveDocument
Dim partRoot As Document
Set partRoot = productDocument1.Part
MsgBox "The density is " & partRoot.Density
End Sub
27
Documentation can be found from within the CATIA VBA editor by way of
the menu. Go to View>Object Browser or simply hit F2. As an example, lets say
you want to create a pad object, Type in the unknown object type into the search
window at the top of the object browser. Look in the third column of results
(member) for something that makes sense. In this case, AddNewPad sounds
good. Look in the second column (class). This will tell you what object is needed
to use the function in the third column. Now look at the bottom of the window. This
will tell you how to use the function and what objects are needed.
Function AddNewPad(iSketch As Sketch, iHeaight As Double) As Pad
Member of PARTITF.ShapeFactory
Where Argument 1 is a sketch and I means input. The Pad object must be declared.
Windows Explorer
A great way to enhance the experience for your end users and one of the
most important features of Visual Basic programs is by creating userforms.
28
Nick Weisenberger
Userforms give you the ability to quickly and easily create graphical user interfaces
(GUI) for your macro programs. The foundation of any GUI in a Visual Basic
program is a Form, onto which various buttons, text fields, list fields, etc. may be
dragged onto. Users can input text, choose from a list of options, our click a
command button which runs a subroutine that uses the user input options.
Forms, buttons, text fields, etc. can be thought of as special kinds of objects
that instead of running methods have events. In the same way that a method is a
function or a subroutine that runs whenever called from within a program, an
event is a subroutine that runs whenever a user interaction triggers that event. For
example, each button on a form has a Click event that runs whenever a user clicks
on the button.
To create a new UserForm press ALT-F11 to open the VBA editor. In the
Project explorer window (top left side), right-click on the project then select Insert
UserForm. Double check to make sure it is named UserForm1 in the properties
window. You can drag command button icons to your new UserForm. For more on
UserForms see Workshop 7.
Design Mode
If you're working with large assemblies, you may want to automatically set
each item in the tree to design mode (individually opened parts are typically
automatically opened in design mode already):
29
Keep in mind, that when the new part is added, the objProduct object will
reference the Product level of the Part. The Product class in CATIA VBA has a
peculiar property called ReferenceProduct. This property returns a Product.
30
Nick Weisenberger
Also, there are two internal names for products inside CATIA V5: the
Product Name and the Instance Name. These can both be accessed via the CATIA
Object Model using two different properties:
Example: SubAssy1(SubAssy1.1) where the product name is SubAssy1 and the
instance name is AubAssy1.1:
Product Name: objProduct.Name
Instance Name: objProduct.PartNumber
The viewer gives you the capability of exporting the 3D window into a
picture format:
objViewer3D.CaptureToFile(catCaptureFormatJPEG,
C:\myPicture.jpg)
The size of the picture is, by default, the size of the active window. You can
change the size of the picture with this code:
Set window=CATIA.ActiveWindow
H=win.Height
W=win.Width
sLF=Chr(10)
31
2D Drawing Viewers
32
Nick Weisenberger
33
34
Nick Weisenberger
Spreadsheets are used in the world of engineering to create part lists and
bills of material. These are typically created in Microsoft Excel. A macro can be
created to export data from CATIA into an Excel spreadsheet, quickly automating
this process.
Before launching Excel we need to declare all of our objects and variables
including the Microsoft Excel application itself, each workbook, each worksheet
within each workbook, etc.
Dim Excel As Object
Dim workbooks As workbooks
Dim workbook As workbook
Dim Sheets As Object
Dim Sheet As Object
Dim worksheet As Excel.worksheet
Dim myworkbook As Excel.workbook
Dim myworksheet As Excel.worksheet
Set workbooks = Excel.Application.workbooks
Set myworkbook = Excel.workbooks.Add
Set myworksheet = Excel.ActiveWorkbook.Add
Set myworksheet = Excel.Sheets.Add
35
36
Nick Weisenberger
When you do not want to see your screen follow the actions of your VBA
procedure (macro), you start and end your code with the following sentences:
At the start:
Application.ScreenUpdating = False
To write text in a specific cell, such as the first row's header values, use
Excel.Cell (row #, column #).
'row one headers
'Cell A1
Excel.Cells(1,1)="Part Number"
'Cell B1
Excel.Cells(1,2)="Fasteners"
Excel.Cells(1,3)="Name"
Excel.Cells(1,4)="Thickness"
Excel.Cells(1,5)="Material"
Excel.Cells(1,6)="Mass"
Excel.Cells(1,7)="Sorter"
37
You can use a variable to assign a cell number. For example, if you have a
For Loop and want the Excel row number to increase by one for each iteration of
the loop you might use this:
Dim RwNum As Integer
For I = 1 to 10
Excel.Cells(RwNum, 4) = getThickness
Excel.Cells(RwNum, 5) = getMaterial
Excel.Cells(RwNum, 6) = getMass
RwNum = RwNum + 1
Next 'i
Here is an example using an IF THEN formula. If the name of the CATIA
document does not equal PERMANENT_FASTENERS then enter the name of the
document and add one to the row count, otherwise enter no cell value and leave the
row count the same. Namebody is the name of a body within a catpart.
If namebody <>"PERMANENT_FASTENERS" Then
Excel.Cells(RwNum+1,2)= namebody
RwNum = RwNum + 1
End If
Else
RwNum = RwNum
Excel Formulas
You may also need to include formulas to attain the correct cell value. Add
a .Formula after the Excel.Cell().
38
Nick Weisenberger
Some Excel formulas require quotation marks. If this is the case you will
have to use Chr(34) character representation instead.
Excel.Cells(1,9).Formula =
"=SUMIF(I5:I"&RwNum+2&","&Chr(34)&">0"&Chr(34)&")"
Now let's combine a For Loop with a couple of SUM and IF formulas.
Dim RwNumX As Integer
RwNumX=1
For x=1 to RwNum
Excel.Cells(RwNumX,11).Formula =
"=SUM($J$2:J"&RwNumX &")"
Excel.Cells(RwNumX,12).Formula= "=IF(J"&RwNumX &"=0,
M1,K"&RwNumX&")"
Next 'x
40
Nick Weisenberger
Inserting new rows and columns into your spreadsheet is very easy. First, select a
cell in the spreadsheet and then specify if you want to insert a row above it as in
these examples:
'insert a row at the top for headers
Excel.Cells(1,1).Select
Excel.ActiveCell.EntireRow.Insert
'Insert column to the left of the active cell
Excel.ActiveCell.EntireColumn.Insert
'Insert column to the right of the active cell
Excel.Cells(1,8).Select
Excel.ActiveCell.EntireColumn.Offset(0, 1).Insert
41
Excel.ActiveWorkbook.ActiveSheet.Rows(2).Delete
'delete sorter column G
Excel.ActiveWorkbook.ActiveSheet.Columns(7).Delete
Formatting Excel
After all the formulas and sorting on the spreadsheet is complete, then its
time to format to get it the way you want it to look. I recommend leaving the
formatting until the end. Some formatting examples:
42
Nick Weisenberger
More examples:
change the font type, size, borders, colors, text wrap,
etc.
With Excel.Range("A"&"1", "G"&RwNum)
.Font.Name = "Arial"
.Font.Size = 9
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
'.ColumnWidth = 25
.RowHeight = 20
.Borders.LineStyle = xlContinuous
.Borders.Weight = xlThick
.Borders.ColorIndex = 1
.WrapText = True
.EntireColumn.Autofit
End With
44
Nick Weisenberger
'export to PowerPoint
Dim oPPT As Object
Set oPPT=CreateObject("PowerPoint.Application")
On Error Resume Next
Set oPPT = GetObject("PowerPoint.Application")
If Err.Number <> 0 Then
Set oPPT = New PowerPoint.Application
End If
45
Now, we are going to add a title slide to our PowerPoint presentation. There
are a number of different slide styles you can add, which is designated by the
second number inside the parenthesis after the Add. The first number is the slide
number. You can also set the header text box of the slide to display the part name of
your CATIA object or any other custom text.
'title slide
Set objSlide = oPPTPres.Slides.Add(1, 1)
objSlide.Shapes(1).TextFrame.TextRange.Text = partName
objSlide.Shapes(2).TextFrame.TextRange.Text =
"Annotation Data"
It is often useful to add images captured from the 3D model into your PPT.
We do this by inserting our image capture macro code within out PowerPoint
exporter.
46
Nick Weisenberger
If you insert image captures into your slideshow they may not be the right size
so you might have to adjust them manually. Before you make modifications, it is a
good idea to lock the aspect ratio. Use this code to lock the aspect ratio for all the
pictures as you insert them:
Pic.LockAspectRatio=True
At the end of your code you will probably want to make PowerPoint visible:
oPPT.Visible =True
Now you can export data from CATIA V5 to Microsofts PowerPoint!
Recommended Exercises: Workshop Tutorial 6 and 7
47
There are many other useful functions that are available through making calls to
Windows libraries. These are available from Microsofts website. Some examples:
Its always a good idea to add some notes at the beginning of your code
indentifying who wrote or modified the code, when the last revision was made,
what the code actually is supposed to do, etc. The following are a couple of CATIA
macros I wrote and have used throughout my professional career in one form or
another. Please feel free to use them for your own purposes and improve upon
them!
Return the Parent Name
Nick Weisenberger
Dim info
Set info = oSelElem.Parent.Parent
If Err.Number=0 Then
MsgBox "Parent Name = " & info.Name
Else
Msgbox "You must select an object to return the parent
name."
End If
End Sub
49
Nick Weisenberger
entered.
Operation
aborted.",
Else
'turn off the spec tree
Dim objSpecWindow As SpecsAndGeomWindow
Set objSpecWindow = CATIA.ActiveWindow
objSpecWindow.Layout = catWindowGeomOnly
'Toggle Compass
CATIA.StartCommand("Compass")
'change background color to white
Dim DBLBackArray(2)
objViewer3D.GetBackgroundColor(dblBackArray)
Dim dblWhiteArray(2)
dblWhiteArray(0) = 1
dblWhiteArray(1) = 1
dblWhiteArray(2) = 1
objViewer3D.PutBackgroundColor(dblWhiteArray)
'file location to save image
Dim fileloc As String
fileloc = "C:\Macro Files\"
Dim exten As String
exten = ".png"
Dim strName as string
strname = fileloc & partName & exten
51
'=======================================================
If MsgBox ("To reframe and automatically switch to ISO
view click Yes. To take the image as shown on screen
click No.", vbYesNo) = vbYes Then
objViewer3D.Viewpoint3D = objCamera3D.Viewpoint3D
'reframe
objViewer3D.Reframe()
'zoom in
objViewer3D.ZoomIn()
'objViewer3D.ZoomIn()
'clear selection for picture
CATIA.ActiveDocument.Selection.Clear()
'increase to fullscreen to obtain maximum resolution
objViewer3D.FullScreen = True
'MsgBox strname
'take picture with auto ISO view and reframe ON***
objviewer3D.Capturetofile 4,strname
'****take picture as is with NO reframe or iso view****
Else
zoom in
objViewer3D.ZoomIn()
'clear selection for picture
CATIA.ActiveDocument.Selection.Clear()
'increase to fullscreen to obtain maximum resolution
objViewer3D.FullScreen = True
52
Nick Weisenberger
'take picture
objviewer3D.Capturetofile 4,strname
End If
'*******************RESET**********************
objViewer3D.FullScreen = False
'change background color back
objViewer3D.PutBackgroundColor(dblBackArray)
'turn the spec tree back on
objSpecWindow.Layout = catWindowSpecsAndGeom
'toggle compass
CATIA.StartCommand("Compass")
End If
End Sub
Dim
Set
Dim
Set
viewer1 As Viewer
viewer1= CATIA.ActiveWindow.ActiveViewer
viewpoint1 As Viewpoint3D
viewpoint1= viewer1.Viewpoint3D
IdxSet = 1 To oAnnotationSets.Count
oAnnotationSet = oAnnotationSets.Item(IdxSet)
oAnnotations = oAnnotationSet.Annotations
IdxAnnot = 1 To oAnnotations.Count
oAnnotation = oAnnotations.Item(IdxAnnot)
Nick Weisenberger
With oSel
.Clear
.Add oAnnotation
Call .VisProperties.SetVisibleColor(0, 0, 0, 0)
End With
oAnnotation.ModifyVisu
End If
Next
Next
For i=1 To numCap
Set oCapture = CurAnnoSet.Captures.Item(i)
oCapture.DisplayCapture()
capNamer=CurAnnoSet.Captures.Item(i).Name
Set objViewer3D = CATIA.ActiveWindow.ActiveViewer
Set objCamera3D = CATIA.ActiveDocument.Cameras.Item(1)
'increase to fullscreen to obtain maximum resolution
objViewer3D.FullScreen = True
fileloc = "M:\Macro Files\"
exten = ".png"
strname=fileloc&partName&" "&capNamer&exten
'take picture
objviewer3D.Capturetofile 4,strname
Next 'i
End If
'change text back to white
For
Set
Set
For
Set
IdxSet = 1 To oAnnotationSets.Count
oAnnotationSet = oAnnotationSets.Item(IdxSet)
oAnnotations = oAnnotationSet.Annotations
IdxAnnot = 1 To oAnnotations.Count
oAnnotation = oAnnotations.Item(IdxAnnot)
With oSel
.Clear
.Add oAnnotation
Call .VisProperties.SetVisibleColor(255, 255, 255, 255)
End With
oAnnotation.ModifyVisu
End If
Next
Next
'================================================
'error handling
Else
Msgbox "Not a part document! Open in new window."
End If
End Sub
Help Documentation
Nick Weisenberger
Final Thoughts
Now you know how to write VBScript macros for CATIA V5! Youre on
your way to automating those repetitive tasks and impressing your coworkers and
bosses.
Good luck and happy programming!
-Nick Weisenberger
57
58
Nick Weisenberger
Appendix I: Acronyms
The following terms are used throughout this text (in alphabetical order):
59
WORKSHOP Tutorials
The following pages contain seven step-by-step tutorials designed to
help teach you macro programming in CATIA V5.
Contents
Workshop 1: Fundamentals
Workshop 2: Creating Your Own VBA Modules and Classes
Workshop 3: Creating a Basic VBA Program from Scratch
Workshop 4: Objects in CATIA VBA
Workshop 5: Navigating a Part Document with Error Handling
Workshop 6: Creating Sketch Geometry
Workshop 7: Using Forms in CATIA VBA
WS-1
WORKSHOP 1
Fundamentals
WS-2
Workshop 1 Introduction
Description
VBScript is a subset of the Visual Basic Programming language
(VBA). All elements of VBScript are present in VBA, but some VBA
elements are not implemented in VBScript. The result of the slimming down
process is a very small language that is easy to use. Code specific to CATIA is
saved as .CATScript. In this workshop you will learn some of the basic
fundamentals needed to create and run macros.
Outline
1.
2.
3.
4.
WS-3
Standardization
Improve efficiency
Expand CATIA capabilities
Streamline tasks
1. Macro recorder
2. Write custom code with the macro editor
WS-4
WS-5
WS-6
Make sure the Library type is set to "Directories" then click "Add existing library"
WS-7
Browse to "C:\MyCatScripts" or
wherever your catscripts are saved then
click ok.
WS-8
WS-9
WS-10
Recording a Macro
WS-12
WS-13
Finally, drag and drop the .CATScript file from the command window
to whatever toolbar you would like the icon to appear on
Now you can click the Icon to run your macro!
You can also setup a custom keyboard shortcut as well.
Code can be sent to other user as a lightweight .txt text file
WS-14
Fundamentals Example
Hit alt+F8 to open the macro window. Create a new CATScript
macro named msgbox. Click the Edit button. Copy and paste the
code below. The following code will display a message box with the
text "Hello." strHello is a variable declared as a string (or text) object.
strHello is then defined. Every Sub must end with "End Sub". Click
Save. Close the editor and run your macro. The "Hello" message box
should appear.
Su b CATMain ( )
Dim st rHe llo As St rin g
st r He llo ="He llo "
MsgBo x st r He llo
En d Su b
WS-15
Workshop 1 Conclusion
WS-16
WORKSHOP 2
WS-17
Workshop 2 Introduction
Description
Although most of the CATIA VBA programming that you will do
will involve the use of classes that are defined by the CATIA
programming API, you will likely find it useful to define your own
classes. In this workshop you will create a custom class in order to
demonstrate the fundamentals of VBA object design.
Outline
1.
2.
3.
4.
Step 1
Open the VBA editor by hitting Alt + F11. Create a new macro library and VBA
project, called "myVBA".
Double click on your newly created library (which will appear in Current
Libraries).
WS-19
Step 2
Ensure the project and properties boxes are visible by going to the top menu bar
and clicking View >View Project Explorer and View Properties Window
Right click on VBAProject (myVBA in this example) > Insert> Module.
Use the (Name) field in the properties box to rename it
"Create_New_Part_Document"
WS-20
Step 3
Right click on the Modules folder of the VBA project and select Insert > Class Module.
Rename the resulting class module as Messenger by clicking on Class1 then renaming the
"Name" field in the
properties box.
WS-21
Step 4
WS-22
Step 5
Enter the code seen to the right into the
UseTheMessenger module. Note the
following:
Sub CATMain()
Dim oMssgr As Messenger
Set oMssgr = New Messenger
oMssgr.Message = "Hello"
MsgBox oMssgr.Message
End Sub
Step 6
Return to the code window for the class module Messenger" and make the
changes shown below. These changes have the effect of hiding the strMessage
variable, but then create a read-only property named Message whose value is
stored in the strMessage variable.
Now go back to the UseTheMessenger module and make the changes shown
below and to the right.
Sub CATMain()
Private strMessage As String
Property Let Message(MessageIN As String)
strMessage = MessageIN
End Property
WS-24
Step 7
Attempt to run UseTheMessenger and note that although the Message property
can be set, it fails when the property is gotten. This is because no Property Get
method has been defined (although, Property Let has been defined).
WS-25
Step 8
Return to the code window for the class module Messenger and add a Property
Get method as shown below.
Run the UseTheMessenger module again. It should work and the message Hello
should be displayed.
Note: the advantage of strictly defining these Let and Get methods is that it gives
the programmer control over whether a variable is read-only or read-write. Also, the
code that is in the Let and Get methods can contain more complex operations
and logic.
Step 9
Assume it would be desirable to keep count of how many times the Message
propertys value is changed. To do this, create a private integer variable iCount,
change the Property Let method of the Message property, and add a Property
Get method for a new property named MsgChangeCount.
Private strMessage As String
Private iCount As Integer
Property Let Message(strMessageIN As String)
strMessage = strMessageIN
iCount = iCount + 1
End Property
Property Get Message() As String
Message = strMessage
End Property
Property Get MsgChangeCount() As Integer
MsgChangeCount = iCount
End Property
WS-27
Step 10
Change the UseTheMessenger module as shown below. Run it and a message
should be displayed saying Message changed 1 times.
Change the UseTheMessenger module as shown to the lower right and run it
again. A message should be displayed saying Message changed 2 times.
Sub CATMain()
Dim oMssgr As Messenger
Set oMssgr = New Messenger
oMssgr.Message = "Hello"
MsgBox "Message changed " &
oMssgr.MsgChangeCount & " times."
Sub CATMain()
Dim oMssgr As Messenger
Set oMssgr = New Messenger
oMssgr.Message = "Hello
oMssgr.Message = "Hello again
MsgBox "Message changed " &
oMssgr.MsgChangeCount & " times."
End Sub
End Sub
WS-28
Step 11
Although the class works presently, there is one area where the class code
could be more explicit. The iCount variable is incremented by one every
time the Message property is changed, but it isnt clear what value iCount
starts at. Testing the code has shown that it does start at zero, however its
best to be explicit.
In the code window for the Messenger class module, click the left dropdown menu and choose Class.
WS-29
Step 12
The result of the previous step should be that the text for the subroutine
Class_Initialize appears in the code window. Enter the code shown below into
this sub. This has the effect of setting the value of the iCount to zero when a
Messenger object is created with the New command.
WS-30
Step 13
Properties have been defined for the messenger class. Now create a method for
this class. This method will capitalize the message that is stored in the Message
property. Enter the code seen below in the Messenger class module.
The function UCase is a standard VBA function that takes a String as an argument
and returns the same string in all capital letters.
Private strMessage As String
Private iCount As Integer
WS-31
Step 14
Change the UseTheMessenger code so that it calls this new capitalize method as
shown.
Run the code. Note that the capitalize method has the intended effect of changing
the message box text from Hello to HELLO.
Sub CATMain()
Dim oMssgr As Messenger
Set oMssgr = New Messenger
oMssgr.Message = "Hello"
oMssgr.Capitalize
MsgBox oMssgr.Message
End Sub
WS-32
Workshop 2 Conclusion
This concludes Workshop 2. In this workshop you have learned to:
Create a VBA class
Define a read-only property for the class (only provide a Property Let
method)
Define a read-write property for the class (provide both Property Let
and Property Get methods
Use the Class_Initialize subroutine to assign initial values to class
variables
WS-33
WORKSHOP 3
WS-34
Workshop 3 Introduction
Description
In this workshop, as opposed to starting a CATIA VBA
program by recording a macro, you will instead insert a new
module into an existing CATIA VBA library and type the program
statements in manually. You will also see the difference between
Subs and Functions, and get experience using primitive variable
types, arrays, and For loops.
Outline
1.
2.
3.
4.
5.
WS-35
WS-36
Step 2
In the code window, type the code shown below
Click Save on the File menu to save the your changes.
Sub CATMain()
'Declaration of variables
Dim intA As Integer
Dim intB As Integer
Dim intC As Integer
'Valuate two of the variables
intA = 2
intB = 3
'Set the value of the third as a sum
' of the first two
intC = intA + intB
'Create a string to be displayed as output. The function Str()
'converts
the integer intC into a String
Dim strOut As String
strOut = "The sum is " + Str(intC)
'Call a message box to display the output string
MsgBox strOut
End Sub
WS-37
Step 3
WS-38
Step 4
Right-click on the myVBA project on the Project tree and select Insert > Module.
Rename the newly created module Workshop2_02.
In the code window, type the code shown below.
Sub CATMain()
Dim intA As Integer
Dim intB As Integer
Dim intC As Integer
intA = 2
intB = 3
DisplaySum intA, intB
End Sub
Sub DisplaySum(ByVal int1 As Integer, ByVal int2 As Integer)
Dim int3 as integer
int3 = int1 + int2
MsgBox The sum is + Str(int3)
End Sub
WS-39
Step 5
Click Save on the File menu to save the your changes.
Run the macro, this time by using the Run button in the VBA editor. This
requires that the cursor in the code window is sitting within the CATMain Sub.
Sub CATMain()
Dim intA As Integer
Dim intB As Integer
Dim intC As Integer
intA = 2
intB = 3
DisplaySum intA, intB
End Sub
Sub DisplaySum(ByVal int1 As Integer, ByVal int2 As Integer)
Dim int3 as integer
int3 = int1 + int2
MsgBox The sum is + Str(int3)
End Sub
WS-40
Step 6
Right-click on the myVBA project on the Project tree and select Insert > Module.
Rename the newly created module Workshop2_03
In the code window, type the code shown below
Click Save on the File menu to save the your changes.
Run the macro, this time by using the Run button in the VBA editor. This requires
that the cursor in the code window is sitting within the CATMain Sub.
Sub CATMain()
Dim intA As Integer
Dim intB As Integer
Dim intC As Integer
intA = 2
intB = 3
Step 7
Right-click on the myVBA
project on the Project tree
and select Insert > Module.
Rename the newly created
module Workshop2_04
In the code window, type the
code shown to the right
Click Save on the File menu
to save the your changes.
Sub CATMain()
Dim intA(3) As Integer
Dim intB(3) As Integer
Dim intC As Integer
intA(1) = 1
intA(2) = 2
intA(3) = 3
intB(1) = 1
intB(2) = 2
intB(3) = 3
Dim i As Integer
For i = 1 To 3
intC = DisplaySum(intA(i), intB(i))
MsgBox intC
Next
End Sub
Function DisplaySum(ByVal int1 As Integer, ByVal int2 As Integer) As Integer
WS-42
Workshop 3 Conclusion
This concludes Workshop 3. In this workshop you have learned to:
Create a CATIA VBA program from scratch
Use primitive variable types such as integers and strings
Use a Sub (subroutine) to encapsulate code that is to be called
multiple times throughout a program
Use a Function in a way similar to a Sub, but when a return
value is desired
Use an array to store a list of primitives (integers in this case)
and then iterate through that array using a For loop
WS-43
WORKSHOP 4
WS-44
Workshop 4 Introduction
Description
In this workshop you will explore the basics of objects, their
properties, and their methods in CATIA VBA programming.
Outline
1.
2.
3.
4.
WS-45
Step 1
Create a new module in the myVBA
macro library called
CATIAbasicObjects
In the code window type Sub
CATMain() and hit Enter.
In the CATMain() Sub, type CATIA.
(notice the period) and note that the
Intellisense drop-down appears,
displaying a list of properties and
methods of the CATIA object.
Note that the Documents property
of the CATIA object is on the list.
This is what is depicted in the CATIA
object model diagram below.
NOTE: the object called Application
is the same as the CATIA object in
the VBA view.
WS-46
Step 2
Scroll down the Intellisense drop-down and note that the Windows property is there as well.
So Documents and Windows are both properties of the CATIA object, but they
are also objects themselves. Moreover, they are a special type of object: they
are collections.
Erase the text CATIA. that you just entered.
WS-47
Step 3
Open 3 new parts in CATIA, accepting their default names and save them
anywhere on disk.
Enter the code below into the code window.
Run the macro using the Run button. The count of open documents should be
displayed.
Sub CATMain()
Dim documents1 As Documents
Set documents1 = CATIA.Documents
MsgBox "The number of documents is "
& documents1.Count
End Sub
WS-48
Step 4
Add the code shown to the right and re-run the macro:
Note: The method Item() was used on the Documents object documents1 in order
to retrieve a member of the collection.Then the Name property and FullName
property of the Document object doc1 were used. These properties return Strings,
which were displayed in the message boxes.
Sub CATMain()
Dim documents1 As Documents
Set documents1 = CATIA.Documents
MsgBox "The number of documents is " & documents1.Count
Dim doc1 As Document
Set doc1 = documents1.Item(1)
MsgBox doc1.Name
MsgBox doc1.FullName
End Sub
WS-49
Step 5
Modify the previous code as shown in the
code window to the right
Run the new code using the Run button.
Note that the For each loop iterates
through the Documents collection
documents1. The same effect could be
achieved with the below code, but a For
Each loop is simpler:
Sub CATMain()
Dim documents1 As Documents
Set documents1 = CATIA.Documents
MsgBox "The number of documents is " &
documents1.Count
Dim doc1 As Document
Set doc1 = documents1.Item(1)
MsgBox doc1.Name
MsgBox doc1.FullName
Next
Next
End Sub
WS-50
Step 6
Modify the previous code as shown in
the code window to the right:
1) Uncomment a couple lines
2) Comment the For Each loop out
completely
3) Add more code
Run the new code using the Run
button.
Sub CATMain()
Dim documents1 As Documents
Set documents1 = CATIA.Documents
MsgBox "The number of documents is " &
documents1.Count
Dim doc1 As Document
Set doc1 = documents1.Item(1)
MsgBox doc1.Name
MsgBox doc1.FullName
For Each doc1 in documents1
MsgBox doc1.Name
Next
Dim partDoc1 as PartDocument
Set partDoc1 = doc1
MsgBox partDoc1.Name
End Sub
WS-51
Step 7
Note that the PartDocument object partDoc1 is Set to the Document object
doc1. The setting of a variable to an object of a different type is possible in this
case because the PartDocument class inherits from the Document class. This is
depicted in the CATIA object diagram below. Not only does PartDocument inherit
from Document, but so does ProductDocument, DrawingDocument, etc.
WS-52
Step 8
Modify the previous code as shown in the
code window to the right by adding the line:
partDoc1.Close
Note in the Intellisense drop-down that the
Close method has a green icon to indicate
that it is a method as apposed to a property.
The icon for a property can be seen for the
property FullName
Run the new code using the Run button
Note that the calling of this Close method
performs the action of closing the document
Sub CATMain()
Dim documents1 As Documents
Set documents1 = CATIA.Documents
MsgBox "The number of documents is " &
documents1.Count
Dim doc1 As Document
Set doc1 = documents1.Item(1)
MsgBox doc1.Name
MsgBox doc1.FullName
For Each doc1 in documents1
MsgBox doc1.Name
Next
Dim partDoc1 as PartDocument
Set partDoc1 = doc1
MsgBox partDoc1.Name
partDoc1.Close
End Sub
WS-53
Workshop 4 Conclusion
This concludes Workshop 4. In this workshop you have learned to:
Access the properties of objects
Iterate through the items of a collection
Set a variable of one type to an object of another type that it
inherits from
Call the methods of objects
WS-54
WORKSHOP 5
WS-55
Workshop 5 Introduction
Description
In this workshop you will learn to drill down the object structure a
part document while using error handling to deal with certain
programmatic challenges.
Outline
1.
2.
3.
WS-56
Step 1
First, we are going to create some geometry to test our macro on. Units and names
do not matter for this exercise.
Create a new part
In the part design workbench, draw a sketch of a square on any plane
Pad the sketch (to any length)
Under Geometrical Set 1, create an offset plane and a datum (explicit) plane
WS-57
Step 2
Create a new module in the myVBA macro library called NavigatePart
Enter the code shown on the right
With the new part open, run the code using either the play button or the Tools >
Macro > Macros menu.
NOTE: Nothing happens
Now, create a new product document and leave it open in CATIA as the active
document. Run the code again and the message box should appear
Sub CATMain()
On Error Resume Next
Dim partDoc1 As PartDocument
Set partDoc1 = CATIA.ActiveDocument
If Err.Number <> 0 Then
MsgBox "Active document is not a part document!
End
End If
End Sub
WS-58
Step 3
Open the V5Automation.chm file and go to the object diagram for part documents. The first goal is to add code
that will count the number of sketch-based-features. These feature objects are all different kinds of shapes". The
diagram shows that we will have to drill down like so: Part > Bodies > Body > Shapes. Click on the red arrow
next to the Shape box to see a more detailed view of Shape objects.
WS-59
WS-60
End If
Err.Clear
Next
MsgBox "Number of sketch based shapes is " & count1
End Sub
WS-61
For i = 1 To shapecount
Set sketchShape = shapes1.Item(i)
If Err.Number = 0 Then
count1 = count1 + 1
End If
Err.Clear
Next
WS-62
WS-63
WS-64
WS-65
For k = 1 To geocount
Set datumPlane = hybridBody1.HybridShapes.Item(k)
If Err.Number = 0 Then
count2 = count2 + 1
End If
Err.Clear
Next
MsgBox "Number of sketch based shapes is: " &
count1 & vbNewLine & _
"Number of datum planes is : " & count2
End Sub
WS-66
Workshop 5 Conclusion
This concludes Workshop 5. In this workshop you have learned to:
Use the object diagrams found in the .chm file to understand
CATIA objects
WS-67
WORKSHOP 6
Creating Sketch Geometry
WS-68
Description
Outline
1.
2.
3.
Open the recorded macro and observe what has been recorded.
4.
WS-69
WS-70
WS-72
Sub CATMain()
===============================================
Get the part body
===============================================
Dim partDocument1 As PartDocument
Set partDocument1 = CATIA.ActiveDocument
WS-73
===============================================
Add a sketch on the Y-Z Plane
===============================================
Dim sketches1 As Sketches
Set sketches1 = body1.Sketches
WS-74
line2D1.ReportName = 1
Dim line2D2 As Line2D
Set line2D2 = axis2D1.GetItem("VDirection")
REPLACEMENT CODE
line2D2.ReportName = 2
Dim point2D1 As Point2D
Set point2D1 = factory2D1.CreatePoint(20#, -20#)
point2D1.ReportName = 3
Dim point2D2 As Point2D
Set point2D2 = factory2D1.CreatePoint(60#, -50#)
point2D2.ReportName = 4
WS-75
WS-77
WS-78
===============================================
Creating Sketch Geometry
===============================================
part1.InWorkObject = sketch1
Dim factory2D1 As Factory2D
Set factory2D1 = sketch1.OpenEdition()
Dim axis2D1 As Axis2D
Set axis2D1 =
sketch1.GeometricElements.Item("AbsoluteAxis")
Dim point2D1 As Point2D
Set point2D1 = factory2D1.CreatePoint(20#, -20#)
Dim point2D2 As Point2D
Set point2D2 = factory2D1.CreatePoint(60#, -50#)
Dim line2D3 As Line2D
Set line2D3 = factory2D1.CreateLine(20#, -20#, 60#, -50#)
line2D3.StartPoint = point2D1
line2D3.EndPoint = point2D2
sketch1.CloseEdition
part1.InWorkObject = body1
part1.Update
End Sub
WS-79
Workshop 6 Conclusion
This concludes Workshop 6. In this workshop you have
learned to:
Start a CATIA VBA program by first recording a macro
WS-80
WORKSHOP 7
Using Forms in CATIA VBA
WS-81
Workshop 7 Introduction
Description
In this workshop you will learn how to use VBA forms in order to
provide users with a user interface from which they can launch CATIA
VBA programs.
Outline
1.
2.
3.
WS-82
WS-83
Step 1b
Name it the form frmCreateLine by editing the (Name) property.
Edit the caption of the form by using the Caption property.
WS-84
WS-85
In the blank code window for the newly created module enter the following code:
Sub CATMain()
frmCreateLine.Show
End Sub
WS-86
WS-87
WS-88
WS-90
Label
Label
TextBox
(Name) = lblPointA
(Name) = lblXcoord
(Name) = lblYcoord
(Name) = tbPointAy
Caption = X-Coordinate
Caption = Y-Coordinate
Text = 0
Caption = Point A
TextBox
(Name) = tbPointBy
Label
Text = 10
(Name) = lblPointB
TextBox
(Name) = tbPointBx
Text = 10
TextBox
CommandButton
(Name) = tbPointAx
Text = 0
(Name) = cbCreateLine
WS-91
WS-92
WS-93
WS-94
===============================================
Creating Sketch Geometry
===============================================
part1.InWorkObject = sketch1
Dim factory2D1 As Factory2D
Set factory2D1 = sketch1.OpenEdition()
Dim axis2D1 As Axis2D
Set axis2D1 = sketch1.GeometricElements.Item("AbsoluteAxis")
Dim point2D1 As Point2D
Set point2D1 = factory2D1.CreatePoint(20#, -20#)
Dim point2D2 As Point2D
Set point2D2 = factory2D1.CreatePoint(60#, -50#)
Dim line2D3 As Line2D
Set line2D3 = factory2D1.CreateLine(20#, -20#, 60#, -50#)
WS-95
==============================================
Creating Sketch Geometry
==============================================
part1.InWorkObject = sketch1
REPLACEMENT CODE
WS-96
Step 11. Save the VBA project and run the macro
Highlight the VBA library on the project tree and save your changes
Close the VBA window, open a new part, and open the macros dialog
through Tools > Macro > Macros, and run the Show_CreateLine_Form
macro.
WS-97
Sub CATMain()
frmCreateLine.Show vbModeless
End Sub
Save the project, close the VBA editor, and run the
Show_CreateLine_Form macro. Note that even before you hit the
Create Line button you are able to interact with CATIA (zoom in, rotate,
etc.). Change point coordinate values on the form and hit the Create
Line button to create another sketch.
WS-99
Workshop 7 Conclusion
This concludes Workshop 7. In this workshop you have
learned to:
Create a form and insert code into its Event subroutines
WS-100