KB 51771 Lab Manual - VBA Error Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

KNOWLEDGEBASE

Using VBA with FT View SE

Hands on Lab Excerpt

Answer ID 51771

Error Handling Techniques in


FactoryTalk View SE VBA

1 of 40
Using VBA with FactoryTalk View SE Lab

Contents

Before you begin .........................................................................................................................................3


About this lab.................................................................................................................................................3

Tools & prerequisites.....................................................................................................................................3

Lab Setup ......................................................................................................................................................4

Document Conventions ..............................................................................................................................5

Starting FactoryTalk View Studio and the SE Client ...............................................................................6

Section 1: Error Handling in VBA .............................................................................................................8


About This Section ........................................................................................................................................8

About Error Exceptions in VBA .....................................................................................................................8

Using Option Explicit .....................................................................................................................................9

Displaying Error Messages in the Diagnostics Log.....................................................................................14

Errors and error trapping .............................................................................................................................18

2 of 40
Before you begin

About this lab


This lab demonstrates how to extend capabilities of FactoryTalk View SE by using Visual Basic for
Applications (VBA). The lab is aimed at a broad range of users; attendees should be familiar with VBA
Integrated Development Environment (IDE) of FactoryTalk View SE and writing VBA code.
This lab concentrates on how to write robust code and good error handling techniques with the VBA IDE
in FactoryTalk View SE.
The main section of this lab includes:

§ An exercise in exploring different error handling techniques. It is a hands-on approach designed


to show you the good and bad of each technique so you can decide which one is best for your
application.

Tools & prerequisites


The following software has been used for the examples in this lab manual:
§¤ RSLogix 5000 v16.03
§¤ SoftLogix5800 v16.03
§¤ FactoryTalk Services Platform v2.10
§¤ FactoryTalk View SE v5.00
§¤ RSLinx Enterprise v5.00

3 of 40
The following FactoryTalk View and RSLogix 5000 files are available for this example in the Lab Files
subdirectory:

1. A complete FactoryTalk View v5.0 SE application with many VBA examples, including the one detailed
in this technote. This can be found in: _Complete SE Application\VBA_Lab_v1_0.apa

This lab manual steps you through the VBA_Lab_v1_0 application


G and assumes you have it installed.

or 2. If you do NOT want to install the complete application and instead want to view each component
individually, they have been separated and included here:

RSLogix 5000 file: RSLogix 5000\VBA_Lab.ACD


SE Displays: SE Displays\ErrorHandling.gfx
Macros: Macros\ ErrorTrapping_Tags_Reset.mcr
Macros\ ErrorTrapping_Tags_Zero.mcr

HMI Tags: VBA_Lab-Tags.CSV

Lab Setup

SoftLogix/RS Emulate/ControlLogix
§¤ Load the RSLogix 5000 application into your controller. The examples in this manual use slot 2. Put
the controller in Run Mode.

FactoryTalk View SE
§¤ Restore the FactoryTalk View back-up apa file or manually create the SE application using the
individual files included (see above)
§¤ Ensure that your RSLinx Enterprise topic exists, points to the controller, and has alarms and events
enabled. The examples in this manual use the topic name SoftLogix.

4 of 40
Document Conventions

Throughout this workbook, we have used the following conventions to help guide you through the lab
materials.
This style or symbol: Indicates:
Words shown in bold italics Any item or button that you must click on, or a menu name
(e.g., RSLogix 5000 or OK) from which you must choose an option or command. This will
be an actual name of an item that you see on your screen or
in an example.
Words shown in bold italics, An item that you must type in the specified field. This is
enclosed in single quotes information that you must supply based on your application
(e.g., 'Controller1') (e.g., a variable).
Note: When you type the text in the field, remember that you
do not need to type the quotes; simply type the words that
are contained within them (e.g., Controller1).
The text that appears inside a box is supplemental
information regarding the lab materials, but not information
that is required reading in order for you to complete the lab
exercises. The text that follows this symbol may provide you
with helpful hints that can make it easier for you to use this
product. Most often, authors use this “Tip Text” style for
important information they want their students to see.
Note: If the mouse button is not specified in the text, you should click on the left mouse button.

5 of 40
Starting FactoryTalk View Studio and the SE Client

1. From the Start menu, select FactoryTalk View Studio

2. Double-click Site Edition (Local) Icon.

3. Select the existing project called VBA_Lab and click the Open buttin

