[go: up one dir, main page]

100% found this document useful (2 votes)
4K views100 pages

FTView SE VBA PDF

Uploaded by

Daniel Ruiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
4K views100 pages

FTView SE VBA PDF

Uploaded by

Daniel Ruiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

CoTMS68 - Extending FactoryTalk View Site

Edition Solutions with VBA Code

For Classroom Use Only!


Important User Information
This documentation, whether, illustrative, printed, “online” or electronic (hereinafter “Documentation”) is intended for use only as
a learning aid when using Rockwell Automation approved demonstration hardware, software and firmware. The Documentation
should only be used as a learning tool by qualified professionals.

The variety of uses for the hardware, software and firmware (hereinafter “Products”) described in this Documentation, mandates
that those responsible for the application and use of those Products must satisfy themselves that all necessary steps have been
taken to ensure that each application and actual use meets all performance and safety requirements, including any applicable
laws, regulations, codes and standards in addition to any applicable technical documents.

In no event will Rockwell Automation, Inc., or any of its affiliate or subsidiary companies (hereinafter “Rockwell Automation”) be
responsible or liable for any indirect or consequential damages resulting from the use or application of the Products described in
this Documentation. Rockwell Automation does not assume responsibility or liability for damages of any kind based on the
alleged use of, or reliance on, this Documentation.

No patent liability is assumed by Rockwell Automation with respect to use of information, circuits, equipment, or software
described in the Documentation.

Except as specifically agreed in writing as part of a maintenance or support contract, equipment users are responsible for:
• properly using, calibrating, operating, monitoring and maintaining all Products consistent with all Rockwell Automation
or third-party provided instructions, warnings, recommendations and documentation;
• ensuring that only properly trained personnel use, operate and maintain the Products at all times;
• staying informed of all Product updates and alerts and implementing all updates and fixes; and
• all other factors affecting the Products that are outside of the direct control of Rockwell Automation.

Reproduction of the contents of the Documentation, in whole or in part, without written permission of Rockwell Automation is
prohibited.

Throughout this manual we use the following notes to make you aware of safety considerations:

Identifies information about practices or circumstances


that can cause an explosion in a hazardous environment,
which may lead to personal injury or death, property damage, or economic loss.

Identifies information that is critical for successful application and understanding of the product.

Identifies information about practices or circumstances that can lead to personal injury or death, property
damage, or economic loss. Attentions help you:
• identify a hazard
• avoid a hazard
• recognize the consequence

Labels may be located on or inside the drive to alert people that dangerous voltage may be present.

Labels may be located on or inside the drive to alert people that surfaces may be dangerous temperatures.
CoTMS68 – Extending FactoryTalk View Site Edition Solutions With VBA Code

Contents
Before you begin ........................................................................................................................................... 5
General ............................................................................................................................................................................................. 5
SoftLogix ........................................................................................................................................................................................... 5
FTViewSE ......................................................................................................................................................................................... 5
RSLinx .............................................................................................................................................................................................. 5
About this lab .................................................................................................................................................................................... 5
Tools & prerequisites ........................................................................................................................................................................ 6

Getting Started .............................................................................................................................................. 7


Opening the project file. .................................................................................................................................................................... 7

Error trapping: ............................................................................................................................................... 9


No error trapping: ............................................................................................................................................................................ 11
Test Before Trying .......................................................................................................................................................................... 14
Simple But Risky Error Trapping: Resume Next ............................................................................................................................. 19
Error Trap (Error Handler) With Resume ........................................................................................................................................ 22
Error Trap (Error Handler) With Resume Next ................................................................................................................................ 26
Error Trap (Error Handler) No Resume, just stop .......................................................................................................................... 28
Error Trapping and Error Handling the best way ............................................................................................................................ 30
Easy Fixes: Option Explicit ............................................................................................................................................................. 36
Comments....................................................................................................................................................................................... 40

Long VBA execution times: Techniques and information. .......................................................................... 41


Set-up ready for section. ................................................................................................................................................................. 41
Blocking Operator Interaction ......................................................................................................................................................... 45
Queuing VBA Events: ..................................................................................................................................................................... 50
DoEvents ........................................................................................................................................................................................ 53

Events ......................................................................................................................................................... 65
Inside the Event Loop ..................................................................................................................................................................... 71
MesageBox ..................................................................................................................................................................................... 72

3 of 100
Tag Creation, destruction and Writing. ....................................................................................................... 77

Invoking an ActiveX ..................................................................................................................................... 84

4 of 100
Before you begin

These steps only need to be completed if not using the VMWare image for VZ09.

General
 Ensure that the required files are installed in the correct path (see below).

SoftLogix
 Install a SoftLogix 5800 processor in slot 3 of the virtual chassis. Configured to: No Auto Save, 100ms dwell time, Remember
Last State.
 Download the ACD file ‘FTViewSE_VBA.acd’ into the SoftLogix 5800 Controller. Put the Controller in to Run Mode

FTViewSE
 Restore the FTViewSE archive file, FTViewSE_VBA_MAIN.apa and give it name application name FTViewSE_VBA

RSLinx
 RSLinx Classic is only used to enable download of acd file to SoftLogix 5800 and Studio 5000 data monitoring.
 RSLinx Enterprise is used by FactoryTalk View SE. Ensure the shortcut (called FTView_SC) in RSLinx Enterprise is
‘pointing’ to the SoftLogix 5800 controller in slot 2 via Virtual BackPlane driver 1789-A17 Backplane.
NOTE: If using a hard controller ‘point’ the shortcut to that controller via the appropriate driver. And convert the ACD to the
appropriate processor.

About this lab


The ability to add ‘Visual Basic for Applications’ (VBA) code to FactoryTalk View SE offers great versatility in achieving your user
requirements. VBA is a scripting language; hence care must be taken to not only to write code to deliver the required functionality
but also to ensure robust and reliable code suitable for use in industrial automation applications. This lab will give practical
guidance and examples on avoiding problems and promoting robust and reliable code generation.
This lab defines Reliability and Robustness of VBA code thus:
Reliability: Is producing VBA code that (within the bounds of normal operation) will execute with a predictable and repeatable
behavior.
Robustness: Is producing VBA code that will not allow an unrecoverable condition to occur which prevents further execution of
VBA code.
You will not be required to write any significant VBA code in this lab, merely investigate the effects of code changes already
written for you. It is not the intention of this lab to teach VBA programming, or the FactoryTalk View SE object model, merely to
communicate the common issues that can cause problems when writing VBA code.
This lab has been produced in response to investigating numerous FactoryTalk View SE projects where the VBA code was
finally identified as the root cause of the reported issues. The investigations also identified that the ‘same code suspects’ are
encountered repeatedly. It is these issues that the lab addresses. The lab cannot cover all possible problems that can be
encountered, but by focusing on the top few, the user can move a long way towards achieving reliable and robust VBA code.

5 of 100
You will cover five main subjects in the lab:
 Error Trapping: options and consequences.
 Simple measures to avoid issues
 Large (long) VBA code routines.
 Events.
 Speed of execution

When there is an important point or note I want to draw your attention to, you will see the ‘hand’  symbol.
When you see the ‘flag’ symbol  it means that the point in discussion has a serious potential to cause problems within the
FactoryTalk View SE Application, for example infinite loops or exiting VBA code in an unknown state.

Just a note to say; whilst this lab is highlighting issues that can be caused by ‘poor’ VBA code it is important to remember that
it’s not all bad news , a small amount of ‘good’ VBA is fine to increase functionality and gives great versatility to enhance your
FactoryTalk View SE applications.

This lab takes approximately 90 minutes to complete.

Tools & prerequisites

Software Required:
 RSLogix 5000, V21.00.00
 FactoryTalk View Studio, V8.0
 SoftLogix, V21 (or physical processor)
 RSLinx Classic V3.6
 RSLinx Enterprise V5.6

Path Required:
 C:\Lab Files\VZ09\

Files Required:
 C:\Lab Files\VZ09\CSV\ FTViewSE_VBAData.CSV
 C:\Lab Files\VZ09\Logix\ FTViewSE_VBA.ACD
 Restored FTViewSE_VBA_MAIN.apa file for FTViewSE_VBA stand-alone project (C:\Lab Files\VZ09\APA)
 C:\Lab Files\VZ09\SampleFiles\ TestText.txt, RSTE-2104.pdf, RA_Small.jpg, CLxPerf.htm and dir CLxPerf_files

Prerequisites:
 Be familiar with FactoryTalk View SE.
 Be familiar with VBA IDE (Integrated Development Environment) environment and VBA coding.
 Be familiar with FactoryTalk View SE client object model.

6 of 100
Getting Started

Opening the project file.

1. Start FactoryTalk View Studio by double clicking the icon on the desktop

2. Click View Site Edition (Local Station) then click Continue

7 of 100
3. Select FTViewSE_VBA, click Open.

