Getting Started With VBA For CATIA V6

Print Friendly, PDF & Email

Getting Started With VBA For CATIA V6

This post will walk you through getting started with VBA for CATIA V6, but the process can easily be expanded for any application that has the capability to automated with VBA, such as Word, Excel, CATIA V5 etc..

VBA Fundamentals

So what is VBA, VBA stands for Visual Basic for Applications and has been around for a long time, you may have recorded macros in Excel and just played them when you need these were recorded in the VBA language and you may have referred to them as scripts.

Within every programming language there are keywords, these keywords are interpreted and understood by the compiler, and syntax how these keywords are organized again interpreted and understood by the compiler. were going to look at just enough to get started and then explorer the other keywords and syntax as we go.

Commenting Code

In most code editors we can add comments to the code that the compiler will ignore, VBA is no exception to this. When we want to add a comment a single quote is used.

' This is a Comment

Keywords

Lets go through the basic keywords for VBA.

Dim (Declare In Memory)

The DIM (Declare In Memory) keyword allows us to create a space in memory and it has a syntax as follows;

Dim VariableName As String
'Dim Declare In Memory
'VariableName can be anything
'As is the keyword used prior to the variable type name
'String the variable type name

The “‘VariableName” can literally be anything, the As is another keyword, which is used prior to the variable Type Name, and finally the Type Name in this case is String, there are many Type Names but the standard ones tend to be;

  • String to store text values, must be wrapped in double quotes e.g., “This is a String!”
  • Long and Integer to store whole numbers
  • Double to store numbers with decimals
  • Boolean to store TRUE and FALSE values
  • Object to store VBA objects such as worksheets and charts

A variable is a location in your computer’s memory that you define and then use to store values. This storage is temporary and the values are cleared when your macro ends. You can name a variable something meaningful and specify the type of data that it will store. You can then access and change that variable’s value as many times as you want in your VBA code.

When creating variables the variable name must not begin with a number, cannot use special characters such as %, &, ! or @, including spaces. Finally, reserved keyword such as Dim, Public or Next cannot be used. These reserved words are important for other VBA operations.

Set Keyword

Set, is a keyword used in VBA programming to assign a reference to an object, which is going to remain fix throughout the program. Within VBA we have two groups of things, Objects (Classes) and Property’s. Property’s are typically values so Integers, Doubles, Boolean, Strings etc.. Where as Objects are Classes they are collections of Methods, Other Objects and Property’s, they define a structure an object.

Why is this important, wee when dealing with variables or property’s vs. objects and equating them, we have to handle them slightly differently. Its pretty simple, when equating Objects we must use the Set keyword where as property’s we don’t.

Dim MyProperty As String
MyProperty = "255,255,255" ' No Set Keyword Since its a Property

Dim ioCATIA as Application
Set ioCATIA = CATIA ' Set Keyword Required Since its an Object
Sub and Function

The code we write must be contained within a code block, there are two types of code blocks Subroutines and Functions. There is a very simple difference between these two type, a Subroutine executes the code within it, whereas a Function executes the code within it and returns something.

Every program must have an entry point, the main subroutine that is executed when the script is called. This subroutine can have nested subroutines and functions within it, and these nested subroutines and functions can have nested subroutines and functions within them and so on. So your program structure ends up being a tree structure. The other benefit of this is that code can be objectified and reused when ever you need to use it.

Both Sub and Function are keywords and have their own syntax as follows;

Sub SubroutineName()
  
End Sub

Sub SubroutineName2( InputVariable As Integer )
  
End Sub

Sub SubroutineName3( InputVariable As Integer , InputVariable2 As String )
  
End Sub

Function FunctionName() As Double
  
End Function

Function FunctionName2( InputVariable As Integer , InputVariable2 As String ) As Double
  
End Function

The “SubroutineName” can literally be anything, the parenthesis give us the opportunity to pass in one or more variables into the subroutine or function. The End Sub tells the compiler when the Subroutine is complete. The Function syntax is very similar however notice the As Type Name statement at the end of the Function declaration. This tells the compiler the type of data being returned by the function, remember a subroutine just does something whereas a function does something and returns something. Like a manager who tells the employee to create a report and email it to them, so they can present it.

Some applications require the main subroutine to have a very specific name i.e. CATIA which requires the main routine to be CATMain.

Sub CATMain()
  
End Sub

If this is not the case then its good practice to call out the entry point.

Sub ThisIsMyEntryPoint()
  
End Sub

From the main subroutine we can call other subroutines and functions. When we do this we have to remember that subroutines just do something whereas functions return something dependent on their return type defined by the As Type Name after the closing parenthesis. Lets first look at calling a subroutine.

Within the Main Subroutine were calling the same Subroutine twice, but each time passing a different string, which is then displayed in a message box by the subroutine “DisplayMessage”.

Sub CATMain()
  DisplayMessage("Hello World!")
  DisplayMessage("Bob's Your Uncle.")
End Sub

Sub DisplayMessage(iMessage As String)
  msgbox(iMessage) 
End Sub