4. After the project opens maximize FactoryTalk View Studio

5. Expand the ‘displays’ to show configured displays

6 of 40
6. Expand the height of the diagnostics bar to show 5 or 6 lines.Change it from a single line like this

to multiple lines like this

7. Click on the Launch SE Client icon from View Studio.

8. When prompted, select the C:\Lab Files\PV14 VBA Lab\VBA_Lab.cli configuration file.

7 of 40
Section 1: Error Handling in VBA

RELATED KNOWLEDGEBASE ANSWER IDS

35147: RSView SE VBA Error Handling for Communication Events Tips & Best Practices

About This Section


In this section, you will learn about error handling when using VBA in FactoryTalk View SE. You won’t be
required to actually write any code here, but you will observe several different methods of error handing in
terms of how they are programmed and their runtime behavior.

Ultimately, the choice of how to include error handling in your code is yours.
Note: the choice is how to include it, not if you include it!

In this section you will:


§¤ Learn how to use Option Explicit
§¤ Learn how to properly display error messages in the FactoryTalk Diagnostics Log
§¤ Explore different methods of error trapping and their behaviors

• No Error Trapping – execute code with no checks or error traps

• Manual Testing of Values – execute code with manual checks for bad values

• On Error Resume Next – If there's an error, skip that line of code and go to the next.

• On Error Goto/Resume – If there's an error, do something, then continue executing code


where you left off.

• On Error Goto/Resume Next – If there's an error, do something, then continue executing


next line of code.

• On Error Goto – If there's an error, do something, then stop executing the procedure.
Good to
• On Error Goto/WatchForErrors – Keep track of place in code and if there's an error,
know!
evaluate the current position in the code and react accordingly.

About Error Exceptions in VBA


When a run-time error occurs in a VBA application, an error message appears on the screen, and the
script either halts or behaves unpredictably.

To prevent the application from crashing or behaving unpredictably, you can include code that intercepts
the error and tells the macro how to handle it. The process of intercepting and handling a run-time error is
called "error trapping." The set of instructions that tells the application how to handle the error is called the
"error-handling routine" or "error handler."

8 of 40
When an error occurs, there is a system-level error statement that you can display; it will not be specific to
your application and your operator may not know what to do with it, but for completely unexpected errors,
the message may help you figure out what’s wrong.

For more information about Microsoft VBA and error handling, good reference can be found at:
Error Trapping with Visual Basic for Applications http://support.microsoft.com/kb/146864
How to Use "On Error" to Handle Errors in a Macro http://support.microsoft.com/kb/141571

Using Option Explicit


There is a very simple method to help reduce the occurrence of errors in your code; that is the use of the
‘Option Explicit’ key words. Make it a habit to put this statement as the first line in all your code
modules. Using this statement basically tells VBA to make you declare all the variables you are going to
use. It forces you to think about what variables you are going to use and of what type they should be. It
closes one of those paths that allow sloppy programming, and you know what sloppy programming
brings? Errors! Let’s have a look at a quick example.

1. Open the ErrorHandling display in FactoryTalk View Studio.

2. Click the Test Display toolbar icon

9 of 40
3. Click the Clear All button to clear the diagnostics list

4. Click the Click To Execute button

Look at the diagnostics list, you should see:

5. Click it a couple of more times:

It is fairly obvious that the code should be listing the current time and then an incrementing number.
The number represents the number of times you have clicked this button from when the display was
opened.
6. Click the Edit Display toolbar icon to look at the VBA code.

10 of 40
7. Right-click the Click To Execute button and select the VBA Code menu item

Here is the code:

You see that error trapping is being used, but we were not seeing errors in the diagnostics list, so
that’s not the problem. Take just a minute to look at the code; do you see what’s wrong?

8. Let’s put “Option Explicit” in the code. Type ‘Option Explicit’ as the first line in the code, Type it after
the header comments.

% To have this automatically added to new displays, under the VBA IDE menu choose Tools >
Options and check Require Variable Declaration.

11 of 40
9. Now return to the FactoryTalk View Studio Display. Click the Test Display toolbar icon again.

You should immediately see the following:

Now do you see the problem?

The variable CurrentTimeNow has been mistyped as CurrentTmeNow. The ‘i’ is missing.
10. So click the OK button and correct the variable.

11. Return to FactoryTalk View Studio and select theTest Display toolbar icon again.