Wait for the project to fully open indicated by the Explorer window being fully populated.

.4. After the project opens maximise FactoryTalk View Studio

5. Expand the ‘displays’ to show configured displays

After Expansion

6. You are now ready to start the lab, continue with next section.

8 of 100
Error trapping:

Error trapping in VBA code is extremely important. No error trapping or poor error trapping is the number one reason to have
instability in code and hence in the FactoryTalk View SE application. As we want to ensure reliable and robust code for use in
industrial applications it is important to take the time and make the effort to ensure the correct level of error trapping is
implemented in an application.
These are the methods we will review in this section.
 No Error trapping: Code runs, and no action is taken when an error occurs.
 Testing before execute: Test or check for any possible errors before executing code.
 On Error Resume next: If an error occur on a line of code skip the line and continue with the next.
 On Error Goto – with Resume: If an error occurs on a line of code, trap it, do something, then return to original line of
code that cause the error.
 On Error Goto – with resume Next: If an error occurs on a line of code, trap it, do something, then return to the line of
code after the one that cause the error.
 On Error Goto: If an error occurs on a line of code, trap it, do something, then stop running the code.
 On Error Goto – Tracking code execution progression and change error response depending on position.

1. Double Click the display name Error_trapping to open it.

9 of 100
2. Click the Test Display tool bar icon.

The display will look like this:

Each of these buttons has some VBA code associated with it to show the different techniques. We are going to use the grid of
numbers purely to assist in evaluation of the different methods.

 This section of the lab will walk you through exercises of the different levels of error trapping, from no error trapping to the
best error trapping solution. If you only want to see the best way to error trap you can go to page 30 (Error Trapping And Error
Handling The Best Way) and skip the rest of the section. However if you do skip ahead you will miss out on a lot of important
information about why it’s the best solution. Missing the experience of what and how things can go wrong if the best solution is
not applied.

Still with me? Excellent then let’s get started.

10 of 100
No error trapping:
So I think we both know that this is not going to end well.

2. Click the ‘No Error Trapping’ button.

Wait a few seconds and the tag values will show the following values:

As you can see, multiple calculations have been made:


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

All right, well not so interesting yet. Let’s try changing one of the values to simulate a slightly different condition.

4. First click the ‘Zero Results’ button, Wait a few seconds until all the results are zero (0).

Now Change the divisor in the 3rd calculation to zero (0). Don’t forget to press ‘Enter’ on the keyboard to write the value.
You know it’s changed when the divisor in the list also changes to zero.

11 of 100
5. Now again Click the ‘No Error Trapping’ button.

You will see the following:

6. This time we have a Microsoft Visual Basic ‘Run-time error ‘11’’ This indicates the VBA code has stopped execution. If this
occurred in the FactoryTalk View SE client that would be the end of the VBA code running. However as we are in studio we
have the option to select ‘debug’ to see what went wrong.

  It is possible to enable debug mode in a FactoryTalk View SE client. But this is only recommended in
the commissioning stage not in a production system.

So let’s do that now click Debug.

You will see the following:

12 of 100
7. So whats going on here? The VBA code is looping around 5 calcualtions (iloop 0 to 4). In this loop an error has occurred
and stopped code execeution. Hover the mouse pointer over the iLoop variable.

You will see that a value of 2 is displayed which is the third calculation (0,1,2,3,4)

That’s the calculation you modified the value of, from 7.00 to 0.00.

So the problem is that a division by 0 has occurred 30 / 0 , which is an illegal calculation, hence the error in the diagnostic log.

I am not suggesting that you would do simple calculations like this in VBA (you would probably use a derived tag file). Don’t
focus on the fact it was a divide by zero error. It could have been any error condition; for example hard drive full, database record
locked, bad tag value or missing objects. I am using this simple example code to help me make three 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, so not doing what
the operator expects and not controlling the process.

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

 The code is terminating in an incomplete and unknown state, because there is no error trapping
implemented. Not Reliable or Robust code.

8. Click Reset in the VBA IDE window

13 of 100
9. Click FactoryTalk View Studio icon in the bottom windows toolbar or alt-tab to FactoryTalk View

Click Test Display - now ready for next section.

Test Before Trying

10. So we have seen that no error trapping is a very bad idea. So you might think what about testing for a zero before trying the
calculation. Remember this is just an example – it could be testing for drive full, database connected etc. It is the principle
that is more important.

Before we continue - make the diagnostics windows larger so you can see several lines. Do this by hovering the mouse
curser over the line shown, until you see the arrow turn to the expand curser, when it does, click and drag the window
higher.
From this:

To this more larger diagnostic list window

11. Click ‘Clear All’

12. Click ‘Test Before Trying’ button

14 of 100
13. Now this time we did not get an error, but look in the diagnostics list, you will see an entry like this.

The VBA code did not get an error because this time we tested for a zero (0) in the code and prevented the calculation and
hence the error.
You will also see that the 3rd calculation in the results list is still at zero (0.00)

14. Let’s have a look at this code. Click the ‘Edit Display’ toolbar icon in FactoryTalk Studio.

15. Right Click the ‘Test Before Trying’ button, and then select VBA Code

16. Here you see the test for the zero value in the divisor. Don’t worry about the detail of the code. But notice the
LogDiagnosticMessage line.

15 of 100
 There was an important line of code introduced here; it is the line that reported the tag name in error to
us:

The LogDiagnosticMessage instruction is part of the FactoryTalk View SE Client object model; it allows us to
log messages into the ‘diagnostic List’ just as the FactoryTalk View SE does itself. This is an invaluable aid
to us in fault finding during and after the fact. We will be using this instruction repeatedly in the further
examples

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

17. Return to FactoryTalk View Studio and click Test Display icon in the toolbar

Change the divisor in the 3rd calculation to minus 7 (-7). Don’t forget to press ‘Enter’ on the keyboard to write the value.
You know it’s changed when the divisor in the list also changes to -7.

Now click the ‘Zero Results’ button, Wait a few seconds until all the results are zero (0).

Now Click the ‘Test Before Trying’ button

16 of 100
18. What you will see now in the Diagnostic Display is:

(Note: if the VBA IDE was not left open from the last section you will see the runtime error box as in step 20)
Only calcualtion 1 and 2 have been executed:

19. Click the Visual Basic IDE icon in the windows tool bar.

20. You will see the Run-time error box. Click the Debug button.

You see the highlighted line in the code.

17 of 100
The reason you got an error here is because the defined tag is an HMI tag with a limit of 0 to 10000. We are trying to write a
negative number (30 / -7 = -4.28) but it is out of range and the VBA code has terminated in an error.

  So the thing to note here is, it’s very good to think about what errors might occur in a section of code,
and try to prevent an error from occurring. But can you be sure you have thought of everything? Can you test
for everything?

  Testing is not a substitution for error trapping, but is good practice towards the ultimate goal of writing
robust and reliable VBA code.

 The code is terminating in an incomplete and unknown state, because there is no error trapping
implemented. Not Reliable or Robust code.

21. Click Reset in the VBA IDE window

22. Click FactoryTalk View Studio icon in the bottom windows toolbar or alt-tab to FactoryTalk View Studio, ready for the next
section.

Click Test Display - to get ready for next lab section.

18 of 100
Simple But Risky Error Trapping: Resume Next

So can we agree that not trapping errors, even when including testing for possible errors, is not a good idea when we want to
write reliable and robust code? I think we can, and so we must implement some error trapping.
But there are several options, which one should you use? The following sections will take you through each type of error
trapping, and I hope to persuade you that in the end there is really only one choice and technique when it comes to writing
reliable and robust VBA code. But first let’s look at the resume Next method.

23. First click the ‘Zero Results’ button, Wait a few seconds until all the results are zero (0).

Now click ‘Clear All’ in the diagnostic list, just so we are not confused by earlier diagnostic messages.

24. Leave the -7 in the divisors. Click the ‘Simple But Risky Error Trapping’ button

25. You will see the following diagnostic messages appear in the diagnostics list:

19 of 100
You will also see that the 3rd calculation in the results list has not worked and the result is still at zero (0.00)

So the VBA code has run and there is obviously a problem, BUT the VBA has not stopped on an error as in the previous
section. The problem has been logged into the diagnostic list. Let’s see how this was done, and see if it is the answer to our
problems, ie logging problems but not ‘crashing’ the VBA code.

26. Click ‘Edit Display’ icon in the toolbar

27. Right Click the ‘Simple But Risky Error Trapping’ button.

40. Note this time – no debug message box as before, which, means the code did not terminate unexpectedly. You will
now be looking at the code which is the same as the code in the previous section, except for the addition of the line:
‘On Error Resume Next’:

20 of 100
What is the On Error Resume Next instruction doing? It tells the VBA, if a line of code generates an error ignore it and just
continue with the next line of code.
So the thing to think about here is; If an error occurs it will not stop the VBA code, ok good, so far. But it will just jump to the
line after where the error occurred and continue running from there. Now is that a good thing or not?
Well there may be times when that is not really a problem. However remember we want to write reliable and robust code.
Just ignoring an error does not sound like we will achieve that. In addition since the code is executed sequentially it may be
that ignoring an error, will set us up for a whole load more errors. For example an error could be, ‘no database connection’
and now we are trying to access the database, which is not connected, so accessing the database instructions would fail.

  The use of the ‘On Error Resume Next’ is used a lot by programmers who want a quick fix to prevent the
VBA code from crashing, but do not want to think too much about what the code will do if an error occurs.
 Only use this where lines of code do not depend on the previous lines of code, or the consequence of an
error is unimportant. In other words don’t use it.

  In this case we did get an error message (from FactoryTalk View SE, not the VBA) but depending on
the error type this is not always the case. Problems like this can go undetected for a long time; many hours
can be spent looking for the issues. Whilst this is going on what is happening in the factory to production and
quality of product?

 The code is terminating in an incomplete and unknown state, because there is no error trapping
implemented. Not Reliable or Robust code.

 When it comes to writing reliable code, ‘On Error Resume Next’ is not your buddy!

  If you are investigating an issue and see the use of ‘On Error Resume Next’, a quick fault finding tip is to
remove (or comment out) the line, this can then highlight if the VBA code is in fact giving errors by allowing t

21 of 100
Error Trap (Error Handler) With Resume
We are now going to investigate the ‘On error Goto’ error trapping Instruction. This is a way to tell the VBA that if an error
occurs, go to a label in the code and continue executing the code below the label. This is useful because we could write VBA
code to do something in response to an error occurring i.e. error handling. As part of that error handling code we may wish to
return back to the main routine, but how do that? Well the resume instruction will jump back to where the error occurred in the
code. Ok, so let’s investigate this.

28. Return To FactoryTalk View Studio and if not in test mode Click Test Display

29. Click the ‘Zero Results’ button, Wait a few seconds until all the results are zero (0).

22 of 100
30. Now Change the divisor in the 3rd calculation to zero (0). Don’t forget to press ‘Enter’ on the keyboard to write the value.
You know it’s changed when the divisor in the list also changes to zero.

31. Click the ‘Error Trap With Resume’ button.

Ok – well that does not look good! See the diagnostics list! What you will be seeing is a division by zero error being
generated multiple times and it does not look like stopping any time soon.

32. Try clicking the three buttons you used before. Does anything else happen?

No! Looks like the code is in a loop and nothing is going to interrupt it.
.

 The VBA code is single threaded. That’s a way to say it can only do one code routine at any one time. So that’s
why it’s ignoring the other buttons, until we can stop the continuous loop in the VBA code.

23 of 100
33. Oh – but let’s just try the zero results button – click the Zero Results button now. .Does that work? (i.e. the Result Values
Change To Zero)

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

 FactoryTalk View SE components: commands, displays, macro’s, event files, derived tag files etc., run
independently of the VBA code. Top tip - If you can do something natively in FactoryTalk View SE, that’s the best
place to do it. Not in VBA.

34. OK, interesting - but we still stuck in the loop! So let’s try clicking the edit display button. That’s bound to help, right?

Did it help? No! So even though we have stopped running the display the VBA code is still stuck in a loop and it’s not
stopping. You will not even be able to close the display; don’t try that just yet though as it will stop you following the next
steps.

35. Right! Time to show it who the boss is. On the keyboard press at the same time the keys ‘Control Ctrl’ key and the
‘Pause|Break’ key. Once should be enough, if not try again.

You will now see:

If you do not see the box click the VBA IDE, then you will see it.

24 of 100
36. Click Debug, and you will see this code 1. Here is the line that says, If an
error occurs then go to this label
(errTrap1)

2. Here is the line causing the error


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

3. Here the error is logged to the


diagnostic list and then RESUME,
i.e return to the line that caused
the error in the first place. And the
error occurs immediately
again……….A Loop

  The use of the ‘resume’ has to be controlled very carefully. Returning to a line which is causing an error
can result in an infinite loop. Sometimes it is valid to return to a line and try again, but the number of times to
try has to be controlled by the programmer in the error handler routine.

  Now what if: We had not logged a message into the diagnostic list, there would be no visual indication
that anything was wrong. The Operator would complain that the system was unresponsive (locked up) and
the PC would probably be rebooted. Maybe the error would occur again immediately and maybe not, it would
depend on if the condition causing the error was still present or not.

  The code is terminating in an incomplete and unknown state, because there is no good error
trapping implemented. Not Reliable or Robust code.

37. Click ‘Reset’ in Microsoft Visual Basic

25 of 100
Error Trap (Error Handler) With Resume Next

We looked in the previous section at the use of the Resume instruction in an error handler, to return the execution to the main
routine where the error was encountered. So now we will look at another instruction - Resume Next.

38. Return To FactoryTalk View Studio

39. Click ‘Test Display’ icon in the toolbar. Then Click ‘zero Results’ button

40. Click ‘Clear All’ in the diagnostics list.

41. Click the ‘Error Trap With Resume Next’ button

42. You will 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 very good, but
let’s look at the code and think about something.

26 of 100
43. Click the edit display button

44. Right click the ‘Error Trap With Resume Next’ button and select VBA code.

45. You will 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 handler
routine.

This is better as we did not get the continuous loop of code as before. This is because we used ‘Resume Next’ which returned
control to the line of code after the one that caused the error. You may be wondering what the difference is between this example
and the one we looked at in a previous section (On Error Resume Next)? Well the result is exactly the same, except the
mechanism is different. In the previous ‘On Error Resume Next’ example, the code execution would continue immediately on to
the next line of code. Here we jump to an error routine (error handler) and then do something (log the error) and then return to
the main routine.

Again you see the third calculation has not been completed, but we have completed the ones that could be completed. So we
have seen we can go back to the line that caused the error (resume) or the line after the line that caused the error (resume next).
But what about doing nothing? Let’s look at that now.

27 of 100
Error Trap (Error Handler) No Resume, just stop

We looked in the previous section at the use of the Resume Next instruction in an error handler, which returned to the main
routine on the line after the one that cause the error. So now we will look at the alternate of not returning to the main routine.

46. Return to FactoryTalk View Studio

47. Click ‘Test Display’ icon in the toolbar. Then Click ‘zero Results’ button

48. Click ‘Clear All’ in the diagnostics list.

49. Then click the ‘Error Trap And Dump’ button.

You will see:

So what has happened here? In the previous example we had results for all but the 3rd calculation. Now we only have the
first two calculations.

28 of 100
50. Click the ‘Edit Display’ button

51. Right Click the ‘Error Trap And Dump’ button, select VBA code.

You will see:

Same code example, but


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

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 after the error get updated.
We jumped to the error handler and stopped executing at the end of the error handler. So we are not in danger of executing
further lines of code in an unknown state. However maybe the fact we are not executing some code when we could is a bad
thing also, ie we could have calculated 4 out of the five values.

29 of 100
Error Trapping and Error Handling the best way
(In my opinion, see what you think)
I hope you did not find the pervious sections too tedious; the intention was to introduce ideas that we can use to think about
getting us to a solution for a good and controlled way to handle errors in code and start to achieve the reliable and robust code
we would like.
So here is what we learned from the above sections:
 Not a good idea to use resume next in the main body of the code as we have no control over any errors that occur.
 We can think about what errors could occur in a section of code, but we probably cannot think of everything that could
occur. Not all errors that need be treated in the same say, it depends what the error is.
 We need to log when an error has occurred so we can see it in real time and in analysis after the fact.
 If we intend to retry a line of code that caused an error (resume) we need to control how many times we try that.
 At the end of a routine of code we need to know that it completed successfully or not. This is not the same as saying
the routine was error free. For example maybe an error occurred on writing a value to a database, but on the second
attempt it worked successfully. Or maybe not writing the value is unimportant (a conscious decision) to the production
and its loss is perfectly acceptable. Hence overall the routine was successful.

The solution:
1. We will always use an error handler in routines based on ‘On Error Goto label:’
2. The error handler will as an absolute minimum log any errors that occur.
3. The main code routine will be examined to segregate sections of the code into areas where different type of error
and/or different response to the error is required. We will track the code execution and prepare for each new
section or code ready for if an error occurs..
4. We will control the number of times we retry a line of code causing an error.
5. We will make a conscious decision as to what to do about an error occulting in a section of code. Retry, ignore or
stop.

30 of 100
In diagrammatical form

31 of 100
44. Go back to FactoryTalk View Studio and click ‘Test Display”

Click ‘Clear All’ in the diagnostics list.

45. Click ‘Error Trap The Best Way’

you will see the following:

So we have calculated all values apart from the one in error. And we have logged the following errors: Also we have
displayed a message to the operator that there is a problem.