Now lets look at how we call a function, its not unlike calling a subroutine but we have to equate it to something. In this case the Function returns a String so we have to create a String variable (Message) and equate it to the “BuildMessage” function. This function similar to the previous example requires a string to be passed to it.

Sub CATMain()
  Dim Message As String
  Message = BuildMessage("Bob")
  msgbox(Message)
  Message = BuildMessage("Gavin")
  msgbox(Message)
End Sub

Function BuildMessage(iName As String) As String
  BuildMessage = "My Name is " & iName
End Function
If Else ElseIf End If

No programming language would be complete without the capability to check conditionality, in VBA we have two types If and Switch, lets look at If first. The If keyword is followed by a logic expression for example; <, <=, =, >=, >, <> there are some other logic expression but lets keep it simple. The logic expression does not have to be wrapped in parenthesis but this keeps it readable. If the logic expression is in parity Then the the code between the If and ElseIf, Else or End If is executed. The Then, ElseIf, Else or End If are all keywords that make up the syntax of the If, Else, ElseIf, End If.

If(boolean_expression) Then
   Statement 1
   .....
   .....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
   .....
   ....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
   .....
   ....
   Statement n
Else
   Statement 1
   .....
   ....
   Statement n
End If

Let’s put some of this together, the msgbox(“Message”) is an out of the box VBA subroutine that requires a string to be passed into it as an input. This subroutine will display a message box to the user containing the passed in string. So lets use this to try out some simple If Statements.

Dim X as Integer ' Create a space in memory that will hold an integr value ,called X
X = 1 ' Initilize X with the value of 1
If( X = 1 ) Then ' evaluate if X equals 1
  msgbox("True") ' If X equals one, display a message
End If ' end the if statement

X = 11 ' Initilize X with the value of 11
If( X < 10 ) Then ' evaluate if X is less than 10
  msgbox("True")
Else
  msgbox("False") ' If X is not less than 10, display a message
End If ' end the if statement

X = 15 ' Initilize X with the value of 15
If( X < 5 ) Then
  msgbox("False")
ElseIf( X >=15 )  Then ' evaluate if X is Greater than or Equal to 15
  msgbox("True") ' If X is greater than or equal to fifteen, display a message
Else
  msgbox("False")
End If

So lets put some of this together, but to do that we want to make it a little more interactive by using an additional out of the box vba function; UserValue = InputBox(Message, Title, Default) this function displays a window which allows a user to enter a value which is returned by the function. This function takes in three inputs; a message, a title and a default value.

Were also going to use the And keyword to define a range within the logic expression, Or can also be used. Also within the msgbox subroutine we will use the & keyword to concatenate two strings together (remember when the compiler evaluates the variable at runtime the variable is replaced by its current value).

Sub CATMain()
  
  Dim UserValue As Integer
  Dim UserMessage As String
  Dim UserTitle As String
  Dim UserDefault As Integer
  
  UserMessage = "Enter a Value Between 1 and 100."
  UserTitle = "Enter Value."
  UserDefault = 50
  UserValue = inputBox( UserMessage , UserTitle, UserDefault)
  
  If ( UserValue <=25 ) Then
    msgbox( "You Selected a Value Between 0 and 25 : " & UserValue )
  ElseIf ( UserValue > 25 And UserValue <= 50 ) Then
     msgbox( "You Selected a Value Between 26 and 50 : " & UserValue )
  ElseIf ( UserValue > 50 And UserValue <= 75 )
     msgbox( "You Selected a Value Between 51 and 75 : " & UserValue )
  Else
     msgbox( "You Selected a Value Between 76 and 100 : " & UserValue )
  End If
  
End Sub
For Next

In any code its important to have the ability to loop, within VBA the For loop allows us todo that. The For loop requires a Counter, Start and End integer only the Counter must be a pre declared variable, since its value will increment with every loop. Within the For loop the Counter is initialized to the value of the Start integer. Then the To key word defines the End integer value, essentially the from to count. By default the For loop will increment by 1 every time the code hits the Next keyword. However we can use the Step key word to define the step size of the Counter value. After the Next keyword the Counter variable can be added again this is redundant in the latest VBA releases.

For counter = Start To End [Step stepsize]
   Statement 1
   .....
   ....
   Statement n
Next [counter]

In the following examples, each For loop calls a simple subroutine to display the current Counter value. Each For loop example uses a slightly different For loop syntax, some counting in increments of 1 some in increments of 2 and some counting backwards.

Sub CATMain()

  Dim Counter, Start, Target, StepSize As Integer
  Start = 1
  Target = 10
  StepSize = 1

  For Counter = Start To Target Step StepSize
   'Statement 1
    Messaging(Counter)
   'Statement n
  Next
  
  For Counter = 1 to 10
   'Statement 1
    Messaging(Counter)
   'Statement n
  Next

  For Counter = 1 to 10 Step 1
   'Statement 1
    Messaging(Counter)
   'Statement n
  Next
  
  For Counter = 10 to 1 Step -1
   'Statement 1
    Messaging(Counter)
   'Statement n
  Next
  
  For Counter = 1 to 10 Step 2
   'Statement 1
    Messaging(Counter)
   'Statement n
  Next Counter
  