Oh No! Not another problem!

It must have been a bad night before this was coded, as the variable that should be
NumberOfPresses has been coded as NumberOfPreses. There’s an ‘s’ missing.

12. So click the OK button and correct the variable name and let’s try again.

12 of 40
13. Return to FactoryTalk View Studio and select the Test Display toolbar icon

No error this time!

14. Click the Click To Execute button.

Click it a few times. You should get the following in the diagnostics list. (Note: your time will be
different)

So now the code is doing what we expected.

% VBA will try to help you out by automatically creating variables for you and even changing their
type automatically. But letting VBA do this for you leads down that sloppy coding path we don’t want
to tread.

Always use the ‘Option Explicit’ statement. It makes you think about the variables you are going to
use and their type. And it will show you any typos you have made in the code.

M As you saw in the example without ‘Option Explicit’ VBA did not complain about the typos in
the code because it assumed you meant to type names of CurrentTmeNow and NumberOfPreses
and so VBA made new variables for you. Whereas you really intended to type CurrentTimeNow and
NumberOfPresses. The error trapping did not fire because as far as VBA was concerned there was
not error. These typo problems can be very difficult to spot, so always use ‘Option Explicit’.

15. Save the ErrorHanding display but leave it open for the next section.

13 of 40
Displaying Error Messages in the Diagnostics Log
There is a very simple method for you to send specific messages to the Diagnostics List and Diagnostics
Log, to help you debug your errors and notify the operator of problems with VBA code. By writing your
own messages to the Diagnostics Log, not only do you give potentially useful feedback to your operator,
but the messages are viewable and archived with the rest of the system messages.

Minimally you can write any text message that you want to the Diagnostics Log. As you develop your
application with many displays, the more information you add to the message the better. Including the
display name, procedure name and severity level will not only make your messages more meaningful, but
they will also help you troubleshoot your application when something goes wrong.

Using the Application.LogDiagnosticsMessage method

In the previous section explaining the use of Option Explicit, you saw the LogDiagnosticsMessage
method in action.

In the example above, the method is being called to display nothing more than a string defined by you,
the programmer. While this sort of message reporting is fine when you’re just getting started out, it can
ultimately be a lot better.

1. Open the VBA IDE for the ErrorHandling display.

2. Find the procedure cmdShowOptionExplicit_Released().

14 of 40
3. Find the line of code circled above. Add a space after LogDiagnosticMessage to get the field
help display.

Alternately, highlight LogDiagnosticMessage and press the F1 key to open the SE Client Object Model
Help display.

Note that there are two optional


arguments to the method:
- Severity
- Audience

ftDiagSeverityConstants are defined as:


ftDiagSeverityError (1) – the message is an error
ftDiagSeverityWarning (2) – the message is a warning
ftDiagSeverityInfo (4) – the message is informational
ftDiagSeverityAudit (8) – the message describes a change made to the system

ftDiagAudienceConstants are defined as:


ftDiagAudienceRSMACC (1) – the message is intended for RSMACC
ftDiagAudienceDeveloper (2) – the message is intended for technical support
ftDiagAudienceEngineer (4) – the message is intended for control system designers, application
engineers, and administrators
ftDiagAudienceOperator (8) – the message is intended for operators
You can use the severity and audience constants to log the messages not for the operator, but maybe for
the maintenance staff, or the programming staff.

This by itself can be very useful, but you will see in the next section, it can get even better.

15 of 40
Using the SystemLogModule BAS module

When you have a larger application with many screens or many people working on many screens, you
may want to standardize how everyone reports their errors to the system.

The following demonstrates the use of a wrapper module written around the LogDiagnosticMessage
method. The purpose of the wrapper module is to provide a standard way to compile and display error
messages so you don’t end up with generic non-informative messages like this in one area:
LogDiagnosticMessage “Error.”
And good messages like this in other areas:
LogDiagnosticMessage “Display: <filename>, Function: <function name>,
parameter file not found, Error: <error number>, Description: <error
description>, ftDiagSeverityError, ftDiagAudienceEngineer

1. In the VBA IDE for the ErrorHandling display, right-click anywhere in the tree and select the
Import File…

2. When prompted, select the file located at:


C:\Lab Files\Error Handling\System Log Module\SystemLogModule.bas

3. Open the newly imported module called SystemLogModule and observe the code. You will find a
function defined:

This function essentially takes its input parameters, compiles the message, and sends it to the
FactoryTalk Diagnostic Log. The good thing about using a wrapper application such as this, your
messages will be consistent and uniform throughout your application. And the formatting will prevent you

16 of 40
from getting lazy… (no more msgbox “error” lines of code!)

Whereas an error message in your code might currently look like this:
my_string = “popFileSelect:cmdSelectFile. Unable to open file. Error(“ &
Err.Num & ”) Description: “ & Err.Desc
LogDiagnosticMessage my_string, ftDiagSeverityError, ftDiagAudienceOperator

Using the SystemLogModule, the error message would look like this:

WriteSystemLog ftDiagAudienceOperator, ftDiagSeverityError, “popFileSelect”


“cmdSelectFile”, “Unable to open file”, Err.Num, Err.Desc

Where popFileSelect is the name of the display and cmdSelectFile is the name of the active
executing object. It is always recommended to include this information in your error messages!

Tip!

If you sometimes forgetting to add the name of the calling display and the active object as part of your
message, try using Me.Name and Me.ActiveElement.Name instead.

WriteSystemLog ftDiagAudienceOperator, ftDiagSeverityError, Me.Name,


Me.ActiveElement.Name, “Unable to open file”, Err.Num, Err.Desc

You will see SystemLogModule used in some examples in the rest of this lab.

Always remember: it is an error to not correctly and consistently report your errors!

17 of 40
Errors and error trapping

No Error Trapping
The lack of error trapping in VBA code is the number one reason that VBA code can cause problems
within a FactoryTalk View SE application. In this section we are going to investigate the effects of having
no, poor, and good error trapping in a project.

1. Open the ErrorHandling display if you closed it in a previous section.

Calculation Box

The seven Error Trapping buttons on the left side of the screen call VBA procedures that perform
mathematical calculations shown in the calculation box. It’s not being suggested that you should do
simple math like this in VBA, but instead it’s an easy way for us to simulate errors so you can observe
how VBA behaves.

2. Click the Test Display toolbar icon

18 of 40
The display should look like this

Calculation Box

3. Now click the No Error Trapping button.


This button will execute VBA code without any error handling at all.

Wait a few seconds, then the tag values should then show the following:

As you can see, a calculation has been made:


Result = X / Y (i.e a division sum)

All right, not so interesting yet. Let’s try changing a value now to simulate different conditions.

rd
4. Change the divisor in the 3 calculation to zero. And don’t forget to press enter! You know the
value is accepted when the divisor value in the calculation box changes to zero as well.

19 of 40
5. Now again click the No Error Trapping button

You should now see the following:

6. We have a ‘Run Time error 11’. The VBA code has stopped execution. We now have the option to
end the code or go and debug the code, let’s select the Debug button.

You should now see the following:

So what’s going on here? The VBA code is looping around the 5 (0 – 4) calculations, and we have
encountered an error. If you hover the curser over the iLoop variable, you will see we have a count of
2 (third calculation).

20 of 40
So we have a division by 0, which is an illegal calculation and hence an error.
Now you might be thinking, well that’s pretty obvious that you should use error trapping, and you
would be right; yet a lot of VBA programmers do not use it!

% As stated before, it’s not suggested that you do simple math like this in VBA, but doing this
calculation here to make two important points:

VBA routines without error trapping might run fine some of the time, but there can be circumstances
when something changes (in our case a tag value being zero) and the code stops running. Hence not
doing what the operator expects and not controlling the process correctly.

If the VBA code has an error it stops running at that point (in our example the third time around the
loop). So the thing to note here - is that the third, fourth and fifth calculations are not performed, but
the first and second are.

M So the code is exiting in an incorrect and unknown state!

7. Click the Reset toolbar icon in the VBA IDE window

21 of 40
Manual Error Handling
So we have seen that no error trapping is a bad idea. So you might think what about testing for a zero
before I try the calculation? OK so let’s try that now.

1. Go back to FactoryTalk View Studio

2. Click the Test Display toolbar icon

3. From the Diagnostics list click the Clear All button

rd
4. Change the divisor in the 3 calculation to -7 and press enter. You know the value is accepted
when the divisor value in the calculation box changes to zero as well.

5. Click the Test Before Trying button. This is the code that checks for bad values manually before
executing the calculation.

6. Now this time we did not get an error; but look in the diagnostics list, you should see an entry like this:

7. Click the Clear All button

8. So the VBA code did not encounter the error because we tested for the values before trying the
calculation. Let’s have a look at this, Click the Edit Display toolbar icon.

22 of 40
9. Right-click the Test Before Trying button, and then select the VBA Code menu item

10. Here you see the test for the negative value in the divisor

So that’s great we have stopped the error occurring and all is good with the world, or is it?

11. Click the Test Display toolbar icon

rd
12. Change the divisor in the 3 calculation to 0 and press enter. You know the value is accepted
when the divisor value in the calculation box changes to zero as well.

13. Click the Test Before Trying button.

14. What you should see now in the Diagnostic Display is:

23 of 40
14. Go to the Visual Basic IDE and select Debug from the error dialog

You see the highlighted line

The reason you got an error here is because we are trying to divide by zero. The defined tag is an
HMI tag with a limit of 0 – 10000. The test for a negative number helped for the range check but it
didn’t help us here. Let’s step over this error.

15. Right-click, the line underneath the one that cause the error, and select the Set Next Statement
menu item

Right-click
This Line

16. Press F5 to continue execution.

% So the thing to note here is; it’s good to think about what errors might occur in a section of
code, but can you be sure you have thought of everything and can you test for everything?

M Failing to think of all possible errors that could occur will eventually cause you problems. For
example, it could be problem to exit the code in an unknown state.

24 of 40
“On Error Resume Next” Error Handling
So it is good to think about errors that could occur in your code, but it also may be very difficult to think of
everything that could go wrong. So now let’s investigate trapping VBA errors and look at the
consequences of each method.

rd
1. Go back to the screen and change the divisor in the 3 calculation to -7 and press enter. You know
the value is accepted when the divisor value in the calculation box changes to zero as well.

2. Click the Clear All in the diagnostic list, just so we are not confused by earlier messages.

3. Click the Simple But Risky Error Trapping button

4. You should see the following line appear in the diagnostics list:

So the VBA code has run and not crashed on us this time. We have logged the errors into the
diagnostics list. Let’s see how this was done, and see if it is the answer to our problems.

5. Click the Edit Display toolbar icon

25 of 40
6. Right-click the Simple But Risky Error Trapping button.

7. You should now be looking at the code: This is the


line we are
interested in

So here we are saying if an error occurs, ignore it and just continue with the next line of code. So the
thing to think about here is; that if an error occurs it will not stop the VBA code, but will just blindly
continue running the code after the line where the error occurred. Now there may be a time when that
is not really a problem; however there are many circumstances when it does matter. If lines of code
depend on the lines of code previous to them; your code will produce invalid results.

% The use of the ‘On Error Resume Next’ is used a lot by programmers who do not want the VBA
code to crash, but also do not want to think too much about what the code will do if an error occurs.
Only use where lines of code do not depend on the previous lines of code, i.e not very often.

M The use of the ‘On Error Resume Next’ can lead to exiting the code in an unknown state, and
potentially the code not doing what it was supposed to do, and no log of the problem being produced.
Problems like this can go undetected for a long time, with engineering effort being spent looking at
other reasons for the system not operating correctly.
8. Now look at this line. We will be using this statement repeatedly in the further examples.

This is the
line we are
interested in

% There was an important line of code introduced here; it is the line that reported the tag name in
error to us. The LogDiagnosticMessage statement is part of the FactoryTalk View SE
implementation, it allows us to log messages into the ‘diagnostic List’ just as FactoryTalk View SE
does it’s self. This is an invaluable aid to us in fault finding during and after the fact.

26 of 40
On Error GoTo/Resume Error Handling
We are now going to investigate the ‘On error Goto’ Statement. This is a way of telling VBA that if an error
occurs then go to a specific line of code so we can decide what to do about it. However this statement
can be used very effectively or it can cause all sorts of trouble. Let’s look at a bad use of this statement.

1. Click the Test Display toolbar icon

rd
2. Change the divisor in the 3 calculation to 7 and press enter. You know the value is accepted
when the divisor value in the calculation box changes to zero as well.

3. Click the Clear All in the diagnostic list, just so we are not confused by earlier messages.

4. Click the Error Trap With Resume Button.

You should find no problems so far, calculations work OK.

rd
5. Change the divisor in the 3 calculation to 0 and press enter. You know the value is accepted
when the divisor value in the calculation box changes to zero as well.