OK let’s look at the code:

46. Click the edit display button

32 of 100
47. Right Click the ‘Error Trap A Better Way’ and select VBA code.

You will now be looking at the routine cmdBestErrorTrap_Released() The body of this code is expanded on the previous
routines to give more scope to show the error trapping in action. Also expanded is the error trapping section of code we are
able to do this because we can track the code execution progress and hence distinguish errors.
Here you see defined a local variable ‘WatchForError’, it could be called anything; it’s just a local variable.

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

So what we are doing here? Well for each distinct section of code, where it’s possible for distinct types of error to occur or a
different response to an error is required, a number is allocated to ‘WatchForErrors’. The number is purely of our choosing.

33 of 100
49. Now if an error occurs the code execution will jump to the error handling routine as you have seen before, but this time by
examining the WatchForError variable we know at what point in the code the error occurred and hence can handle the
error in the most appropriate way.

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.

34 of 100
So looking at the example above: If the value in our WatchForErrors was a:-
 Zero 0
We know that the next lines of code were defining variable/objects etc. So we log an error, 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, there could be a number of reasons why this could fail, and we think to retry the code
again. But we do not want to go into an infinite loop. So here we introduce a counter to let us try this only 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 two above.
50. In this routine I have also introduced a way (there are several ways this can be done) of writing messages to the operator
without using the Message Box (MsgBox ) more on why not later. This is very useful in case the operator misses the message in
the dialogue list box or the dialogue list box is not shown on the client..

The reason for pointing this out is, you see the, If – Then –else conditional expression around the TextOperator.caption.
The reason this is here is to protect against an error occurring within the Error Handler code, for example if the text object
were deleted from the graphic there would be an error. So a flag is set in the code to detect if the object is not there and
hence not use it error handler code.

 It is important not to have an error occur inside the error handler code. There can only be one active
error handler enabled at a time and it is non –reentrant. Meaning the code will just crash in the error handler and
there is no recovery from it apart from closing and reopening the display. So keep the error handler simple and
protect against any errors from occurring in the error handler.

 This section has been using the LogDiagnosticsMessage method to write to the log file . See AID 51771
Error Handling Techniques in FactoryTalk View SE VBA (based on the 2005 version of this lab) for a better way
to log diagnostic messages in a consistent way, particularly if multiple programmers will work on a project.

71. Close the display ‘Error Trapping’, we have finished with it

****** End Of Section ******

35 of 100
Easy Fixes: 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
word. Make it a habit to put this instruction as the first line in all your code routines and modules. Using this instruction
tells VBA to enforce that all variables in the code must be explicitly declared before 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 allows for sloppy programming,
and you know what sloppy programming brings? Yes errors.
Let’s have a look at an example.

1. in FactoryTalk Studio Open the display ‘Option_Explicit’

2. Click ‘Test Display’ icon in the toolbar.

36 of 100
3. Click the ‘Clear All’ button in the diagnostics list

4. Click the ‘Run To Execute’ button

Look at the diagnostics list, you should see:

Click it a couple of more times:

5. It is fairly obvious that the code should be listing the current time and then a number, indicating the number of
times the button has been clicked. So click the Edit Display button then let’s look at the VBA code.

Right click the ‘Run To Execute’ button and select VBA.

37 of 100
6. Here is the code:

Hey there is some error handling enabled, excellent. But we were not seeing errors in the diagnostics list, so that’s not the
problem. But there is a LogDiagnosticsMessage method in the main routine that looks to be writing the kind of message we
saw.

Take just a moment to look at the code; do you see anything wrong?

7. Maybe you do, maybe you don’t. But let’s try following the advice of always putting an Option explicit instruction
in the code.

Type as the first line in the code the following: Option Explicit

8. Now return to the FactoryTalk View Studio Display. Click the Test Display button again.

38 of 100
You will immediately see the following:

Now do you see the problem? The variable CurrentTimeNow has been mistyped as CurrentTmeNow (The i is missing).
9. Click OK button and correct the variable – add the i to correct the variable as CurrentTimeNow

10. Return to FactoryTalk View Studio and click ‘Test Display’ again.

Oh No not another error!

It must have need a bad night before this was coded, see the variable that should be NumberOfPresses has been coded
as NumberOfPreses there’s an S missing I the middle of presses. So click OK and correct the variable name and let’s try
again.

39 of 100
11. Return to FactoryTalk View Studio and select ‘Test Display’.

No error this time, so click the ‘Click To Execute’ Button.

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

So now the code is doing what we expected.

 As you saw in the example without ‘Option Explicit’ VBA did not complain about the typos in the code
because it was trying to be helpful and assumed you meant to type names of CurrentTmeNow and
NumberOfPreses and so 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 no
error. These typo problems can be very difficult to spot, so always use ‘Option Explicit’.

Always use the ‘Option Explicit’ instruction. 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.

Comments

12. It is a good idea to always put comments in your code. Versions, dates and enough comments to help you and
other understand what it is the routines are doing. What is obvious when you are writing the code may not be so
obvious several years later. Meaning full comments will help to keep you out of trouble down the line when
making modifications, investigation issues or code reuse

13. Close and save the display ‘Option_Explicit.

****** End Of Section ******

40 of 100
Long VBA execution times: Techniques and information.

The recommendation and best practice when VBA is used is to minimize the amount of time spent in a VBA routines, because as
explained earlier the VBA is single threaded, which means a single point of execution or one VBA command at a time. Now
that’s not a problem as such, the real problem comes when we want to run other VBA routines also. For example, an operator
clicking buttons which trigger VBA routines. But they will not run until the previous routine is finished. If the routines are short and
quickly executed this is unlikely to be a problem. However if the routines take significant time to execute then we have the
potential for a system that the operator considers unresponsive or slow.
Reasons that routines can take time to execute:
 Large amount of code
 Long loops of code. Single, multiple, nested.
 An unresponsive external component ie OBDC database or Excel etc

It may be that to achieve the functionality you require with the VBA requires long execution times. So in this section we will look
at some techniques and important information to be aware of when using long VBA execution times.

Set-up ready for section.

1. In FactoryTalk View Studio open the display ‘DoEvents’

41 of 100
2. Click Test Display icon in the toolbar

Click on the ‘Zero Values’ button.

Click the Clear All button the diagnostics list

3. We are going to monitor tags in the controller. To do this open Studio 5000 by double Studio 5000 desktop icon.

4. Click FTViewSE_VBA under Recent Projects. Wait until Studio 5000 opens.

5. Select from the menu bar: Communications - Go Online. If you are prompted to Upload – click upload.

If you are prompted to Upload – click upload.

42 of 100
6. Click Controller Tags, Expand MenuValues by clicking on the + symbol.

You should see this. Notice all the tag values are zero (0). We will come back to Studio 5000 later to monitor tag values. But
now return to FactotyTalk View Studio, leaving Studio 5000 open

7. Now we are going to test some VBA code that has a loop to load 1000 values from a file (CSV) on the hard-drive
to 1000 tags in the controller (SoftLogix 5800).
The CSV file is located at : C:\Lab Files\VZ09\CSV\, go to this location and double click the FTViewSE_VBAData.CSV file.
Excel will open the file

43 of 100
You should see that this file is 100 rows of 100 values per row. The values simply increment form 0 to 9999 , this is for ease
of seeing what is going on in the next sections. But in reality the values could be anything – think of it as 100 recipes with
100 values per recipe.

8. Close the Excel file without saving it by clicking the X in Excel

44 of 100
Blocking Operator Interaction

9. Return to FactoryTalkView Studio. What is going to happen is when you click the Get Menu Values button the
VBA code is going to read 10 lines from the CSV file values you just looked at and put them in the MenuValues
array tags. MenuValues[0] to MenuValues[999], ie 1000 (10 x 100) values.

The line that the code will start with from the CSV file is determined by the number shown on the display (default
is one (1). Hence if the value is 1, lines 1 to 10, will be loaded to the controller, if the number was 20 the lines 20
– 29 would be used.

Enough talk let’s do it. Click the button ‘Get Menu Values’

In the diagnostics list you should see the following. Each line as it is written to the controller is reported with a running
seconds count. In my example the 1000 values took approximately 4.7 seconds to be sent to the controller. Your image may
give a slightly different figure.

45 of 100
10. Let’s see if the code worked (it should have, as no errors were reported). Go to Studio 5000. Scroll down the
control tag list to see the MenuValues are now populated with incrementing values from 0 up (because we
started at line 1).

11. So that seemed to work OK; however you can see it can take a few seconds to download all the values to the
controller. Now that in itself may not be a problem, but what if you have a click happy operator, could anything go
wrong

Let’s start by zeroing all the controller values first, click on the ‘Zero Values’ button. This sets a tag in the
controller (not using VBA, but a native View SE object) and the controller resets (zero’s) all the MenuValues[]
tags values.

46 of 100
12. This time you are going to do the same test you did before BUT some timing is required so please read the
whole step (A-C) before you do it.

A) Click ‘Get Menu Values’