End Sub

Sub Messaging(iCounter As Integer)
  msgbox("Current Count is : " & iCounter)
End Sub

Exit End

There are occasion when we just want to stop the code from running, this is where the End keyword is useful. For example we can use the msgbox as a function which returns a status i.e. which button did the user select within the message dialogue window; Yes, No, or Cancel. In this case No will end the Code with no message and Cancel will end the code with a message. Only Yes will allow any additional code to be executed.

Sub CATMain()

    Dim msgboxResult As String
    msgboxResult = MsgBox("Do You Want to Carry On?", vbYesNoCancel, "Carry On?")

    If (msgboxResult = vbNo) Then
        
        End
        
    ElseIf (msgboxResult = vbCancel) Then
    
        MsgBox ("Cancelling Command.")
		End

    End If

   	'Statement 1
	'Statement ...
   	'Statement n
    
End Sub

The Exit keyword is typically used in conjunction with a For loop, it allows a loop to stop loop prematurely based on a logic statement. In this case when the loop counter equals 5, an additional question asks if the user wants to exit the loop. If the response is yes then the for loop is exited.

Sub CATMain()

    Dim ioIndex As Integer
    For ioIndex = 1 To 10
    
        If (ioIndex = 5) Then
        
            Dim msgboxResult As String
            msgboxResult = MsgBox("Do You Want to Exit the For Loop?", vbYesNo, "Exit Loop")
            
            If (msgboxResult = vbYes) Then
            
                Exit For
                
            End If   
        End If
    Next
    
End Sub
Error Handling

Error Handling is very important and there are two frames of though on this; Catch any errors arising from the data being processed, or Catch any Error that were thrown intentionally or non-intentionally. I will be focusing on the data and intentionally throw errors in this section.

Within VBA by default an error will cause the execution to stop and an error message displayed. This default behavior can be turned off by using the following keywords in the following syntax.

On Error Resume Next

From this point onwards any error thrown will be ignored which maybe catastrophic for you code. We can turn error handling back on by using the following keywords in the following syntax.

On Error Goto O

In between these we can test for an error and then do something about it. In this example were asking the user to key in an integer value, but what if they don’t? Here is where we can use error handling to check for an error and then do something about it. In the first example we capture the error and set a default value for the integer variable. In the second example we keep looping until the user enters in an acceptable value or they choose to exit the script. Notice in the second example we have to reset the error handler to 0 before retrying, this is done by setting the Error Number property to 0.

We can use this same error handling to capture errors with code that maybe fragile based on the user data.

Sub CATMain()
  
  On Error Resume Next
  
  Dim UserValue As Integer
  UserValue = InputBox("Enter an Integer Value.", "Integer Value", 0)
  
  If (Err.Number <> 0) Then
    MsgBox ("You Entered an Alpha Charter Silly, Were Going to Use the Default Value.")
    UserVlaue = 0
  End If
  
  On Error GoTo 0
  
  On Error Resume Next
  
    Dim Passed As Boolean
    Passed = False
    Do While Passed = False
        UserValue = InputBox("Enter an Integer Value.", "Integer Value", 0)
    
        If (Err.Number <> 0) Then
            Dim Status As String
            Status = MsgBox("You Entered an Alpha Charter Silly, Did You Want to Try Again?", vbYesNo, "Try Again.")
            If (Status = vbNo) Then
                MsgBox ("Exitting Script.")
                End
            Else
                Err.Number = 0
            End If
        Else
            Passed = True
        End If
    Loop
  On Error GoTo 0
  
End Sub

Where possible its better to write same validation methods that you can use, prior to a line of code that potentially may throw an error. In the example below the function is designed to tell you if a directory exists. So prior to writing or reading a file from a directory we can validate if that directory exists. If the function returns False indicating that the directory does not exist we can go back to the user and ask them for a valid directory. This is better than allowing the error to happen, capturing this error and then doing something about it, we should be proactive not reactive.

Function DirectoryExists(Directory As String) As Boolean
    DirectoryExists = False
    If Len(Dir(Directory, vbDirectory)) > 0 Then
        If (GetAttr(Directory) And vbDirectory) = vbDirectory Then
            DirectoryExists = True
        End If
    End If
End Function

When writing a function or subroutine its often a good idea to catch unknow or unintended errors. This is done by using the Goto keyword with the following syntax. At the Start of the subroutine or function we tell the error handler On Error Goto ErrorSub, ErrorSub is a specific line in the code denoted by this name ErrorSub followed by “:”.

So if an error is thrown then the code will automatically jump to ErrorSub, and a message box will be displayed with the Error Description. If an Error is not thrown then when we get to Goto EndSub we are jumping the error reporting piece, since no error has been captured and Ending the subroutine or function normally.

Sub SelectGridBounds()
'Error handling
    On Error GoTo ErrorSub

   	'Statement 1
	'Statement ...
   	'Statement n
    
    'Error handling
    GoTo EndSub
ErrorSub:
    MsgBox Err.Description
EndSub:
    
End Sub

So for now this is a good basis to get going with VBA.