6. Click the Error Trap With Resume Button.

27 of 40
Now look in the diagnostics list, what you should be seeing is a division by zero error being generated
in a continuous loop!

7. Try clicking some of the buttons you used before. Does anything happen? No, the code is in a loop,
and that’s what it is going to do, nothing else.

8. Try clicking the Zero Results button (wait several seconds), does that work?
(Result Values Change To Zero).

Yes this works, this is because the tag values are being zeroed with a FactoryTalk View SE macro.

% FactoryTalk View SE components (i.e., displays, macro’s, event files, derived tag files, etc) run
independently of the VBA code. If you can do something natively in FactoryTalk View SE, that’s the
best place to do it.

9. OK, but we are still stuck in the loop, so let’s try clicking the Edit Display toolbar icon.

Does that help? No!

28 of 40
10. The way to stop this is to hit the ‘Control Ctrl’ key and the ‘Pause | Break’ key together.
You should now see:

If not click Microsoft VisualBasic in the toolbat, then you will see it

11. Click Debug

1. Here is the line that says, If an


error occurs then go to label
(errTrap1)

2. Here is the line causing the error


(divide by zero). So the code
execution jumps to errTrap1 (see 3
below)

3. Now here we log the error to the


diagnostic list and then RESUME,
i.e return to the line that caused
the error in the first place. Now
code execution returns to where it
was (see 2 above)………. Loop

29 of 40
% The use of the 'On Error Resume Next' can lead to the existing code being in an unknown
state, the code potentially not doing what it was supposed to do, and no log of the problem being
produced. Some times it is valid to return to a line and try again, but the number of times should be
controlled by the VBA programmer.

M Now imagine that the LogDiagnosticsMessage was not in the error routine. There would be no
visual indication that anything was wrong. The Operator would complain that the system was
unresponsive and the station would probably be rebooted. Maybe the error would occur again and
maybe not, depending on if the condition causing the error had gone away (in our case if the value
was not zero anymore). Hence giving an unreliable system with unpredictable crashes.

12. Let’s tidy up to get ready for the next section:


Click the Reset button in Microsoft Visual Basic

13. Return to FactoryTalk View Studio. Click the Clear All button in the diagnostics list.

30 of 40
On Error GoTo/Resume Next Error Handling

1. Click the Test Display toolbar icon

2. Click the Zero Results button

rd
3. Change the divisor in the 3 calculation to 0 and press enter. You know the value is accepted
when the divisor value in the calculation box changes to zero as well.

4. Click the Error Trap With Resume Next button

5. You should see the following results:

So the code did not crash, we calculated the values that we could, and reported the error message.
So that’s all very good, but let’s look at the code and think about something.

6. Click the Edit Display toolbar icon

31 of 40
7. Right-click the Error Trap With Resume Next button and select the VBA code.

8. You should be looking at the following code:

The only difference


between this code and
the previous example is
‘Resume Next’ rather
than just ‘Resume’ at the
end of the error trap
routine.

So here we are not going to get the same problem as the previous example, because we are
‘Resuming Next’ line not just ‘Resuming’ on the line that gave us problems. You may be wondering
what the difference is between this example on the one we looked at in Step 1 of the “On Error
Resume Next” error handling (The Bad). Well the result is exactly the same, except the mechanism is
different. In the example in “On Error Resume Next” error handling (The Bad) Step 1, the code
execution would continue immediately on the next line. Here we jump to an error routine and then do
something and then return back. It is this that we will investigate in a little while.

% We are returning to a line of code below the one that caused the error, but is it good to do that
always? Maybe not!

32 of 40
On Error GoTo Error Handling
Let’s do one last example of error trapping before discussing a solution to all of this.

1. Return to FactoryTalk View Studio. Click the Clear All’ in the diagnostics list.

2. Click the Test Display toolbar icon

3. Click the Zero Results button

rd
4. Change the divisor in the 3 calculation to 0 and press enter. You know the value is accepted
when the divisor value in the calculation box changes to zero as well.

5. Click the Error Trap And Dump button.

You should now see:

So what has happened here? In the previous example we had results for all but the value in error.
Let’s have a look at the code.

33 of 40
6. Click the Edit Display toolbar icon

7. Right-click the Error Trap And Dump button, select the VBA code.

You should see:

Same code example, but


this time there is no
‘Resume’ or ‘Resume Next’.