B) Wait until you see the first few lines 1 to 3 for example:

Then Click the Zero Values button once

C) Wait until all 10 lines have been written.

13. Return to Studio 5000 . Scroll up and down the MenuValues[] tags. You will see that some of the
MenuValue[] tags are zero and some have a value. In my example below I clicked the zero values button after
line 3 but before line 4 had been processed. So I have zero (0) in Tags MenuValue[0] to MenuValues[399], but
the correct values for MenuVlaues[400] – MenuValues[999]. Check you have the same, the values will change
on a boundary as the hundreds changes as in my example.

So you only have part of your recipe file, not the whole thing. This is not good!

47 of 100
What has happened to allow this? Well because of the length of the loop (approx. 5 seconds) the operator has time to
interact with the display and in this case they (you) clicked ‘Zero Values’ button, so all the tag values were zeroed, but the
loop continued to run and filled in the latter values. So our recipe is incorrect and incomplete!

This particular problem can occur because A) Long loop of VBA and B) FactoryTalk View SE objects are independent of the
VBA. The Zero Values button is a ‘Momentary Push Button’ object running a macro on release

14. Let’s have a look at the VBA code and see how we can make the code more reliable. Click ‘Edit Display’

Now right click ‘Get Menu Values’, and select VBA Code.

You should now see: (if it does not appear click the flashing icon in the windows toolbar )
You will see this centeral section of code :

48 of 100
15. I don’t want you to spend your time now in studying this code. Just notice the main loop, ten (0-9) iterations (100
values per iteration). Above you can also see a couple of arrows ------ pointing to two lines of commented out
code. Remove the comment character ‘ from JUST the start of the two lines for both lines:

‘cmdzero.Visible = False becomes cmdzero.Visible = False

‘cmdzero.Visible = True becomes cmdzero.Visible = True

16. Return to FactoryTalk View Studio and ‘Test Display’ again.

17. Now click ‘Get Menu Values’ button again. But this time watch for the ‘Zero Values’ button disappearing as the
routine starts and reappearing when the last line is written.

Hence be aware of what the operator can do whilst VBA is executing and prevent them from interacting with
the process. Ironically if the Zero Values button initiated more VBA code rather than a native object the operation
would not have been interrupted, but would have been queued up behind the running VBA. This however brings
its own problems as we will see in the next sub sections.

49 of 100
Queuing VBA Events:
Now we will look at how VBA event queue up and get executed as the pervious routine ends. This will then lead us into a
discussion regarding the command DoEvents.

18. Return to FactoryTalk View Studio and the DoEvents display. Here you see two sets buttons for incrementing
(+) and decrementing (-).the starting line number.

The buttons on the right, increment and decrement by calling FactoryTalk View SE commands directly:

The buttons on the left, increment and decrement by calling VBA code.

Notice here the command is identical so we can compare the results directly.

19. Click both the left and right buttons + and – to ensure that the starting line number value does increment and
decrement the value. Note: The limit for the tag is 1 to 90 so you cannot go below 1 or above 90. If you try you
will see errors in the diagnostics list. Also click the buttons in fast succession to get a feel for the response of
incrementing and decrementing rate, you should find that both left and right buttons respond about the same.

50 of 100
20. Now this time do the same tests, BUT first: click the ‘Get Menu Values’ button then the ‘+ and -‘ buttons on the
right hand side only.
First:

Second: Click the right hand + - buttons repeatedly until line 10 has been processed.

You will see this works just as before.

21 Now this time do the same tests, BUT first: click the ‘Get Menu Values’ button then the ‘+ and –‘ buttons on the
left hand side only.
First

Second: Click the left hand + - buttons repeatedly until line 10 has been processed.

Now what you should find is that the left hand buttons + and - do not work when you click them but after line 10 has been
processed the actions all come together .causing the value to change only after line 10 has been processed. A little flood of
messages.

51 of 100
 So the point to note here is that FactoryTalk View SE operations/commends etc are independent of any VBA
code running. So whilst the long loop of VBA code was running, the system still responded to the right hand
buttons (FactoryTalk View SE commands). The left hand buttons were calling other VBA routines, because VBA
in FactoryTalk View SE is single threaded these routines are not called immediately, rather the system queues
them up. When a VBA routine is finished it will then execute the next VBA routine in the queue, hence all the
increments coming together. This gives the operator a feeling of an unresponsive system and could lead to an
unreliable operation of the process.

 This can be a problem if the routines that are called are all long. So in our example if you clicked multiple
times the ‘Get Menu Values’ button then each of these long loops would be queued behind the other long loops
causing potentially very long delays and increasing the operator feeling of unresponsiveness.

If you can use a native FactoryTalk command then that is the best solution. They are independent of VBA,
error trapping is built into the commands and well documented.

52 of 100
DoEvents
So the last section showed us how the VBA events are queued up and run when the previous event (routine) has finished. It was
a simple example to show direct comparison between native commands and VBA. In the real world the VBA code is probably
going to be more complicated.
So here is a scenario that most programmers go through when programming in VBA. They see (or operators report) that the
application is slow. The programmer investigates and discovers that the VBA events are queuing up because of the long
routines.. They go on the web and discover the command: DoEvents. This looks promising as it seems to provide a solution to
the issue.

Microsoft define DoEvents for VBA as:


The DoEvents function surrenders execution of the macro so that the operating system can process
other events. The DoEvents function passes control from the application to the operating system.

This other events, also means more VBA code events.

Microsoft also warn of problems associated with DoEvents.


 Using too many nested DoEvents statements may deplete the stack space and therefore
generate an "Out of Stack Space" error message. This error is referring to the application
stack space allocated to the Microsoft Excel application.
 Make sure the procedure that has given up control with DoEvents is not executed again
from a different part of your code before the first DoEvents call returns; this can cause
unpredictable results.
 Once DoEvents relinquishes control to the operating system, it is not possible to
determine when Microsoft Excel will resume the control. After the operating system
obtains control of the processor, it will process all pending events that are currently in the
message queue (such as mouse clicks and keystrokes). This may be unsuitable for some
real- time data acquisition applications.

These issues references Microsoft Excel BUT are equally applicable to FactoryTalk View SE.
So DoEvents does have its uses but these warnings should never be far from your thoughts if you are planning on using it. In the
next sub section we will use it, and show you some of the potential traps and how to avoid one of them.

22. Click edit display icon in the toolbar.

Right Click the ‘Get Menu Values’ button and select VBA Code.

53 of 100
you will see:

23. On the line that shows ‘DoEvents , remove only the first comment character ‘ at the start of the line.

From: 'DoEvents '<------ HERE is the DOEVENTS


To: DoEvents '<------ HERE is the DOEVENTS
Return to FactoryTalk View Studio and click ‘Test Display’ icon in the toolbar

54 of 100
24. Try the same test again: Click the ‘Get Menu Values’ button followed by several clicks of the left hand + and -
buttons several times. Watch the diagnostics list, you see there is still a slight delay but not so much as before,
because the clicks are being handled between line updates not just at the end of the routine. Note we can ignore
the right hand buttons because we know they work independently of the VBA.

 By using a DoEvents in the loop we have reduced the delay time between responding to the clicks.
How? Well as stated above - DoEvents yields execution so that the operating system can process other
events. In our case these were the click events and could be processed because the DoEvents inside the
loop yielded execution to the operating system. Well that seems fine so far. But then our fictional VBA
programmer conceders using more DoEvents inside the loop to reduce the response delays even more.
BAMM This is the start of the slippery slope that Microsoft warned us about above, bullet point one in the
warnings.

It is also worth noting that because the DoEvents essentially allows the routine to be interrupted it can
extend the overall execution time of the main routine, depending on how long the interrupting routines take.
Again this can give an operator a feeling of unreliability and poor response. In our example it will not make a
great difference as the interrupting (increment/decrement) routine is only one line of code.

25. We have seen that using a DoEvents in the VBA code allows for another routine to interrupt the currently
executing routine. However you also need to be aware that it will allow the same routine to run again, before it
has finished the first execution of the routine i.e code re-entry. This is in the warnings above, bullet point number
2. Now we will test this out to see how it could impact your code.
Some Tidying up first, click ‘Zero Values’

Then set the Start Line Number to 1 (if it is not already) by clicking the – button (either left or right)

55 of 100
then click ‘clear all’ in the diagnostics list

26. Please read the whole step before doing it because there is some timing involved. If you make a mistake don’t worry just do
step 25 again to reset.

A) Click ‘Get Menu Values’ Button

B) Then quickly click the right hand + button 2 times, so the Line Number is = 3

C) Then quickly click the ‘Get Menu Values’ button again.

D) Now wait until the diagnostics list stops incrementing (not displaying new lines). You may want to
make the diagnostic list larger so you can see more detail.

56 of 100
27. This is what I got. Your test may show slightly different timings BUT you should have the same pattern as below.
Read from the bottom up, A-D refer to the sub steps in Step 26

The first execution of the routine continues


from where it finished, Line 6

Step C was here. Start the routine again. It is


not interrupted because we did not click the
Get menu values a second time.

Step B was here and here. Increment

Step A was here. Start routine – It gets to


Line 5

The DoEvents has allowed the second click of the ‘Get Menu Values’ to be processed in the middle of the first execution of
the loop. In my example we see line 5 has just been processed – but then is interrupted by a second execution of the loop
from Line 0 to line 9, then the interrupt returns to the first execution of the loop and it finishes from where it was interrupted.
Ok but has that caused us a problem? Yes it has, because we incremented the start line counter before the second click of
the ‘Get Menu Values’ button.

28. Return to Studio 5000 (which should still be open and on line). Look at the MenuValues[0] upwards. You should see that it
starts with 200 and increments. Remember to make it easy to see what is going on, the values in the CSV file are simple
incrementing numbers.

Why do they start at 200 and not 0? Well it did start at 0 on the first execution, but because the line number was changed to
2 the second execution overwrote the values. Starting at 200.

57 of 100
The second execution of the loop ran for all 10 lines. BUT then the first execution of the loop returned and finished writing
lines 6 to 9, effectively overwriting the values from the second execution of the loop.

Hence in my example I predict that if I look at MenuValues[600] I will see a break in the nice incrementing – you will see
the same but maybe on a different line number .

And sure enough that’s what I do see.

I have part of recipe 1 and part of recipe 3. This is not good and can lead to bad/lost production.

58 of 100
29. How can we stop this sort of behavior? We already looked at one way earlier. That is hiding the button, as we did with the
zero values button. But another technique to stop re-entry from anywhere else in a project is detailed below. We can
include a few lines of code to stop a re-entry into the routine until it’s finished. Let’s do that now.

Click ‘Edit Display’ icon in the toolbar.

Right Click the ‘Get Menu Values’ button and select VBA Code.

30. You are going to do some very minor code insertions. Follow the pictures below, the top pictures to become as bottom
pictures by adding a few lines of code.

This first line defines a flag for us to set and detect the code is already running. The static keyword says remember the state
of this flag.

Near the top of the routine type the following line of code
to this position. (You can also copy paste from this lab
manual).

Static StopReEntry as boolean

Becomes

59 of 100
31. Type a conditional statement to check the state of the flag we just defined and if the flag is not set se will set it. This is our
‘memory ‘that we have started the routine.

Near the top of the routine type the following line of code
to this position. You can also copy paste from this lab
manual).

If StopReEntry = false then


StopReEntry = True

Becomes

32. Type an else clause towards the bottom of the routine, just above the error trapping code.

Near the bottom of the routine type the following line of code to this position,
just above the error trapping. You can also copy paste from this lab
manual).
StopReEntry = false
Else
LogDiagnosticsMessage "Already Busy With Recipe Download"
End If

60 of 100
Becomes

33. And finally for completeness type a reset flag in the error hander.

At the bottom of the routine type the following line of code to this
position: (You can also copy paste from this lab manual).
StopReEntry = false

Becomes:

Return to RSView Studio and Test The display.

61 of 100
34. Time to see if your coding will help us with the re-entry issue. Return to FactoryTalk View Studio
Save your work by clicking on the save icon in the toolbar

Click the Test Display icon in the tool bar.

Clear the diagnostics list

Click the ‘Get Menu Values’ button

Wait until you see a few lines being processed, say Line 3 or 4, then again and click ‘Get Menu Values’ button

This time you should see in the diagnostics list

If you also see this, then congratulations you have prevented the routine from being reentered and hence the recipe
download from being partially overwritten.

62 of 100
35. We are almost done in this section but one more thing to be aware of if using the DoEvents in long code.

Zero the recipe values gain.

Click the ‘Get Menu Values’ button

Wait until you see at least Line 2 in the diagnostics log and click the close X of the DoEvents display

36. The display will close and the recipe download will stop. The download (recipe) is incomplete.

If you want to, go to Studio 5000 and see that the tag values have not been downloaded after the line indicated in your test.

41. So what has happened here? We clicked close display whilst the VBA code was running, however because we are using
the DoEvents in the VBA code, the event is acted upon and the display is closed immediately. So the VBA has no container
to run in and stops. Additional coding is required to prevent or announce the closing of the display like this. Failure to do so
gives possibility of unreliable and non-robust code, as terminating the VBA like this could cause crashes not caught by the
error trapping because it is no longer active because the display is closed.

63 of 100
 The use of ‘DoEvents’ is not a quick fix to responsiveness problems when VBA coding causes long
execution times. (Note: By long execution times I mean time, that allows an operator to continue interaction with
the displays.) As you have seen additional coding is required to counter the side effects of the DoEvents.

 ‘DoEvents’ yields execution so that the operating system can process other events (including outside of
FactoryTalk View SE) . How long do these other events take? Well how long is a piece of string? The time of
yielding to the system depends on what the system is currently doing, it may be quick but it may not be.

Programmers sometimes use the windows API call ‘Sleep’ in place of ‘DoEvents’. The sleep function has
some advantages over DoEvents but the same care must be taken.

One last little note: We have been using the diagnostics list to keep track of the progress of the VBA thought the loop of
code. It is important to keep the operator informed of progress. For example just as progress bars show you the progress when
you install software for example. In actual application it is better to use a technique like in the last section of the error trapping
section. This was the use of a text object but rather than showing errors you could show progress through the long loop.

Ok one more: If in your VBA code you make a call to an external component for example MS Excel, or OBBC etc. You have
no control of when that call will return. This again can lead to giving a poor operator experience.

64 of 100
Events

We are now going to discuss a very useful feature of VBA, that is the use of the ‘WithEvents’ keywords when declaring an object
variable more specifically a Tag object. This enables changes to a tag value to be detected by the VBA without specifically
‘polling’ the tag to look for value changes ie a notification (Event) is raised to flag that a change has occurred. Also this event will
be raised no matter how the value is changed ie by the controller, the operator , VBA or other process.
We will also look at how to prevent issues occurring if you choose to use this powerful WithEvents function.

First Investigate the way WithEvents works.


1. Double click to open the display ‘WithEvents’.

You will see this:

2. Click the ‘Test Display’ icon in the toolbar

65 of 100
The display will open with 0 values in all of the boxes.

Notice that a message has appeared in the diagnostic list: Note the order of the tags may not be exactly as below, we will
discuss this later.

3. Double click any of the EventTags(x) values boxes and type in a value (0 to 99). Press the enter key. Do this
for different tags and different values. Look at the diagnostics list each time you do so to see what is logged.

In this example I changed the EventTag(1) value to 34. Logged in the diagnostic list you see a message ‘download’ (which
is logged by FactoryTalk View SE) followed by a message which includes a time stamp; tag name; and a value. This is
logged by the VBA code. We will look at it later.

An operator change of values was detected by the VBA code.


4. Now click and release the ‘Turn On Run Timer’ button.

It will change to:

66 of 100
5. Note that the value of EventTag(0) is incrementing every 2 seconds (if you do not see it incrementing move the highlight to
another tag value by clicking on any other EventTags).
Also note that each time the value increments, you get a log in the diagnostics list.

This value is being incremented in the controller with a two second timer.

A controller change of values was detected by the VBA code


6. In the explorer of FactoryTalk View SE Studio double click the command line..

7. Enter the following text exactly:


DerivedOn Event

Press Enter. This turns on a derived tag file called Event


The Derived Tag file is changing running a simple script to increment a tag - EventTag[2]:

67 of 100
8. After a few seconds you should see that EventTag(2) is incrementing (at a faster rate than for EventTag(0)) in the
WithEvents display and that a message is logged in the diagnostics list again at a faster rate than for EventTag(0).

Sometimes you even see both tags changing together.

FactoryTalk View server changing values was detected by the VBA code

9. Now in the command line type the following and press return:

DerivedOff Event

10. Close the Command Line box by clicking on the X icon

11 Click on the ‘Turn Off Run Timer’ button:

it will become

All tags should have stopped changing, and no updates in the diagnostic list.

 We have just seen that if an operator, a controller, or an HMI server changes a tag value that VBA captured the event
and for our example, sent a message to the diagnostic log. This was all done with same code not customized for each
scenario.

68 of 100
12. Let’s have a look at the code. Click Edit Display icon in the toolbar.

Then right click the ‘Turn On Run Timer ’ button, and select VBA Code.

13. Scroll to the top of the code, you should see the first two lines are:

Here you see the key word WithEvents.