34 of 40
So here, we get the same error as before, but this time we don’t resume into the code we just finish
the routine. This is the reason none of the values get updated, because we do not execute the
gpGroup.WritePendingValues line, i.e. write the tag values.

% In this case we get an error, jump into the error handler, and stop executing at this point in the
code. Using this method, we are not in danger of executing further lines of code in an unknown state.
However, halting code execution could also be an undesirable behavior; since in this case we are
only calculating 4 out of the 5 values

Sorry if all of the above has been confusing, but you had to see all the different ways to trap errors in
VBA, and what can happen when used – or more importantly – misused. In sophisticated applications,
the situation is more complex because the error handling can be very large, complex pieces of code in
itself. The decision of Resuming, Resuming Next, Stopping Code or returning to a different line can cause
all sorts of problems that usually get blamed on the SE product, not on the VBA code. It’s also possible
that code can run well most of the time and then a situation occurs that causes the code to fail.

Now let’s look at a solution for all of this.

« « « « « On Error GoTo with WatchForErrors Error Handling « « « « «

1. Go back to FactoryTalk View Studio and click the Clear All button in the diagnostics list.

2. Click the Test Display toolbar icon

3. Click the Zero Results button

rd
4. Change the divisor in the 3 calculation to 0 and press enter. You know the value is accepted
when the divisor value in the calculation box changes to zero as well.

35 of 40
5. Click the Error Trap A Better Way

you should see the following:

So we have calculated all values apart from the one in error. And we have logged the following errors:

OK let’s look at the code:

6. Click the Edit Display toolbar icon

7. Right-click the Error Trap A Better Way button and select the VBA code button

You should see the following: It’s a bit small; it will be expanded on the next pages.

36 of 40
8. The body of this code is identical to the previous examples, but here we have an expanded error
handling routine and a very simple technique to help distinguish errors.

Here you see we have defined a local variable ‘WatchForError’, it could be called anything, it’s just a
local variable.

37 of 40
9. Now have a look in the body of the code and see how this local variable is used.

So what we are doing here is, before each section of code where errors could occur, we allocate a
number, the number is purely of our choosing.

38 of 40
10. Now if an error occurs the code execution will jump to the error handling
routine: Here is our variable. Now we
can decide what to do if we get
an error, depending on which
section it occurred in we can
take different actions.

So looking at the example above, iIf the value in our WatchForError was a:
§ Zero 0
We know that the next lines of code are defining variable/objects etc. So we log an error that it is not
safe to continue with the code because if objects/variables are not defined we cannot continue
without generating errors.
§ One 1
We know we are about to carry out some calculations. We also know if a calculation fails we can
continue to calculate the other values because the calculations in this case do not depend on the
ones before. However if the subsequent calculations do depend on the one before then we should not
continue. In this case we ‘Resume Next’. Note we also log exactly what the error was and in which
index of the loop we were in when the error occurred.
§ Two 2
We know we are writing tag values and that there could be a number of reasons why the tag write
could fail. We think to retry the code again, but want to avoid getting into an infinite loop scenario. To
avoid this, we introduced a counter to let us only try this 3 times before going into error.
§ Three 3
Here we have an error reported in the write section. Now I have chosen here not to retry, but I could
equally have chosen to retry a number of times as in the two above.

39 of 40
% This is not the best or absolute way to error trap in your code, but if error trapping like this was
used in all routines it would reduce the risk of problems. Using a value like WatchForError is a simple
technique to isolate and decide what to do about errors that occur. At minimum, remember to at least
log the error so that you can see what happened in your code. Also take a look at the Microsoft site
for further information on error trapping in VBA. Here is the reference site again, mentioned earlier in
this section of the lab:
http://support.microsoft.com/kb/146864

M Just a word of warning here: Keep the error handling code simple!
If you get an error in the error handling code – another error handler will not handle that for you.
Code execution will stop!

- Think about what errors might occur in your code.

- Think about what to do about them.

- Think about what you want to do for errors you have not thought about.

- Keep error handling code simple.

9. Close the ErrorHandling dispaly. We are finished with this section!


J

% Tips

- You should always use the “IsError” function with numeric displays. The value could be in error
because of a communication problem, the tag does not exist in the controller, or the tag has no
value yet.

- To interrupt code execution is to hit the ‘Control Ctrl’ key and the ‘Pause | Break’ key together.

40 of 40

You might also like