This is telling VBA to monitor for events occurring on the object. In this case it is a TagGroup (an object defined by the
FactoryTalk View SE Client object model). What events? Well let’s look now.

14. Click the dropdown arrow and select and click on gpGroup

69 of 100
15. Here is the code called the event handler for the group object.

Notice that the gpGroup (tag group) has a change event. This means that if a tag value in the group changes then this event
handler code will run. There is no need to spend time now looking at the code, I just want to point out it is the same code
that is executed from wherever the tag is changed.

As stated before this is very useful techniques to have VBA react to a change without having to poll and wait for the
change to happen.

70 of 100
Inside the Event Loop
I want to show you now a couple of things to be aware off if you decide to use the WithEvents technique.

16. Still in the VBA IDE remove the comment mark ‘ from the two green lines between the WatchForErrors
statements.

To become:

What these lines do is add a value of 1 to the existing value of EventTag(9) and reset it to 0 if the value goes above 99

17. Now return to FactoryTalk View Studio and click on ‘Test Display’. icon

Again you should see the long line in the diagnostic display

But then EventTag[9] starts to increment and messages are logged into the diagnostic list

You see EventTag(9) changing multiple times a second. Cannot stop EventTag(9) from changing, unless we stop the VBA.

71 of 100
18. So what is happening here? We have caused a loop (an event loop). Because in the Event handling code
(above) we change a tag value ‘EventTag(9)’ (we increment by one). BUT this tag changing will cause the event
loop to be executed again, because EventTag(9) is in the tag group we are monitoring. This has given us the
runway loop we are seeing.

 Do not modify any tags values within the event code that is trigged when the tag values changes. You
create a loop of
Tag value has changed  Fire event code  Change the tag value

You also need to be careful that the change does not occur indirectly also. For example you change a value
in a tag within the event code, that triggers a change in another tag, ie in the controller or derived tag files,
which in turn triggers a change in the first tag.

Remember that the VBA code is single threaded, it can only do one thing at once. So the more often
that event code if fired then other VBA code that maybe running will be paused whilst the event code runs.
This can give an operator the impressing that the application is not running reliably.

MesageBox

I promised you earlier in the lab to discuss the VBA message box (MessageBox). This is a very common way to have VBA
interact with an operator, however it is not a good idea to use it use this in a system as it blocks the VBA code form running
until it is closed.

19. . Click Edit Display in FactoryTalk studio.

20. Select button object from the toolbar and on the display draw a button.

72 of 100
21. The Button properties dialogue box will open when you release the mouse button, Select The Up Appearance
tab.

and enter the text ‘Waiting’ in the caption window.

Click OK

73 of 100
22. Right Click on the button and select ‘Property Panel’

Enter a name for your button called ‘cmdWait’, press Enter to accept change.

Close Property Panel.

23. Right Click on the button and select VBA Code.

74 of 100
24. You will see:

25. Enter the following VBA code line:


MsgBox “Waiting”

What no error trapping! For clarity just this once – no. 

26. Now return to FactoryTlak View Studio and click ‘Test Display’ icon in the toolbar

The Diagnostics list should be logging messages as before, EventTag[9] incrementing

27. Click on the ‘Turn On Run Timer’ button: This will give us more events ie the controller changing the tag values

it will become

26. Now click your new button “Waiting’, you should see the message box appear saying waiting. Don’t click OK
just yet!. Goto next step

75 of 100
27. You will see the diagnostics list has stopped updating? Wait now for about 1 minute before clicking OK. When
you do click OK, watch the diagnostics list. What happens?
What you will see is all the events that should have been processed, have been queued up instead and are then processed
all together when the message box is closed, a flood of events. Depending on the number of events, the time to process
events and how long the message box has been active can cause serious problems for application responsiveness.

 Do not use Message Boxes (MsgBox) in VBA code to communicate with operators I would also advice
against the use of VBA forms.

 What can you do to reduce problems when using WithEvents:


- Keep the number of tags in groups that are WithEvents to a minimum, so that event code is not called
too often.
- Keep the group rate for the tags to a rate that can be handled by the event code without affecting
responsiveness of the display. In my example 250ms = 4 times per second.

- Keep code in the event handler short you do not want further events firing whilst still processing the
previous event. The temptation then would be to use DoEvents in the event handler code.

Do not combine the use of ‘DoEvents’ with ‘WithEvents’. Why? Well remember the discussion
above regarding DoEvents and the operator clicking objects and that code interrupting the running code.
Well WithEvents will do just that. In addition if interrupting fast enough, it is possible to get out of stack space
errors and crash the code. Not good when we are trying to write robust and reliable code.

29. Click Edit Display, close the display WithEvents and close the Command Line window.

***** End Of Section ******

76 of 100
Tag Creation, destruction and Writing.

The object model for FactoryTalk View SE is client based, not server based as it is in RSView32. For VBA to access server tags
there is some code to write; this involves creating the tags to use, using the tags for reading and writing then destroying the tags
when finished using them.
These actions take time and there are some techniques that can be used to speed up this process. We will investigate these in
this section.
1. In FactoryTalk View Studio open display ‘Speed’ by double clicking.

You will see:

2. Click ‘Test Display’ icon in the toolbar

3. First we are going to get a bench mark for how fast we can write 1000 values to internal VBA variables: Click
several times the Button ‘Write VBA Variables’. Look in the diagnostics list, you will see:

You may see a slightly different figures, but it should be of the same order or even 0 ie. Faster than a millisecond. This is not
really surprising as they are internal variables.

77 of 100
4. Now we will use actual tags in the controller to see how this compares. First we are going to use the method
Write Pending Values. This is a method from the object model which allows a synchronous write of all the tags
in the tag group. Click the button ‘Write With Pending’ a few times to get an average.

Wait a few seconds and you should see the following three lines appear, note again the times may be slightly different.

The bottom line shows the time in seconds to create a reference for 1000 tags.
The second line shows how long it takes to write values to 1000 tags.
The third line shows how long to destroy the reference to 1000 tags.

5. Click the button ‘Write Without Pending’.

Again wait for the three lines to appear.

You should notice that the time to reference and de-reference are about the same for both buttons, but the time to write the 1000
tags is 2 to 3 times longer. Note: From V7.0 of FactoryTalk View SE is approximately 10 times faster than earlier versions V3,
V4, V5.

6. Now we have seen the time difference when writing to actual tags, let’s look a look at the reasons. Click ‘Edit
Display’ icon in the toolbar.

78 of 100
7. Right Click the button ‘Write VBA Variables’ and select VBA Code.

You will see:

Here the code is looping 1000 times and writing a value of ‘1’ into 1000 VBA Variables. As you would expect - very fast.

The point to make here is that, when you can use internal VBA Variables, use them, and not tag references.

8. Scroll down the VBA code and you will see two more sub routines, one called:
Private Sub cmdWithOutPending_Released() and one called
Private Sub cmdWithPending_Released()
These routines are almost identical, one (cmdWithOutPending) writes directly to the tag value, and the other
(cmdWithPending) writes all tag values to the ‘pending values’ before actually writing the tag values.

Here is the Without pending routine loop, see how the value of the tag is written directly.
The value is written directly to
the tag value. This is the a
slower method, when many
tag writes are performed

79 of 100
Here is the same loop ‘With Pending’, see the value is now written to the Pending Values first, before the value is actually
written to the tags.

The tag value is written to the


Pending Value. This is a
faster method when many
tags writes are performed

Here is where the tag values


get written.

9. So why when writing a lot of tag values is there such a speed difference? This is what we will now investigate now

Return to FactoryTalk View Studio. In the Menu Bar Click Objects  Select a Numeric Display

Click anywhere on the display background and draw a rectangle.

10 The Numeric Display Properties window opens automatically when you release the mouse button. Click the
Tags button

80 of 100
11. Expand the tag browser ‘folders’ sections as below:

In the right-hand Tags section select the tag - @WriteItemsSuccess(near bottom of list)

Click OK

12. Click OK again

16. Repeat steps 9 to 12 but with a new Numeric object, this time select diagnostic tag - @CLXWritePackets (About
17 items down from the top of the list)

81 of 100
17. Your display should look something like this:

This is my tag
@WriteItemsSuccess

This is my tag
@CLXWritePackets

18. Click Test Display icon in the toolbar

19. Your display will look like this, the numbers will be different, don’t worry about that, it is the change in the count
that we are interested in. So take a note of what they are now.

20. Click the button ‘Write With Pending’ – Wait for the three diagnostic lines to appear again and look at how the
counts have changed. You should see that the @WriteItemsSuccess tag count has increased by 1000 and the
@CLXWritePackets has increased by 9. So we have written 1000 values and it only took 9 communication
packets to do it, very efficient.

21. Click the button ‘Write WithOut Pending’ - Wait for the three diagnostic lines to appear again and look at how
the counts have changed. (This time you will see the values incrementing, rather than just a single change)

You will see that the @WriteItemsSuccess tag count has increased by again by 1000 and the
@CLXWritePackets has also increased by 1000. So we have written 1000 values, but this time it cost us 1000
communication packets, very inefficient.

82 of 100
Using the pending values write is much more efficient in sending data. This is because RSLinx is given
all the tags for writing together and can thus optimize communications to the controller. Writing to the tag
value directly means RSLinx does not get this opportunity to optimize communications and uses many more
packets and longer to achieve the same result.

Notice that the time to make references and destroy references to the tags is significant, in my example
over one second (0.80 +0.32). The way the code is written this referencing and destroying of references is
happening every time the button is clicked. This can be optimized by moving the tag referencing to the
Display_AnimationStart() event and the destroying of referencing to the Display_BeforeAnimationStop()
event.

83 of 100
Invoking an ActiveX

In the previous sections I gave the advice that if something can be done natively in FactoryTalk View SE then it is better to do it
there rather than resorting to the use of VBA. The reasons for this being: maintenance, knowledge, potential for introducing
issues. I want to give an example in this section of working in FactoryTalk View SE when using ActiveX controls. You might be
thinking that when ActiveX controls are used it automatically means the use of VBA, but this is not necessarily so.

Let’s imagine you have a requirement to be able to view different types of document within FactoryTalk View SE. You would like
to display to an operator: PDFs, Text Files, HTML documents, Pictures etc. Can we do this without resorting to VBA? Let’s try.

1. First let’s look at some example documents we would like to display. Open windows explorer and navigate to:
C:\Lab Files\VZ09\SampleFiles
Here you will see several types of document (PDF, TXT, JPG, HTM). Double click some of them if you want to take a quick
look.

2. Return to FactoryTalk Studio. Right click on the Displays icon in the project explorer, select and click new.

Drag and resize the display to fill most of the background gray area; this will give us some space to work.

84 of 100
3. We are going to use an ActiveX control so from the toolbar click the ActiveX Control icon

Or
Select it from the menu bar Objects  ActiveX Control

4. With the mouse arrow labeled ActiveX click and draw a square from the top left corner to approximately 5/8 of
the display area. When you let go of the mouse button the ‘Insert an ActiveX Control’ dialogue box will open.

85 of 100
5. Use the scroll bar and drag down the list – select ‘Microsoft Web Browser’, click the OK button.

Click on the white display area outside of the square you just drew, you will then see the Microsoft Window inside the
square.

We are going to use the flexibility of the Microsoft Web Browser ActiveX control to display the different document types
for us.

86 of 100
6. Save (but don’t close) the display and Name it ‘ActiveX’

7. We now have the ActiveX control but we now need to tell the control what to do. From the toolbar click the button
icon

, or select it from the menu bar : Objects  Push Button Button

87 of 100
8. Draw a button under the ActiveX control on the bottom Left. When you let go of the mouse the ‘Button
Properties’ dialogue will open.

88 of 100
9. Click the ‘Up Appearance’ tab and type ‘PDF’ in the Caption Box (Don’t click OK yet)

10. At this point we could jump off and start writing VBA code to interact with the ActiveX control, but here I want to
try and get the functiaonlity without VBA, at least at first. Click the ‘Action’ tab and then click the elipse ‘…’
button in the ‘Release action: section of the dialogue.

This will open the Command Wizard Step 1 of 2.

89 of 100
11. In the Command Wizard scroll down the comands and select ‘Invoke’, click the ‘Next’ button.

This will display the Command Wizard Step 2 of 2

The Invoke command if a way for FactoryTalk View SE to communicate with an ActiveX control.

90 of 100
12. Populate the top three boxes of Step 2 of 2 exactly as documented:

Display: ActiveX
This is the name of the display when you saved it.
Object: MicrosoftWebBrowser1
This is the default name of the first ActiveX object (you can verify it by looking at the property box) but you can call it
anything you want. But for speed we will stick to the default name.
Property or Method: Navigate2
This is a method exposed by the ActievX control to enable an application to tell the Web Browser where to browse to.
ActiveX controls have differant Properties, Methods and Events they expose to facialitate the functionality they are giving.

13. Leave the radio button ‘Invoke method in object’ selected (by default) Click the ‘Add tag as parameter’
button. Then select the tag ‘SetNav_PDF’ click OK button.

This tag has been defined already for you in the HMI database – it is a string tag that is populated with the file location of the
PDF.

Note: The four commas are required as the Invoke command requires all parameters to be defined and this particular
method ‘Navigate2’ requires five parameters in total.

91 of 100
14. Edit the Method parameter(s) box by typing the following text around the tag you just selected.
Before edit:

After edit: A $ is typed at the start and at the end of the tag.

The surrounding $ tells FactoryTalk View SE to use the content of the tag in a command..
Click the OK button.

15 Click the OK button

16. We are now ready to see if this part works. Click the test display Icon in the toolbar.

Then click the ‘PDF’ button you just editted. After a second or so the ActiveX (should if all is well) display the PDF
document (RSTechED 2014 Selection Guide) notice you can scroll the document inside the ActiveX control, and right click
and interact with PDF. In the real world this could be a maintanance manual or instruction manual. It could be oppened as
here by the operator clicking a button or automatically on an event or alarm occuring.

92 of 100
17. Now let’s get the other documents working. Click Edit Display button in the toolbar.

18. Right Click your ‘PDF’ button and select ‘Copy’. Right Click on the white display background and select ‘Paste’.
Click and move the new button to the right of the PDF button. Double click the new PDF button to open its
properties dialogue.

19. Click the ‘Up Appearance’ tab And in the caption box type ‘JPG’.

20. Click the Action tab. In the Release action box edit the existing command line by clicking and scrolling
From:
Invoke ActiveX.MicrosoftWebBrowser1.Navigate2($SetNav_PDF$)
To: by changing PDF to JPG, don’t’ change anything else.
Invoke ActiveX.MicrosoftWebBrowser1.Navigate2($SetNav_JPG$)

Click OK button.

93 of 100
21. Repeat steps 18, 19 & 20 two more times making two more buttons, but with the following changes.
First Copy Call the button TXT change action tab to
Invoke ActiveX.MicrosoftWebBrowser1.Navigate2($SetNav_TXT$)
Second Copy Call the button HTM change action tab to
Invoke ActiveX.MicrosoftWebBrowser1.Navigate2($SetNav_HTM$)

22. We are now ready to see if this part works. Click the test display Icon in the toolbar.

Click each of the buttons and you should see that we can read and interact appropriately with PDF, JPG, TXT and HTM
documents in the same display and all without using VBA.

23. Click Edit Display button in the toolbar.


I want to show now that we can catch events that the ActiveX control raises again without the use of VBA.
Right Click the ActiveX control and click ActiveX Events. You will see this dialogue open. Note the events change
depending on what the ActiveX exposes.

94 of 100
24. Scroll down the list and click NavigateComplete2
Click the … button on the ‘attach a command ‘box. Select Command Remark and enter ‘Hello I Sent This’ Click Finish.

95 of 100
25. In the Event Parameter box select URL, click the browse button …. Select Tag ‘NavToTag’, this is a string tag
already defined in the HMI database. Click the OK Button twice to return to the didplay.

What this will do – is whenever the Web Browser has finished it’s navigation to a document, it will write a comment into the
log and it will write the URL to a tag. Note this could have been any FactoryTalk View SE command and any of the other
events this ActiveX can raise.

26. From the toolbar select a String Display Object Or from the menu bar select Objects  Numeric and
String  Numeric Display. Draw a long string box under all the buttons until the end of the display.

96 of 100
When the property dialogue opens select tag NavToTag

Click OK
Save the display

27. We are now ready to see if this part works. Click the test display Icon in the toolbar.

Click each of the buttons and you should see the tag is populated with the URL and we get a comment in the diagnostics
list.

97 of 100
We achieved quite a lot of functionality there without the use of VBA, the error trapping and reporting is
built into FactoryTalk View SE, so we did not need to do it here.
However we could have done the same with VBA. The time to use VBA over the Invoke command would be
for example if you were already doing some functionality in VBA for a particular graphic or needed to
manipulate multiple ActiveX controls at the same time.
Another example would be – did you notice the JPG fitted quite well into the ActiveX control you drew? That
was because I scaled it so. But if the JPGs were of different sizes and you wanted the web browser to scale
them. VBA would be a more convenient method as the web browser would require additional manipulation to
scale the JPG.

It is not good practice to mix a particular ActiveX control Properties, Methods and Events between VBA
and the Invoke command – use one way or the other only.

******************************************* End Of The Lab, Thank You ******************************************************************

98 of 100
Notes

99 of 100
Publication XXXX-XX###X-EN-P — Month Year Copyright© 2012 Rockwell Automation, Inc. All rights reserved.
Supersedes Publication XXXX-XX###X-EN-P — Month Year

100 of 100

You might also like