Writing Scripts
Writing Scripts
WRITING SCRIPTS
Version 5.0
August 2008
All rights reserved. No part of this publication may be reproduced in any form or by any electronic or mechanical
means, including photocopying and recording, without permission in writing from GE Fanuc Intelligent Platforms, Inc.
Notice
©2008 GE Fanuc Intelligent Platforms, Inc. All rights reserved. *Trademark of GE Fanuc Intelligent Platforms, Inc.
Microsoft® is a registered trademark of Microsoft Corporation, in the United States and/or other countries.
All other brands or names are property of their respective holders.
We want to hear from you. If you have comments, questions, or suggestions about our documentation, send them to the
following email address:
[email protected]
Table Of Contents
About This Guide .............................................................................................................................. 1
Introduction ....................................................................................................................................... 3
Common Scripting Solutions ........................................................................................................ 3
Finding More Information .............................................................................................................. 3
Help Files .................................................................................................................................. 3
Books ........................................................................................................................................ 4
World Wide Web ....................................................................................................................... 4
Newsgroups .............................................................................................................................. 4
Reference Documents .............................................................................................................. 4
Sample Code ................................................................................................................................ 5
Using Samples in the VBA Help File and Source Code ........................................................... 6
Development Tips ......................................................................................................................... 7
Getting Started with iFIX and VBA ................................................................................................... 9
What You Can Do With iFIX and VBA .......................................................................................... 9
VBA Features Not Supported in iFIX ...................................................................................... 10
Components of a VBA Project .................................................................................................... 10
Host Application ...................................................................................................................... 10
Visual Basic Editor .................................................................................................................. 10
Modules .................................................................................................................................. 10
Forms ...................................................................................................................................... 10
Components of the VBA Editor................................................................................................... 11
Project Explorer ...................................................................................................................... 11
Properties Window.................................................................................................................. 12
Code Window ......................................................................................................................... 13
Using VBA Forms ....................................................................................................................... 14
Using VBA Forms within iFIX ................................................................................................. 14
VBA File Types ........................................................................................................................... 15
VBA Naming Conventions ...................................................................................................... 15
Testing Your Code ...................................................................................................................... 17
Saving Your Work ....................................................................................................................... 17
Configuring VBA Options ............................................................................................................ 17
Tips for Configuring VBA Options ........................................................................................... 17
Configuring VBA Project Options ............................................................................................... 18
Datatype Checking and the VBA Compiler ................................................................................ 18
iii
Writing Scripts
Workarounds .......................................................................................................................... 19
Optimizing Your VBA Project Development ................................................................................... 21
Using iFIX Subroutines and Experts .......................................................................................... 21
Sending Operator Messages to Alarm Areas ......................................................................... 21
Using the Multiple Command Script Wizard ............................................................................... 22
Keyboard Accelerators ............................................................................................................... 23
General iFIX Scripting Tips ......................................................................................................... 25
Creating an iFIX Shape with a VBA Script ............................................................................. 25
Using iFIX Collections............................................................................................................. 26
Connecting Animation Objects to Data Sources .................................................................... 26
Reusing Scripts ....................................................................................................................... 26
Cutting and Pasting Code ....................................................................................................... 26
VBA References ..................................................................................................................... 26
Tracking Errors in Subroutines ............................................................................................... 28
Filtering out Global Pages ...................................................................................................... 29
VBA Coding Help Features ........................................................................................................ 29
Auto List Members .................................................................................................................. 29
Auto Quick Info ....................................................................................................................... 30
Context Sensitive Help ........................................................................................................... 30
Guidelines for Using Asynchronous Methods and Subroutines in iFIX Scripts ..........................31
Performing String Comparisons ............................................................................................. 31
Working with iFIX Objects .............................................................................................................. 33
VBA Object Count Limit .............................................................................................................. 33
Object Availability in the VB Editor ............................................................................................. 33
Understanding the iFIX Object Hierarchy ................................................................................... 34
VBA Object Browser ............................................................................................................... 35
Connecting Objects to Data Sources to Create Animations ......................................................35
Making Connections ................................................................................................................... 36
Directly Connecting to a Data Source .................................................................................... 36
Making Connections through Animations ............................................................................... 38
Connecting or Disconnecting an Object's Property to a Data Source ....................................42
Retrieving Connection Information from a Property's Data Source........................................42
Determining if an Object's Property is Being Used as a Data Source ...................................44
Retrieving General Connection Information ........................................................................... 45
Animation Properties and Methods ............................................................................................ 47
General Animation Object Properties and Methods ............................................................... 47
Linear Animation Object Properties ........................................................................................ 48
iv
Writing Scripts
v
Writing Scripts
vi
Writing Scripts
vii
About This Guide
The Writing Scripts manual is intended for system integrators, OEMs, and process control engineers
responsible for customizing their iFIX® software automation solution using Visual Basic for
Applications. The manual assumes that you are familiar with Microsoft Windows and the Visual Basic
programming language.
The first few sections of the book provide some background on Microsoft Visual Basic for
Applications (VBA), but the intent of this manual is to describe the implementation of VBA within
iFIX, not to explain how to program in Visual Basic.
If you are new to the Visual Basic language, you may want to consult one of several sources of
information on the basics of VB programming, which are beyond the scope of this book. If you are a
novice VB programmer, check out the Finding More Information section and the Getting Started with
iFIX and VBA chapter to learn where to find information on general VB programming topics.
1
Introduction
This introduction contains the following sections:
• Common Scripting Solutions
• Finding More Information
• Sample Code
• Development Tips
The Getting Started with iFIX and VBA chapter describes basic information on using the VBA
programming language, and describes several key components of the VBA environment.
Starting with the section Optimizing Your VBA Project Development, this manual teaches you how to
write VBA code for iFIX objects. The intention of these sections is to teach you how to code by
example, and many times the best explanation of the sample code lies within the commented lines
(lines that begin with an apostrophe — these lines are for explanatory remarks and are ignored by the
VBA compiler), so look carefully. Because each section is dedicated to a different object, you can find
the information you need quickly and easily.
Help Files
You already have two excellent sources of VBA information installed on your computer right now.
3
Writing Scripts
The Visual Basic for Applications Help file that ships with iFIX contains an enormous amount of
information. You can launch this help file by selecting the Microsoft Visual Basic Help command from
the Visual Basic Editor's Help menu. If you don't have iFIX running, you can launch this Help file
directly by double-clicking VBUI6.CHM in the VBA directory of the Microsoft Shared path (by
default, C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\1033). Throughout this
manual, topics are listed in the Visual Basic for Applications Help file that you should explore if you
want to learn more about programming in Visual Basic.
Once you are ready to begin coding, you will undoubtedly need more information on the objects,
properties, methods, and events that are specific to iFIX. You can find this information in the
FIXVBA.CHM Electronic Book, which is located in the Help and Information folder of the Proficy
iFIX WorkSpace's system tree. You can also select the iFIX Automation Help command from the
Visual Basic Editor's Help menu. If you don't have iFIX running, you can launch this Help file directly
by double-clicking FIXVBA.CHM in the iFIX NLS path (C:\Program Files\GE Fanuc\Proficy
iFIX\NLS by default).
The Visual Basic for Applications Help file should not be confused with the iFIX Automation
Interfaces Help file. The VBA Help file is a reference for the Visual Basic for Applications user
interface and programming language only — it does not contain any information about how VBA has
been integrated into iFIX. On the other hand, the iFIX Automation Interfaces Help file is dedicated to
the objects, properties, methods, and events that are specific to iFIX, but does not teach fundamental
VBA programming concepts.
Books
One of the largest bookstores on the Internet, Amazon.com, currently lists over 900 Visual Basic titles,
some of which are carried (or can be ordered) by your favorite local bookstore. Two books which
provide useful information are:
• VB and VBA in a Nutshell: The Language by Paul Lomax
• VBA Developer Handbook by Ken Getz
Newsgroups
The Visual Basic newsgroups are popular sources of information on the VB programming language as
well. These forums are great for interacting with other Visual Basic programmers, and offer an
excellent way to post a particular issue and get it answered by a programming expert. To find them,
filter the newsgroup list by specifying any of the following words: "vb", "visual", "basic", and "visual
basic".
Reference Documents
The chapter, Working with the Scheduler and the DoEvents Function, contains example code that
illustrates how to run several scripts at the same time in the single-threaded environment of VBA using
the iFIX Scheduler application. After reading this section, you may want to refer to the Mastering iFIX
manual to learn more about how to use the Scheduler.
4
Writing Scripts
Sample Code
One of the best ways to learn any programming language is to examine code that already exists and try
to decipher how the code works. This manual contains a great deal of sample code that you can cut and
paste directly into the Visual Basic Editor. The following is a list of the sample scripts included in this
manual. You can click on an example title to view the sample code.Working with iFIX Objects
Manipulating Pictures
5
Writing Scripts
Manipulating Charts
6
Writing Scripts
4. In Ribbon view, on the Home tab, in the WorkSpace group, click Visual Basic Editor.
- Or -
In Classic view, on the WorkSpace menu, click Visual Basic Editor.
5. In the VBE, select the Project Explorer command from the View menu.
6. In the Project Explorer, click the plus sign (+) next to any of the available projects to show the
contents of the project.
7. Double-click a form or module within the project to display it in the VBE. For example, if
you expand the Project_Experts project, expand its Forms folder, and double-click the frmFill
form to view the Fill Expert form.
WARNING: Although you can look at the source code for the above mentioned objects within
iFIX, do not modify any of the code or your environment may not work as expected.
Development Tips
The open architecture of iFIX provides an extremely flexible automation interface. In fact, you may
learn that, in some cases, you can write two or more very different VBA scripts that achieve the same
end result. In the code samples throughout this manual, you will find tips, suggestions, and tricks in an
effort to help you discover the most efficient ways to automate iFIX with VBA.
7
Getting Started with iFIX and VBA
Visual Basic for Applications, or VBA, is the standard scripting language built into iFIX®. VBA was
once only available in Microsoft Office applications. However, Microsoft has made VBA available
through licensing, so companies like GE Fanuc can integrate the language directly into their products.
Refer to the following sections for more information on how to get started with iFIX and VBA:
• What You Can Do With iFIX and VBA
• Components of a VBA Project
• Components of the VBA Editor
• Using VBA Forms
• VBA File Types
• Testing Your Code
• Saving Your Work
• Configuring VBA Options
• Configuring VBA Project Options
• Datatype Checking and the VBA Compiler
9
Writing Scripts
Host Application
All VBA projects must be associated with an application; you cannot create a stand-alone VBA project.
The application that the VBA project is tied to is called the host application. In the case of iFIX, the host
application is the Proficy iFIX WorkSpace, and each VBA project is embedded in an iFIX picture file
(*.GRF), toolbar file (*.TBX), toolbar category file (*.TBC), schedule file (*.EVS), Dynamo set file
(*.FDS), or User file (USER.FXG).
Modules
If you are developing large VBA projects, it may make sense to separate the code into several
modules. Modules are self-contained blocks of code that perform a particular function. For example, if
you wanted to write a wizard that creates a real-time chart for a specific data point, you may want to
break the project up into three modules: one module to retrieve the value after prompting the operator
to specify a data source, one module to plot the data after prompting the operator to specify a chart
type, and one module to create the chart based on the operator's specifications.NOTE: Do not include
modules in Dynamo objects, since they are not moved with the Dynamo object.
Forms
Forms are custom dialog boxes that you create in VBA in order to exchange information with the
operator. Examples of forms are message boxes, input dialogs, and configuration screens. Forms are
essential in helping the application and the operator interact.
10
Writing Scripts
Project Explorer
The Project Explorer is a special window in the VBE that shows each of the elements of your VBA project.
The elements are presented in a tree format, with each branch displaying related information, such as
forms, code modules, and elements from iFIX, such as pictures, toolbars, and global pages.
The Project Explorer makes it easy to select the project elements that you want to work with. For
example, if you want to add a button to a particular form you've been working on, you can select the
form from the Project Explorer. After you select a project element to edit, the VBA editor opens the
appropriate tool. For example, if you select a form, the form displays on screen with the Form Toolbox
available.
There are two ways to select and edit a project element that displays in the Project Explorer:
11
Writing Scripts
Properties Window
The Properties window is used to review and set properties for project objects. For example, you can set the
background color for an iFIX picture in the Properties window, or you can change the name of a rectangle
within that picture.
Properties Window
12
Writing Scripts
Code Window
The Code window is where you write any code associated with your VBA project. You could write
code which is executed when the user clicks a button in an iFIX picture, or it could be a part of a
procedure library you've written to serve your entire project.
Code Window
Two drop-down lists are located just below the title bar. One drop-down list shows all of the objects
referenced in the code module, while the other drop-down list shows the procedures associated with
each object.
To display the code window, do any of the following:
• Right-click an object in the Proficy iFIX WorkSpace and select Edit Script from the pop-up
menu.
• Double-click any code element in your application in the Project Explorer, such as modules
13
Writing Scripts
WARNING: Do not update these files. Doing so may cause the toolbar buttons to stop working
properly.
Modeless forms do not appear in the task bar and are not in the window tab order. To call a modeless
form, use the following code:
userForm1.Show vbModeless
14
Writing Scripts
NOTE: You may lose data associated with a modeless UserForm if you make a change to the
UserForm project that causes it to recompile, for example, removing a code module.
When using a modeless form, if you do not want to allow the user to get to the WorkSpace, use the
DeActivateWorkspaceUI which essentially disables the WorkSpace UI. For more information, see the
DeActivateWorkspaceUI method topic in the iFIX Automation Interfaces Electronic Book.
Inserting an Alarm Summary object into a VBA form may cause unpredictable results when opening
the picture or switching environments from run-time to configuration or vice versa.
Extension Component
FRM Form
To learn more about importing and exporting Visual Basic files, refer to the Help topics within the
section Visual Basic User Interface Help of the Visual Basic for Applications Help file, or search for
the Index keywords "import" and "export".
• You should not use any names that are identical to the functions, statements, and methods in
Visual Basic because you may shadow the same keywords in the language.
• To use an intrinsic language function, statement, or method that conflicts with an
assigned name, you must explicitly identify it.
• Precede the intrinsic function, statement, or method name with the name of the
associated type library. For example, if you have a variable called Right, you can
15
Writing Scripts
• You cannot repeat names within the same level of scope. For example, you cannot declare
two variables named level within the same procedure. However, you can declare a private
variable named level and a procedure-level variable named level within the same module.
• You cannot use a space, hyphen (-), period (.), exclamation mark (!), or the characters @, &,
$, # in the name.
NOTE: If you have database tags that contain invalid VBA characters, such as hyphens, and
you want to manipulate these tags through scripts, you can use two iFIX subroutines
(ReadValue and WriteValue) to do so. You can learn more about the ReadValue and
WriteValue subroutines in the section Optimizing Your VBA Project Development, or in the
iFIX Automation Interfaces Electronic Book.
• You should not use an underscore (_) in the name. It may cause problems with scripting,
because VBA uses underscores in the naming of scripts associated with objects.
• Pictures, schedules, Dynamo sets, toolbars, and toolbar categories require unique names so
that the Proficy iFIX WorkSpace can load them simultaneously. This is true even though the
file name extensions differ for different document types. The following scenarios illustrate
this point:
• If you attempt to open a picture whose name conflicts with a document that is
already open, you will not be able to open the picture. Instead, the following text
appears:
Another Schedule, Picture, Toolbar, or Dynamo Set with same name
is already open.
• If you attempt to enable a toolbar whose name conflicts with a picture that is already
open, the Proficy iFIX WorkSpace will not enable the toolbar.
• If you open a picture that has the same name as a toolbar category, and then either
click the Buttons tab on the Customize Toolbars dialog box or run the Task Wizard,
the Proficy iFIX WorkSpace will not display the toolbar category.
Avoid renaming VBA objects in a VBA script. Doing so will cause the code associated with those
objects not to function. For example, if a rectangle named Rect1 has an associated event called Sub
Rect1_Click(), changing the name of the rectangle to Rect2 will cause Sub Rect1_Click() not to
16
Writing Scripts
Rect1.Name = strNewName
End Sub
You can also display the form you are working on, execute any code that you have attached to event
procedures within the form, and test the controls that you have placed on the form. To run the form,
position the cursor anywhere on the form, and then choose Run Sub/User Form from the Run menu, or
press F5.
To learn more about running your VBA code, refer to the Help topics within the section Visual Basic
How-To Topics of the Visual Basic for Applications Help file, or search for the Index keywords
"running code" or "executing code".
To save a picture from VBA, choose the Save command from the File menu. This will save any
changes that you have made to the picture, as well as to the VBA project.
NOTE: Toolbar and toolbar category files are saved automatically when you exit the WorkSpace. If
you made changes to the User Global file, iFIX displays a message box that asks you if you want to
save your changes.
This section describes two specific items or settings that we recommend you take advantage of when
configuring your VBA options.
17
Writing Scripts
Although it is not required, you should use the Option Explicit statement in the Declarations section of
a module to require variable declaration. The Option Explicit statement forces you to use variables that
have already been declared as a certain type. Using the Option Explicit statement will help you avoid a
common programming error and will shorten your debugging time.
To configure VBA to automatically add the Option Explicit statement to a new project:
The Compile On Demand option, located on the General tab of the Options dialog box, determines
whether a project is fully compiled before it starts, or whether code is compiled as needed, allowing
the application to start sooner. We recommend that you clear this check box so you can more easily
debug errors in your code.
WARNING: Do not enable the Notify Before State Loss option, located on the General tab of the
Options dialog box. Doing so may cause an error or interruption in the Proficy iFIX WorkSpace.
One option that you can enable for your project is to specify a Help file that you may have built for
your project and the context ID that enables it to run with your project. For more information on how
to create a picture-specific Help file, see the Creating Picture-Specific Help Files section of the
Mastering iFIX manual.
For more information on the other project properties that are available, refer to the sections Visual
Basic User Interface Help and Visual Basic How-To Topics in the Visual Basic for Applications Help
file, or search for the Index keyword "properties" and select "project".
18
Writing Scripts
1. One subroutine or function has a variable which is declared as type Variant. If you do not
explicitly assign a type, it is Variant.
2. This variable is passed to a second subroutine or function.
3. The second subroutine or function is set up to accept a value from the first subroutine or
function, but of a type other than Variant (Integer, long, or object, for example).
You may get this error:
Compile Error; ByRef argument type mismatch
Error Example
The following example shows two subroutines: the first subroutine gets a rectangle's downstream
animation object, which is connected to the rectangle's VerticalFill Percentage. The second subroutine
gets the animation object's class type. Since the second subroutine is defined as an object, and the first
is passed in as a Variant/ObjectArrayItem, the VBA 6.0 compiler displays the ByRef argument
mismatch error.
Rect1.GetConnectionInformation 1, "VerticalFillPercentage", _
sSource, sFullQualSource, vSourceObjs, vTolerance, vDeadBand, _
vUpdateRate
CheckSourceObject vSourceObjs(0)
End Sub
This scenario is acceptable in a VBA 5.0 environment, but a ByRef Argument mismatch error is
generated when running or compiling in VBA 6.0.
Workarounds
Either the calling routine or called routine has to change. The following scripts are workarounds that
will satisfy the compiler and provide the exact same functionality.
Workaround 1 – This script changes the called routine and is the easier correction. Referring to
the previous example, if you change the CheckSourceObject routine to specify that the
argument is passed in by value, this will pass the compiler check. Since the parameter
passed is not being modified, it is safe to pass by value.
19
Writing Scripts
MsgBox objSrcObj.ClassName
End Sub
Workaround 2 – This script changes the calling routine so that the coercion is performed before
the call.
This line assigns a declared Object to the first element of the variant array. Next, we pass in the
objSourceObject, which is an Object instead of the Variant/ObjectArrayItem. This passes the compiler
check.
20
Optimizing Your VBA Project Development
VBA is a powerful scripting tool integral to iFIX. Many features of iFIX allow you to use VBA more
effectively. This chapter presents many options that help you build your projects more easily:
• Using iFIX Subroutines and Experts
• Keyboard Accelerators
• General iFIX Scripting Tips
• VBA Coding Help Features
• Guidelines for Using Asynchronous Methods and Subroutines in iFIX Scripts
In VBA, you can read this tag with the following syntax:
Private Sub Text1_Click()
Dim x As Variant
x = ReadValue("Fix32.SCADA.SORTER|SIZER|BLOCK10|PT.F_CV")
Text1.Caption = x
End Sub
Once the value is stored as a variant (x), you can use it in expressions.
21
Writing Scripts
As stated in the previous section, subroutines handle the posting of operator messages to alarm areas
for you. Therefore, the following script:
Writevalue "1", "sample"
A separate subroutine, SendOperatorMessage, is provided for that purpose. Simply add a call to the
SendOperatorMessage to generate the desired message.
WriteValue, ReadValue, SendOperatorMessage, and all other iFIX subroutines are described in
more detail in the Subroutine Summary section of the iFIX Automation Interfaces Electronic Book.
The code within the global subroutines offers a wealth of information to the developer who is learning
how to automate iFIX with VBA. Realizing this, all of the code within these subroutines has been
exported to a text file entitled globalsubroutines.txt (located in the iFIX NLS path) for your
convenience.
iFIX also provides several Experts to help you perform the most common functionality. Just as
subroutines offer help to the seasoned VBA programmer, Experts can help developers who want to
achieve similar results without having to write any VBA code at all. These Experts, which look like
standard dialog boxes, actually generate VBA code for you, based on how you configured the options
within the Expert. You can learn more about Experts in the Creating Pictures manual.
'WizardLast=Wizard2
'WizardEditing=Wizard0
'WizardName=MultipleCommands
22
Writing Scripts
'Wizard1=AcknowledgeAlarm
'Property1=Fix32.THISNODE.AI0.F_CV
'Property2=False
AcknowledgeAnAlarm "Fix32.THISNODE.AI0.F_CV"
'WizardEnd
'Wizard2=AlarmHorn
'Property1=optExpertTypeSilence
'PropertyDescription=AlarmHornSilence: Property1=Type
AlarmHornSilence
'WizardEnd
End Sub
NOTES:
• Although the Multiple Command Script Wizard's purpose is to fully automate the VBA
command scripting process, you can manually edit scripts generated by the wizard with the
VB Editor. You may add or edit VBA scripts anywhere before the Scripts Authoring Tool
header line (***** Scripts Authoring Tool *****), or directly between a "WizardEnd" and a
“Wizard[x]=” statement. Do not edit any of the commented areas in the wizard-generated
script. If the Multiple Command Script Wizard detects an improperly customized VBA script,
you may encounter an error.
• The Multiple Command Script Wizard does not check the command sequence to make sure
commands occur in a logical order.
For more information about the Multiple Command Script Wizard, see the Creating Pictures ebook.
Keyboard Accelerators
You can use keyboard accelerators, key sequences that allow you to perform a function, to fire scripts using
the KeyUp or KeyDown events. However, the built-in WorkSpace keyboard accelerators take precedence
over any KeyUp or KeyDown events in the picture or user area. Therefore, you should avoid using
keyboard accelerators that conflict with those that are reserved for internal use. The following table lists all
of the reserved accelerators in the run-time and configuration environments.
23
Writing Scripts
F10, Ctrl + F10, Alt Activates the WorkSpace menu Yes Yes
(alone) bar.
24
Writing Scripts
Shape.HorizontalPosition = 10
25
Writing Scripts
Shape.VerticalPosition = 10
Shape.Width = 30
Shape.Height = 30
The BuildObject method creates the object. Once the object is created, you can perform one of these
options:
• Set the object's properties through VBA code.
• Call the CreateWithMouse method (as in the above example) to change your mouse cursor
into the draw cursor and then configure the properties of the object using the traditional iFIX
user interface.
To connect an animation object and a data source, use the SetSource method to set the Animation object's
source property:
ExpressionEditor1.RefreshRate, ExpressionEditor1.DeadBand, _
ExpressionEditor1.Tolerance
The SetSource method allows you to set the data source's refresh rate, deadband, and tolerance. The
second parameter lets you set an undefined object as the data source. (True indicates a UseAnyway
condition.)
Reusing Scripts
You can develop scripts directly in the main VBA project; however, this approach makes reusing the
scripts more difficult. Instead, you should store subroutines in a separate module and then call these
subroutines from the main project when you want to reuse the scripts. This allows you to export and
then import the scripts into a new project with minimal modification, and also provides a more
modular, component-based design.Cutting and Pasting Code
You can cut (or copy) and paste an object from one project to another by dragging and dropping that object.
Although this operation directly copies the VB code within the object to the new project, it does not
automatically copy the event entries (a Click event, for example). Make sure you copy the content of the
event entry into a subroutine (by selecting Edit Script from the object's pop-up menu) before pasting the
code into the new project.
VBA References
VBA allows you to add an object library or type library reference to your project, which makes another
application's objects available in your code. These additions to your VBA project are called references.
You can view, add, and delete references by selecting the References command from the Tools menu
in the Visual Basic Editor (VBE).Whenever you add a control into a picture, the control's type library
26
Writing Scripts
is referenced by the picture within VBA. When you delete a control from a picture, the reference to the
control is automatically removed to increase performance. However, you should never manually
remove the references to "Project_FactoryGlobals" or "Project_User".
Whenever you reference objects, controls, or mechanisms in VBA, follow the guidelines in the
following sections. To learn more about references in VBA, refer to the VBA Help file.
Any object that is referenced by name in a script cannot be deleted. For example, in the following
sample script the code in Rect2_Click will execute, but the pen will not be deleted:
Rect1_Click()
Pen1.Source = "Fix32.ThisNode.AI_30.F_CV"
End Sub
Rect2_Click()
Chart1.DeletePen 1
End Sub
If you wanted to access the object in this example without referencing it by name, you could use the
following code in Rect1_Click ():
Rect1_Click()
Dim o as object
set o = Chart1.Pens.Item(1)
o.Source = "Fix32.ThisNode.AI_30.F_CV"
End Sub
When an object (2Dshape, FixDynamics object, ActiveX control) is deleted from a picture and no
object of that type are left in the picture, the reference to that object's type library in the VBA project is
removed. To continue to use this object's type in scripts, you must manually add a reference to the type
library in the VBE by selecting References from the Tools menu and selecting the type library.
You should be aware of the following behavior when dragging and dropping a Dynamo object into a
picture, cutting and pasting a Dynamo object, or dragging and dropping a toolbar button from a
category into a toolbar:
• VBA copies all forms, scripts, events, and sub-forms associated with the toolbar button or
Dynamo object.
• VBA does not copy any VBA modules or class modules associated with the toolbar button or
Dynamo object. Code that you put in these modules will not run if you drag the Dynamo
object or the toolbar button to another picture or toolbar.
• VBA does not copy references to other objects such as controls or DLLs that you create for
27
Writing Scripts
toolbar buttons or Dynamo objects. For example, if you include a third-party OCX as a
control on a form for a toolbar button, VBA does not copy the reference when you drag the
toolbar button to a toolbar. The script will not run until you open the Visual Basic Editor and
create a reference to the OCX for the toolbar project.
0 Use the default error handling. Allows subroutines to provide the error
messages. If no entry is made for the intErrorMode parameter, the default is
used.
1 Allow the user to handle the error messages. Errors in the subroutines are
passed back to the calling routine for handling.
2 Write errors to all Alarm Services. No error messages display. Instead, the
errors are written to all iFIX Alarm Services, including the Alarm History
window.
For example, if you use the intErrorMode parameter with the OpenDigitalPoint subroutine, the
command would look like:
OpenDigitalPoint [DigitalPoint], [intErrorMode]
Examples
For the OpenPicture subroutine, you get the standard error message if you enter 0 for the
intErrorMode, as shown in the following example:
OpenPicture "BadPic", , , , 0
When you use 0 for the intErrorMode, if you try to open a picture that does not exist, a message box
appears whose title is the name of the picture that made the erroneous call and whose contents are the
error number and error description.
If you enter a 1 for intErrorMode, the error is raised for you to handle:
OpenPicture "BadPic", , , , 1
Your error handling code would have to look something like this:
On Error Goto Errorhandler
OpenPicture "BadPic", , , , 1
End Sub
Errorhandler:
28
Writing Scripts
If you enter a 2 for intErrorMode, the error is sent to all Alarm Services, including the Alarm History
window using the SendOperatorMessage method:
OpenPicture "BadPic", , , , 2
When you use 2 for the intErrorMode, you provide for silent error tracking.
29
Writing Scripts
30
Writing Scripts
ClosePicture "Tank1"
DoEvents
OpenPicture "Tank2"
End Sub
Else
End If
End Sub
31
Working with iFIX Objects
The integration of VBA into iFIX provides you with additional control and flexibility to develop,
manipulate, and animate objects and graphics in the Proficy iFIX WorkSpace. This is important since
objects make up a large part of your application.
This chapter gives you some specific examples on how you can use VBA scripting to enhance the
performance of iFIX objects in your application. It also gives you helpful tips for working with objects
and their characteristics.
Refer to the following sections for more information on working with iFIX objects:
• VBA Object Count Limit
• Object Availability in the VB Editor
• Understanding the iFIX Object Hierarchy
• Connecting Objects to Data Sources to Create Animations
• Making Connections
• Animation Properties and Methods
• Connection Example: Animating the Rotation of a Rectangle
• Rotating a Group
33
Writing Scripts
For optimization purposes, if you choose not to tie a script to the object, it does not remain available
after you close the picture. You will have to select it again in the picture and add the objects to the
VBE if you want to use them in a script.
You can, however, forward-reference objects that are not available in the VBE. For example, you can
write a script tied to Rect1 that references Oval1, as shown in the following example:
Oval1.Visible = False
The above code is acceptable even when Oval1 is not available to the VBE. The only difference in the
VBE between objects that are available and objects that are not available is that the list of properties
and methods available to the object appear when you type the period (.) after available objects. When
forward-referencing objects, the objects will be added to the project when the picture is closed or
saved.
The following objects are always available in the VBE:
• Timer objects
• Event objects
• Buttons
• Dynamos
• ActiveX controls
• Variables
• Any objects that have been added to the Global page
34
Writing Scripts
Object Browser
Press F1 to display the associated Help topic in the iFIX Automation Interfaces Electronic Book while
positioned on any iFIX object, property, method, or event.
35
Writing Scripts
conditioning. For example, if a data source has EGU limits from 0 to 65535, and a tank's fill
percentage has a range of 0 to 100, the Linear object transforms the data source range to the
tank's fill percentage range. Refer to the Understanding Signal Conditioning section of the
Building a SCADA System manual for more detail on how the Linear object works.
Lookup – Uses a table structure to map either a range of values or exact values from a data source
to a single value of the connected object's property. For example, if a data source has
multiple alarm values, the Lookup object maps each alarm value to a rectangle's color. You
can also set up a Lookup object to divide a range of values into levels or rows, and map
those levels to a rectangle's color. The Lookup object also has a Toggle property that can be
used for blinking colors.
Format – Converts the source data into a string. When you set up a data source for a data link, for
example, you actually create a Format object that transforms the data source into a string.
You will see examples of these objects in the scripting examples throughout this section. For more
information on animation objects, including object-to-object connections, refer to the Creating Pictures
manual. For a detailed explanation of all the animation properties and methods for each of the
animation object types, refer to the Animation Properties and Methods section.
Visual Basic has many methods you can use to make connections to data sources. These various
methods are detailed in the following sections.
Making Connections
A very important element of connecting objects to data sources is the way in which they are connected.
You can connect to the data source: From an object's property directly to the data source.
• From an object's property to an animation object and then from the animation object to the
data source.
Refer to the following sections for more information about making connections:
• Directly Connecting to a Data Source
• Making Connections through Animations
• Connecting or Disconnecting an Object's Property to a Data Source
• Retrieving Connection Information from a Property's Data Source
• Determining if an Object's Property is Being Used as a Data Source
• Retrieving General Connection Information
36
Writing Scripts
You can form a direct connection either by using the Animations dialog box or by writing a script.
Both methods are described below.
NOTE: You cannot perform a Find and Replace on an object when that object has a direct connection
to another object. To perform a find on an object in an object to object connection, use the One Tag
search type in the Cross Reference Tool. For more information, refer to the Searching for One Tag
section of the Mastering iFIX manual.
To make a direct connection using a script, you need to call the Connect method. The following
procedure shows you how to make a direct animation from an object to a data source on the Click
event of a toolbar button in the configuration environment.
NOTE: For OPC data sources you need to remove any character, such as single quotes, that is not
part of the valid server address syntax. For example: "ServerName.'Device:MyAddress'" should
change to "ServerName.Device:MyAddress" after you remove the single quotes.
1. Insert a rectangle into a picture and name it MyRect. Right-click the rectangle and select Edit
Script to make MyRect available to the Visual Basic Editor.
2. Create a new toolbar and add a button named DirectConnect. See the Understanding Toolbars
37
Writing Scripts
section of the Understanding iFIX manual for more information on creating toolbars and
adding toolbar buttons.
3. Add the following code to the toolbar button's Click event:
Private Sub DirectConnect_Click( )
MyRect.Connect("Horizontal Position", _
"FIX32.NODE.AI1.F_CV", lStatus)
End Sub
The following script uses the Linear Animation object to form the connection from a rectangle's
Vertical Position property to a data source. This script is entered in the Click event of a toolbar named
btnDirectConn. In this example, Animations is the picture name. For more information on the methods
and properties used in the script, namely SetSource, Connect, DoesPropertyHaveTargets, and
GetPropertyTargets, see the iFIX Automation Interfaces Electronic Book.
38
Writing Scripts
Dim vtTargets()
'the rectangle
iRect.HorizontalPosition = 80
iRect.VerticalPosition = 45
iRect.Height = 5
iRect.Width = 10
iOval.HorizontalPosition = 60
iOval.VerticalPosition = 35
iOval.Height = 5
iOval.Width = 10
iRect.Commit
iOval.Commit
39
Writing Scripts
LinearObject.LoInValue = 0
LinearObject.LoOutValue = 0
LinearObject.HiInValue = 100
LinearObject.HiOutValue = 50
LinearObject.UseDelta = True
40
Writing Scripts
'GetPropertyTargets method.
iRect.DoesPropertyHaveTargets "VerticalPosition", _
vtTargets
End Sub
41
Writing Scripts
The Connect method shown below connects an object's property to a data source:
Object.Connect(PropertyName As String, Source As String, _
[DeadBand], [UpdateRate])
This call connects the property (defined in the PropertyName parameter), to a source (defined in the
source parameter.) For example, if you want to connect a rectangle's height property directly to tag AI,
you would enter the following:
Dim 1status as Long
The Disconnect method disconnects the object's property from a data source:
Sub Disconnect(PropertyName As String)
The SetSource method sets the connection properties for an animation object. Use the SetSource
method instead of directly setting the animation object's source property if additional properties have to
be specified for the connection. You do not need to specify the data source.
Object.SetSource bstrExpression, [bUseAnyway], _
[vaConnectionFlags]
NOTE: If you are performing run-time source substitutions, and you want to preserve the tolerance,
deadband, and the update rate for the tag, use the SetSource command instead of the Source property.
If you use the Source property, the tolerance, deadband, and update rate settings are reinitialized to 0.
The SetSource command provides the appropriate parameters to effectively set these attributes. You
can only use the SetSource method for animation objects.
The IsConnected method determines whether an object's property is connected to a data source:
Object.IsConnected(PropertyName As String, (Returned) _
This method is typically used in conjunction with the GetConnectionInformation method, which is
described later in this section. For more information on the parameters for the IsConnected method, see
the IsConnected method topic of the iFIX Automation Interfaces Electronic Book.
42
Writing Scripts
The ParseConnectionSource method parses the Data Source name to determine if a connection to an
object's property exists. If a connection does exist, it returns the object that is connected to the
property, as well as its fully qualified name. It accepts complex expressions and returns individual data
sources for a complex expression:
Object.ParseConnectionSource(PropertyName As String, _
The following example parses the AI1.F_CV source to the VerticalFillPercentage property of Oval
Oval1 to determine the validity of the data source.
The ConnectedPropertyCount method returns the number of the object's properties that are
connected to a data source.
Object.ConnectedPropertyCount (1connectedPropertyCount _
As Long)
The following example lets you find out how many properties in the object Rect1 are connected to data
sources, and then converts that number into an integer.
Dim 1ConnectedCount as Long
Rect1.ConnectedPropertyCount 1ConnectedCount
In the above example, the number 4 might be returned, which indicates that four of Rect1's properties
are connected to data sources. You could use this number to retrieve the connections with the
GetConnectionInformation method described in the Retrieving Other Connection Information
43
Writing Scripts
section.
The GetConnectionInformation method retrieves information from an object, such as the property
that object is connected to, the full name of the data source, and all the source objects:
Object.GetConnectionInformation(Index As Long, (Returned) _
This method is typically used in conjunction with the IsConnected method described earlier. In this
example, notice the addition of the index parameter. You can get the index number with the
IsConnected method or the ConnectedPropertyCount method. See the iFIX Automation Interfaces
Electronic Book for more information on these methods.
Dim vtSourceObjects
Dim Tolerance
Dim DeadBand
Dim UpdateRate
If blnHasConnection Then
End If
44
Writing Scripts
Object.NumberOfTargets(NumberOfTargets As Long)
The DoesPropertyHaveTargets method determines if the object's property (as defined by the
PropertyName parameter) is being used as a data source and what object is using it:
Object.DoesPropertyHaveTargets(PropertyName As String, _
Index As Long)
The GetPropertyTargets method retrieves the target object(s) and the property that the target(s) is
connected to for the object's specified index number:
Object.GetPropertyTargets(Index As Long, (Returned) _
GetPropertyAttributes Method
The GetPropertyAttributes method retrieves a list of property attributes for the specified Data Item
object. For a tag reference, these are properties such as new alarm status and property range
information (EGU limits, list of strings alarm strings (HIHI, LOLO, etc.)). Each property queried may
have a different set of attributes. For more information on this method, refer to the iFIX Automation
Interfaces Electronic Book.
Object.GetPropertyAttributes(FullyQualifiedName As String, _
The following example fetches the attribute information for the HighEGU attribute of the AI1 block on
node NODE1.
Dim vtResults
Dim vtAttributes
Dim LoEGUval
45
Writing Scripts
strLoEGU = vtAttributes(0)
LoEGUval = vtResults(0)
In the above example, the variable strLoEGU will now hold the string "FIX32.NODE1.AI1.A_ELO"
and the variable LoEGUval will hold tag AI1's low EGU value.
CanConstruct Method
The CanConstruct method checks a data source reference for valid syntax. The CanConstruct method
must have the default data system defined as part of the object name. For example, the object name AI
would not work correctly.
Object.CanConstruct(ObjectName As String, (Returned)_
CanConstruct As Boolean)
The following example determines whether the datasource AI1 for NODE1 has valid syntax for the
Picture TestPicture.
Dim bCanConstruct As Boolean
Construct Method
The Construct method launches the Quick Add user interface and prompts you for information needed
to create the tag. If Status returns 0, then the tag has been created:
Object.Construct(ObjectName As String, (Returned) Status _
As Long)
The following example displays the QuickAdd user interface that prompts the user for the information
needed to create the tag NewAI1 for the Oval object Oval1 on node NODE1.
46
Writing Scripts
ValidateSource Method
PropertyName As String)
The following example validates the AI1 source for the Oval Oval1.
Syntax Description
47
Writing Scripts
Syntax Description
Object.InputValue Contains raw data from the data source which will be
transformed by the animation object.
Syntax Description
48
Writing Scripts
Syntax Description
Object.UseDelta Specifies whether to use the absolute or relative value to set the output
value range. The object will always start at the low output value.
Syntax Description
Object.DefaultOutputValue Specifies the value written to the object's property if the input
value is not found within the Lookup object table.
Object.ToggleSource Contains the toggle source string name. This applies to all
levels of a lookup object table. When the toggle source's
value is true, the Lookup object levels toggle between the
output value and the global toggle value. You set the global
toggle value with the Global Toggle property (for example,
setting the toggle source as blink on new alarm).
49
Writing Scripts
Syntax Description
Object.GlobalToggle Specifies the value that will be toggled to if the value of the
global toggle source is true.
Object.ToggleRate Specifies the rate at which the output of the Lookup object
toggles between output1 and output2. For example, in a color
table, this property is the blinking rate.
Object.GetLevel (iIndex, Gets the level properties for the specified level index of the
pInput1, pOutput1, [pInput2, Lookup object. Indexing begins at 1.
pOutput2])
50
Writing Scripts
Dim vtSourceObjects
lngIndex, lngStatus
If blnIsConnected Then
Rect1.Disconnect "ForegroundColor"
End If
End If
51
Writing Scripts
'animating.
".OutputValue"
End Sub
Similarly, you can create an Exact Match color table using the LookupExact method and the
ExactMatch property of an object. The following example shows you how.
Notice that, again, the example first checks that the object is connected in the first place, then proceeds
to manipulate the object's property based on that connection.
Dim vtSourceObjects
52
Writing Scripts
lngIndex, lngStatus
'property connection
If blnIsConnected Then
Rect2.Disconnect "ForegroundColor"
End If
End If
53
Writing Scripts
LookupObject.ExactMatch = True
'animating.
".OutputValue"
End Sub
For more information on data sources, refer to the Creating Pictures manual. For information on
changing data sources at run-time, refer to the Changing Data Sources section.
Syntax Description
54
Writing Scripts
The following script is intended for the OK button's Click event. The script creates an animation
object, connects the animation object to the data point, and then connects the animation object to the
selected shape. See the Creating Pictures manual for more information on Animation objects.
Dim i As Integer
55
Writing Scripts
Dim vtSourceObjects
'the picture.
Set CurrentObject = _
Application.ActiveDocument.Page.SelectedShapes.Item(1)
'method.
If blnHasConnection Then
CurrentObject.GetConnectionInformation lngIndex, _ 0
strPropertyName, strExpression, _
strFullyQualifiedExpression, vtSourceObjects
56
Writing Scripts
End If
End If
'the data source object that the user entered in the Expression
'up.
ExpressionEditor1.RefreshRate, ExpressionEditor1.DeadBand, _
ExpressionEditor1.Tolerance
Exit Sub
End If
RotateObject.LoInValue = Val(txtLoIn.Value)
RotateObject.HiInValue = Val(txtHiIn.Value)
57
Writing Scripts
RotateObject.LoOutValue = Val(txtMinAngle.Value)
RotateObject.HiOutValue = Val(txtMaxAngle.Value)
Rotating a Group
To rotate a group using scripting, please use the following preferred method listed in the steps below.
1. Create a variable object that is used to store the rotation angle of the group.
2. Animate the group's rotation angle using that variable's current value as the source of the
animation.
3. Set the current value of the variable using the script instead of changing the rotation angle of
the group directly.
bUp = True
End Sub
Dim o As Object
58
Writing Scripts
Set o = Me.FindObject("RotationAngle")
dVal = o.CurrentValue
If bUp Then
dVal = dVal + 5
If dVal = 45 Then
bUp = False
End If
Else
dVal = dVal - 5
If dVal = 0 Then
bUp = True
End If
End If
o.CurrentValue = dVal
End Sub
59
Manipulating Pictures
This chapter provides source code examples that show how to manipulate iFIX pictures using VBA.
This section also describes some important characteristics of using VBA scripting in your pictures. It
includes the following sections:
• Understanding Picture Events
• Automatically Starting a Picture
• Managing Multiple Displays
• Changing Displays Using Global Subroutines
• Closing Pictures with Active Scripts
• Using the Workspace Application Object
After reading this section, you will be able to do the following tasks entirely through VBA scripts:
• Manage multiple displays
• Change displays using global subroutines
Run-time Close
61
Writing Scripts
If you open a picture with an OpenPicture subroutine, the open events (Initialize and Activated)
execute immediately. However, if the OpenPicture call is inside looping or branching structure (such
as a FOR loop or an IF statement) then the open events do not fire until the OpenPicture script
completes.
Conversely, if you close a picture with a ClosePicture subroutine, the Close event of the picture being
closed never fires because the picture is removed from memory before its script has a chance to run.
Pictures also execute Activated and Deactivated events as you switch from one picture to another. The
Activated event occurs whenever of picture gains focus. The Deactivated event executes when a
picture loses focus. For example, suppose you have two pictures open and the first picture, Picture1,
has focus. When you select the second picture, Picture2, Picture1 executes the Deactivated event and
Picture2 executes the Activated event. When you switch back, Picture2 executes the Deactivated event
and Picture1 executes the Activated event.
Since the main picture has to be a certain size and position in the run-time environment, you may want
to create a toolbar button to create pictures of the same size to fill the main process picture area. To do
62
Writing Scripts
so, you must first create a picture area, navigation (or toolbar) area, and other run-time areas that are
reserved as "special pictures." After creating these pictures, write down the following coordinates of
the pictures so it will be easier to enter them into the script:
• Window top
• Window left
• Document height
• Document width
These coordinates can be found in the Properties window for the picture. See the Creating Pictures
manual for more information on picture coordinates.
When opening iFIX pictures through scripts, you may want to remove any unwanted scroll bars by
executing the FitWindowToDocument method, which is also illustrated in this code sample.
Let's take a look at the toolbar script. Wherever possible, comments are provided to help you
understand that particular part of the script. These bold-faced comments will appear by default as green
text when pasted into the VBA code window. Comment colors are configured in the VBA Option
dialog.
With iPage
.DocumentHeight = 51.3
.DocumentWidth = 100.44
.FitWindowToDocument
.windowtoppercentage = 7.03
63
Writing Scripts
.windowleftpercentage = 0#
.titlebar = False
End With
1. From the Proficy iFIX WorkSpace, in Ribbon view, on the Insert tab, in the Objects/Links
group, click Objects/Links and then click Bitmap.
- Or -
In Classic view, on the Insert menu, click Bitmap to insert a bitmap into your iFIX picture.
2. Right-click the bitmap and select Button Styles, PushButton from the pop-up menu. A 3D
effect will appear around the bitmap to give it the appearance of a button.
3. Optionally, you can configure a second bitmap to be displayed when the button is depressed.
To do this, right-click the bitmap and select Load Image, Secondary. You can also configure a
ToolTip by entering the desired text for the ToolTip into the Description property of the
bitmap and setting the EnableTooltips property to TRUE.
The top toolbar is actually a separate picture with no titlebar. Clicking a button in this area changes
focus and changes what is known in VBA as the ActiveDocument. To be sure that the correct picture is
operated on when you click the toolbar button, you should first set the active document.
64
Writing Scripts
("MainPicture"), when more than one main picture is opened at the same time. See the Creating
Pictures manual for more information on aliases.
To create a global variable object to hold the string for the current active picture:
1. In the Proficy iFIX WorkSpace system tree's Globals folder, right-click the User icon, and
select Create Variable from the pop-up menu.
2. Set the Name property to CurrentPicture and the VariableType property to 8 - vtString. The
system tree should look like the following:
Once you have created the variable, add the following code to the Activate method of the main picture
to set a Global variable:
Private Sub CFixPicture_Activated()
user.CurrentPicture.CurrentValue = Me.FullyQualifiedName
End Sub
The Global variable lets you know which main picture has focus so the toolbar can act on it. Now you
can add the following script to the bitmap object by right-clicking it and selecting the Edit Script
command from the pop-up menu:
Dim PicObj As Object
'If the document that is open has the same name as the
65
Writing Scripts
PicObj.active = True
'active picture.
AcknowledgeAnAlarm
Exit Sub
End If
Next PicObj
The VBA scripts that make the command buttons operational are provided in this section. The use of
aliases (in the following script, Line is the name of an alias) gives the script control over the opening
and closing of displays, regardless of the exact picture names. Each time the operator selects the
appropriate button, the script closes any picture with an alias of Line, and reassigns the alias to the
opened picture.
66
Writing Scripts
ClosePicture "Line"
End Sub
ClosePicture "Line"
End Sub
ClosePicture "Line"
End Sub
ClosePicture "Line"
End Sub
The following script performs the same function using the ReplacePicture subroutine, without using
aliases. With ReplacePicture, all pictures display in the same window:
ReplacePicture ("Line1")
End Sub
ReplacePicture ("Line2")
End Sub
67
Writing Scripts
ReplacePicture ("Line3")
End Sub
ReplacePicture ("Line4")
End Sub
68
Creating Global Scripts
iFIX includes two global pages that allow you to store public objects, methods, forms, and variable
objects so they can be accessed from anywhere within your system.The FactoryGlobals page contains
the iFIX subroutines and all of their supporting variables, forms, and functions. The FactoryGlobals
file is write-protected to maintain the integrity of these scripts. See the Global Subroutines section for
more information on the iFIX subroutines that are stored in the FactoryGlobals page.
The User page is the location where you can put your own objects, methods, forms, and variables that
you want to use globally.
Since you can access the items that you define as public in the User page from anywhere in the
system, make sure that what you enter is really what you want to expose. If you create a global public
variable, remember that it can be changed from any script at any time.
This section provides examples of the items that you might want to include in your User page,
including:
• Variable objects
• Threshold tables
• Procedures (VBA subroutines and functions)
• Forms
69
Writing Scripts
FIX32 Variable Syntax iFIX Object Syntax iFIX VBA Syntax Description
70
Writing Scripts
FIX32 Variable Syntax iFIX Object Syntax iFIX VBA Syntax Description
object.
71
Writing Scripts
FIX32 Variable Syntax iFIX Object Syntax iFIX VBA Syntax Description
72
Writing Scripts
FIX32 Variable Syntax iFIX Object Syntax iFIX VBA Syntax Description
format in the
Regional and
Language
Options in
the Control
Panel.
73
Writing Scripts
To create a global threshold table that is used for all current alarms in the system:
1. In the Proficy iFIX WorkSpace system tree, double-click the Globals folder.
2. Right-click the User icon and select Create Threshold Table from the pop-up menu. The
Custom Lookup Table dialog box appears as shown in the following figure.
3. Keep the default values of the dialog box and click OK. A threshold table icon appears under
the User icon.
1. In the Proficy iFIX WorkSpace system tree, right-click the new threshold table's icon, and
select Property Window from the pop-up menu.
2. Enter a value for the Name property. If you are creating a global threshold table that is used
for all current alarms in the system, enter CurrentAlarmThresholds.
Once you have named your threshold table, you can make connections from iFIX objects to this table.
The following procedure provides an example of how to connect an object, in this case an oval, to a
global threshold table named CurrentAlarmThresholds.
1. Create an oval.
2. Click the Foreground Color Expert button.
74
Writing Scripts
End Sub
8. When you click the rectangle in the run-time environment, the message box that was stored in
the Project_User page appears.
75
Accessing Real-time Data
iFIX gives you the flexibility to access all kinds of data to perform your scripting applications. This
chapter details how to access real-time data through various methods. The examples show you how to
use the Data System OCX to perform group reads and writes and how to write to a database tag.Refer
to the following sections for more details:
• Using the Data System OCX for Group Reads and Writes
• Reading from and Writing to a Database Tag
Using the Data System OCX for Group Reads and Writes
The Data System OCX (FixDataSystems.ocx) is a logical control that gives you flexible read and write
capability, allowing you to perform group reads and writes to a database. Typically, performing a read and
write through scripting involves the following steps:
The following example illustrates how to use the Data System OCX to create a group of database tags
and perform a group read and group write on them.
The following example writes a value of 50 to a group of database tags:
77
Writing Scripts
'Add all the Tank tags to the Data System OCX's Data Item
'collection. You can add or delete groups without affecting
'the order of the group should the position of an item
'change. This is achieved by specifying a group name
'("TankGroup")rather than listing item numbers.
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK1.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK2.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK3.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK4.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK5.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK6.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK7.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK8.F_CV"
FDS.Groups("TankGroup").DataItems.Add "FIX32.MYNODE.TANK9.F_CV"
FDS.Groups("TankGroup").DataItems.Add _
"FIX32.MYNODE.TANK10.F_CV"
'Read all of the data items that you added to the Data System
'control.
FDS.Groups("TankGroup").Read
'If the value of each tag is not 50, then set it to 50.
For Each DIItem in FDS.Groups("TankGroup").DataItems
If DIItem.Value <> 50 Then
DIItem.Value = 50
End If
Next
78
Writing Scripts
'Read DataGroup1
FDS.Groups.Item("DataGroup1").Read
'Add the item, set it's value and write the group
g2.DataItems.Add("Fix32.MYNODE.AI2.F_CV")
g2.DataItems.Item(1).Value = x+1
g2.Write
End Sub
For more information on using the Data System OCX, including its related properties and methods,
refer to the DataSystem OCX object topic of the iFIX Automation Interfaces Electronic Book.
79
Writing Scripts
NOTES:
• An unsigned write occurs when a database tag is configured for electronic signature, but you
write a value directly to that tag without capturing a signature. If you are working in a secure
environment with the Electronic Signature option enabled, you must be aware of the impact of
unsigned writes to the process database.
• Unsigned writes can originate from scripts. Refer to the Implications of Database Writes With
Electronic Signature section of the Using Electronic Signatures manual for detailed
information.
In this example, a value of 50 is written to the database tag FIX32.NODE.AI1.F_CV. Because of the
restrictions enforced by VBA naming conventions, this is not the recommended method for writing
values through VBA scripting (see the VBA Naming Conventions section). The easiest methods for
reading and writing values through VBA scripting are by using the WriteValue and ReadValue
subroutines. These subroutines are described in more detail in the next section.
Exit Sub
If you omit the second parameter, the WriteValue subroutine writes a value of 60 to the first
connection of the selected object in the run-time environment. For example, let's say that you have a
rectangle selected in your picture, and that rectangle has a VerticalFillPercentage animation tied to the
tag FIX32.MYNODE.AO3.F_CV. When you click a push button containing the following script:
Private Sub CommandButton1_Click()
WriteValue "60"
Exit Sub
80
Writing Scripts
Dim vtAnimationObjects
lIndex, lStatus
strDataSourceName= vtAnimationObjects(0).Source
Set objDataTag = _
System.FindObject("FIX32.MYNODE.AI1.F_CV")
81
Writing Scripts
'equal to 70.
ObjDataTag.Value = 70
End Sub
82
Accessing Data from a Relational Database
iFIX not only gives you the ability to access real-time data, but also has the flexibility to access data
from a relational database. This chapter shows you how to access data from a relational database using
ActiveX Data Objects (ADO).
The chapter also discusses how to effectively query an SQL database. You can also perform this task
using VisiconX, which is now included as an integral part of iFIX.
For more information on VisiconX, see the Using VisiconX manual. For examples of how VisiconX is
used in a sample system, refer to the Using the iFIX Sample System section of the Understanding iFIX
manual.
83
Writing Scripts
'General Declarations
conODBC.Open "driver= _
adLockPessimistic, adCmdText
Exit Sub
ErrorHandler:
HandleError
84
Writing Scripts
End Sub
This example builds upon the previous example for the population of ADORS. It assumes a flexgrid
already exists in a picture.
InitGrid
iRow = 0
iRow = iRow + 1
MSFlexGrid1.Row = iRow
For iCol = 0 To 5
MSFlexGrid1.Col = iCol
MSFlexGrid1.Text = adoRS(iCol)
Next iCol
85
Writing Scripts
adoRS.MoveNext
Wend
RecipeCount.Value = Str(iRow)
Exit Sub
ErrorHandler:
HandleError
End Sub
Exit Sub
End If
adoRS!Batch_Size = CLng(BatchSize.Value)
Milk_Quan = CLng(MilkQuan.Value)
adoRS!Choc_Quan = CLng(ChocQuan.Value)
adoRS!Mix_Time = CLng(MixTime.Value)
adoRS!Milk_Type = CLng("1")
adoRS!Recipe_Name = RecipeName.Value
86
Writing Scripts
Exit Sub
ErrorHandler:
Exit Sub
End If
HandleError
End Sub
Exit Sub
End If
adoRS.MoveNext
87
Writing Scripts
Wend
adoRS!Batch_Size = CLng(BatchSize.Value)
adoRS!Milk_Quan = CLng(MilkQuan.Value)
adoRS!Choc_Quan = CLng(ChocQuan.Value)
adoRS!Mix_Time = CLng(MixTime.Value)
Exit Sub
ErrorHandler:
HandleError
End Sub
End Sub
88
Writing Scripts
For more information on ADO, refer to the Advanced Topic: Using SQL section.
89
Working in the Run-time Environment
iFIX VBA allows you to dynamically control your objects and pictures while you are working in the
run-time environment. This chapter focuses on how you can script your applications to perform a
variety of functions at run time, such as:Changing data sources.
• Changing properties in objects, or in pens of a chart.
• Entering data in global forms.
To connect an AI tag to the Horizontal Fill Percentage of a rectangle when you click it:
Rect1.Connect "HorizontalFillPercentage",
_ "Fix32.Thisnode.AI.F_CV", lstatus
91
Writing Scripts
Before you click the rectangle, it is solid. After you click it, the rectangle starts to fill based on the AI
tag's value. You have dynamically connected the rectangle's fill level to the database tag.
As we discussed in the Working with iFIX Objects chapter, there are three different types of animation
objects — Lookup, Linear, and Format. The example below shows you how to set an object, and
change the source of the animation object that is connected to it while you are in the run-time
environment.
To set an object and change the source of the animation object that is connected to it:
1. Create an AI block (AI1) with RA as the I/O address, and another AI block (AI2) with RG as
the I/O address.
2. Create two Data links. Connect one Data link to AI1, and connect the other to AI2.
3. Add a rectangle, and animate its Foreground Color (a Lookup object) using AI1 as the data
source.
4. Now animate the fill of the rectangle (a Linear object), and use AI1as the data source.
5. Edit the rectangle's Click event.
6. Enter the following code:
Dim AllObj As Object
Set AllObj = _
Application.ActiveDocument.Page.ContainedObjects
Count = AllObj.Count
ObjCount = SingleObj.ContainedObjects.Count
92
Writing Scripts
Select Case _
SingleObj.ContainedObjects._
Item(ObjCount).ClassName
'FIX32.THISNODE.AI2.F_CV
Case "Lookup"
SingleObj.ContainedObjects._
Item(ObjCount).Source = _
"Fix32.Thisnode.AI2.F_CV"
'FIX32.THISNODE.AI2.F_CV
Case "Linear"
SingleObj.ContainedObjects._
Item(ObjCount).Source = _
"Fix32.Thisnode.AI2.F_CV"
End Select
ObjCount = ObjCount - 1
Wend
End If
Count = Count - 1
Wend
Next SingleObj
93
Writing Scripts
To change the data source of a Data link using the Format object:
1. Create an AI block with RA as the I/O address, and a DO block in the database.
2. Create a Data link and connect it to the AI block.
3. Right-click the Data link and select Edit Script from the pop-up menu.
4. Enter the following code in the Data link's Click event:
DataLink1.ContainedObjects.Item(1).Source = _
"Fix32.Thisnode.DO.F_CV"
94
Writing Scripts
5. Initialize the DO block, switch to the run-time environment, and click the Data link.
The caption of the Data link changes to the current value of the DO block.
Count = obj.Count
'Loop through all of the objects in the picture to find 'any that are
Event objects.
obj.Item(Count).Source = "Fix32.ThisNode.DO.F_CV"
obj.Item(Count).Source
End If
Count = Count – 1
Wend
7. Switch to the run-time environment and click the rectangle. The message box appears stating
that the source has changed.
95
Writing Scripts
To search for AO data sources in a picture and replace with them AI data sources:
Success
This example uses a form that you create in User Globals. The following figure shows how it should
appear in the run-time environment.
96
Writing Scripts
This example contains a UserForm frmListEntry and a module UGSubs, both of which are located in
Project_User. The name of the picture is LISTENTRY1.GRF.
Option Explicit
'Get the data source and any passed-in items for the list.
strDataSource = DataSource
End Sub
97
Writing Scripts
Unload Me
End Sub
DataObj.Value = EntryBox.Value
Unload Me
Exit Sub
ErrorHandler:
End Sub
Option Explicit
'Complete to work.
98
Writing Scripts
End Sub
UGSubs.GetListForm
'Pass in the tag to control and load the form list with
UGSubs.ListForm.SetupTheData _
"Fix32.BATCH1.BATCH-RECIPENAME.A_CV", _
UGSubs.ListForm.Show
Exit Sub
ErrorHandler:
HandleError
End Sub
99
Working with the Scheduler and the
DoEvents Function
This section briefly discusses the Scheduler application and the VBA DoEvents function. It includes
the following topics:
• Scheduler
• DoEvents Function
• Using Timers in place of DoEvents
• Using Scripts with Time-based Entries
• Using Scripts with Event-based Entries
For more information on the Scheduler application, refer to the Mastering iFIX manual. For more
information on the DoEvents function, refer to the iFIX Automation Reference. The examples that
appear later in this section illustrate how to work with the two Scheduler objects: Timer and Event.
Scheduler
There are certain tasks that you may want to perform at a specified time or interval, or when a change
occurs in a database value or in any OPC data server value. For example, you may want to run a script that
generates a report at the end of every shift or replaces the currently-displayed picture when a database point
exceeds a certain value.
The Scheduler allows you to create, edit, monitor, and run both types of actions as scheduled entries.
In the Scheduler, you define the time or event that triggers a scheduled entry, and the action, referred
to as an operation, that you want to occur.
The Scheduler is useful because it allows iFIX to schedule time- or event-based scripts to run as
background tasks. This makes it ideal for reducing overhead, since you do not have to use VBA for
monitoring purposes. Because schedules can be run as background tasks, they have their own VBA
thread. This allows you to have two scripts running at the same time; one in the background and one in
the active application.
If you will be writing scripts from a background task that will be manipulating objects or pictures in
the Proficy iFIX WorkSpace, you must first get a pointer to the WorkSpace application. The script
below shows how you can use the GetObject method to do this:
Dim App As Object
Once you have the pointer to the WorkSpace application, you can use the App object in your code to
represent the Application object in the Proficy iFIX WorkSpace.
See the Mastering iFIX manual for more information on the FixBackgroundServer task and the
Scheduler application.
101
Writing Scripts
DoEvents Function
Within iFIX, VBA functions as a single-threaded application. The system can initiate more than one script;
however, only one script can be running at any one time. When an event triggers a script, it is placed in a
queue. Each script in the queue is executed in the order in which it is received once the previous script has
run to completion. For this reason, scripts that loop and scripts that take a long time to run can delay
execution of the scripts behind them in the queue. The DoEvents Function allows the operating system to
process events and messages waiting in the queue and enables an event to yield execution so that the
operating system can process other UI events. Use the VBA DoEvents function in scripts that take a long
time to run.
WARNING: Any time you temporarily yield the processor within an event procedure, make sure the
procedure is not executed again from a different part of your code before the first call returns; this
could cause unpredictable results. In addition, do not use DoEvents if other applications could
possibly interact with your procedure in unforeseen ways during the time you have yielded control.
See the Visual Basic for Applications Help file for more information, including an example of the
DoEvents function.
The following knowledge base articles, prepared by Microsoft and located on the Microsoft web site,
provide useful information on DoEvents:
• Q118468
• DoEvents Function
• Using DoEvents
For I = 0 to 10000
DoEvents
End If
'Do Something
Next I
If your code is tied to an event, your code may be executed again before DoEvents returns. If the code
is operating on global data or data that exists outside the scope of the script, you could corrupt your
own data by reentering the routine.
You can solve this problem by using timers in place of DoEvents to execute portions of the code.
The following script outlines the solution:
102
Writing Scripts
'loop.
End Sub
FixTimer.StopTimer
End Sub
StopRoutine
End Sub
StartRoutine
End Sub
103
Writing Scripts
'This variable ensures that another timer event doesn't execute 'the
routine
If (iAlreadyHere = 1) Then
Exit Sub
End If
iAlreadyHere = 1
Dim I As Integer
'Do Something
IndexCount = i + 1
End If
Next i
iAlreadyHere = 0
End Sub
Using timers to execute portions of code allows VBA, the picture, and global variables to be in a
predictable state while executing your VBA script.
104
Writing Scripts
The following example periodically checks the amount of available hard disk space. If the amount of
disk space gets too low, it triggers an alarm in the iFIX database. The OnTimeOut event occurs at an
interval defined in the properties of the CheckDiskSpace event.
As Long) As Long
105
Writing Scripts
'as the free space. You need to change this parameter to match
lpRootPathName = "c:\"
lAnswer = GetDiskFreeSpace(lpRootPathName, _
lpSectorsPerCluster, lpBytesPerSector, _
lpNumberOfFreeClusters, lpTotalNumberOfClusters)
"0.00")
Fix32.NODE1.lowdiskspacealarm.f_cv = 1
Else
Fix32.NODE1.lowdiskspacealarm.f_cv = 0
End If
End Sub
106
Writing Scripts
'with the Event's data source and then show the form.
107
Writing Scripts
'in Scheduler.
frmDownTime.InitializeDataSource _
(Line1Packer1DownTime.Source)
frmDownTime.Show
End Sub
'Place the following code directly in the form you create and 'set a
reference to Microsoft DAO 3.X Object Library. See 'Visual Basic Editor
Help for details on setting references.
sDataSource = DataSource
108
Writing Scripts
End Sub
txtDownTimeReasonFour.Enabled = True
txtDownTimeReasonFour.SetFocus
End Sub
'When the form gets activated, set the first option to true
optDownTimeReasonOne.Value = True
End Sub
'When the user selects OK, store which reason they chose.
DownTimeReason = optDownTimeReasonOne.Caption
DownTimeReason = optDownTimeReasonTwo.Caption
DownTimeReason = optDownTimeReasonThree.Caption
DownTimeReason = txtDownTimeReasonFour.Text
Else
downtime event"
109
Writing Scripts
txtDownTimeReasonFour.SetFocus
End If
End If
Call AddDownTImeEventData(DownTimeReason)
Unload Me
End Sub
'updates it.
'This database has not been provided and will need to be created
Dim db As Database
"\downtime.mdb")
'Create a recordset.
Dim rs As Recordset
110
Writing Scripts
TimeDate = Now
rs.AddNew
rs.Fields(1) = TimeDate
rs.Fields(2) = TimeDate
rs.Fields(3) = sDataSource
rs.Fields(4) = DownTimeReason
rs.Fields(5) = Fix32.NODE1.downtimeperiod.f_cv
rs.Update
End Sub
111
Manipulating Charts
This chapter shows how to use VBA scripts to manipulate charts so they display real-time and
historical data for a given process value at the click of a button. For examples of using VBA within the
WorkSpace, iFIX has a Sample System which includes examples of VBA scripting. Please refer to the
Using the iFIX Sample System section of the Understanding iFIX manual for information on using the
Sample System.The examples in this chapter show how to perform the following chart tasks through
scripting:
• Switch from real-time data to historical data at run time.
• Scroll historical data in a chart.
• Automatically update historical data in a chart.
• Set chart and pen properties at run time.
• Add a pen.
• Delete a pen.
• Change the pen data sources.
• Passing in external data to a pen.
• Change a chart's duration.
• Change a chart's start and end times.
• Zoom a pen.
• Pause a real-time chart.
For this example to work properly, you must have a previously-configured Extended Trend tag and
you must have already successfully trended this tag's data in a chart. Also, you will need to add three
command buttons to your iFIX picture. The figure below shows how the picture might look.
113
Writing Scripts
If Chart1.Pens.Item(1).ShowLine = 1 Then
114
Writing Scripts
'pen visible.
Chart1.Pens.Item(1).ShowLine = False
Chart1.Pens.Item(2).ShowLine = True
Chart1.CurrentPen = 2
'legend visible.
Chart1.Pens.Item(1).Legend.Visible = False
Chart1.Pens.Item(2).Legend.Visible = True
End If
Chart1.ScrollBack
End Sub
'not available.
If Chart1.Pens.Item(1).ShowLine = 1 Then
Exit Sub
End If
Chart1.ScrollForward
115
Writing Scripts
Chart1.Pens.Item(2).ShowLine = False
Chart1.Pens.Item(1).ShowLine = True
Chart1.CurrentPen = 1
Chart1.Pens.Item(1).Legend.Visible = True
Chart1.Pens.Item(2).Legend.Visible = False
End If
End Sub
Example: Creating Buttons that Scroll Back and Scroll Forward through
Historical Data and Set Current Time
Private Sub CommandButton1_Click() 'Scroll back button.
Chart1.ScrollBack
End Sub
Chart1.ScrollForward
116
Writing Scripts
End Sub
'This button manually sets the chart to the current time and
Chart1.EndTime = Now
Chart1.RefreshChartData
End Sub
Chart1.EndTime = Now
Chart1.RefreshChartData
End Sub
For more information on how charts scroll, refer to the Trending Historical Data manual.
117
Writing Scripts
• StartDateMode
• StartTimeMode
• TimeBeforeNow
NOTE: Run-time changes that you make to the configuration properties of a chart revert back to the
original settings once the display is closed.
118
Writing Scripts
• DaysBeforeNow
• TimeBeforeNow
• StartTimeType
• StartDateType
NOTE: Run-time changes that you make to the configuration properties of a Pen revert back to the
original settings once the display is closed.
119
Writing Scripts
• AutoScaleDisplayLimits • DaysBeforeNow
• Duration • EndTime
• FixedDate • FixedTime
• GetDuration • GetInterval
• GetTimeBeforeNow • HorizontalGridColor
• HorizontalGridStyle • Interval
• NumberofHorizontalGridLines • NumberofVerticalGridLines
• ScrollBack • ScrollForward
• SetDuration • SetInterval
• SetTimeBeforwNow • ShowDate
• ShowHorizontalGrid • ShowVerticalGrid
• ShowLegend • ShowTimeAxis
• ShowValueAxis • StartTimeMode
• ShowTimeAxisTitle • ShowValueAxisTitle
• StartDateMode • StartTime
• TimeAxisNumLabels • ValueAxisNumLabels
• TimeAxisNumTicks • ValueAxisNumTicks
• TimeAxisTitle • ValueAxisTitle
• VerticalGridColor • VerticalGridStyle
Adding a Pen
To add a new pen to a chart, use the following
syntax: Chart.AddPen("Fix32.NODE.TAG.F_CV")
In the configuration environment, adding a pen will expand the chart by the height of the legend line.
At run-time, the chart does not expand. Instead, the plot area shrinks.
Deleting a Pen
Deleting a pen is easy. For example, if you have a chart with three pens and you want to delete the
second, use the following syntax:Chart1.DeletePen(2)
120
Writing Scripts
The deletion will not work if there is a script referencing the name of the pen you are trying to delete.
For example:
Pen2.PenLineColor = 255
Chart1.DeletePen(2)
This deletion will fail because there is a script explicitly using Pen2. Instead, use the following script
sequence:
Private Sub Rect2_Click()
pPen.PenLineColor = 255
Chart1.DeletePen (2)
End Sub
If you delete all your pens, you will create a blank chart. To add the pen back into the chart, open the
Chart Configuration dialog box, or use the AddPen method in VBA.
NOTE: If you are deleting a single pen, and you want to add another, change the pen source via
Pen.Source = "Fix32.Node.Tag.f_cv". This will give your chart better performance.
Pen1.Source = "Fix32.Area1.PumpTemp1.F_CV"
End Sub
Pen1.Source = "Fix32.Area1.PumpTemp1-History.T_DATA"
End Sub
Pen1.Source = "Hist.Area1.PumpTemp1.F_CV"
Chart1.RefreshChartData
121
Writing Scripts
End Sub
The previous example allows you to easily switch between different types of data. This next example
changes the data source of a pen by editing an object's Click event.
Count = Obj.Count
ChartCount = Obj.Item(Count).ContainedObjects.Count
Set ChartObj = _
Obj.Item(Count).ContainedObjects._
Item(ChartCount)
ChartObj.Source = "Fix32.Thisnode.AI.F_CV"
End If
ChartCount = ChartCount - 1
Wend
End If
Count = Count - 1
Wend
122
Writing Scripts
("c:\winnt\ChartData.mdb")
dbOpenDynaset)
record_var.MoveLast
count = record_var.RecordCount
record_var.MoveFirst
123
Writing Scripts
Dim i As Integer
For i = 0 To count - 1
value(i) = record_var.Fields("Value").value
times(i) = record_var.Fields("Time").value
quality(i) = record_var.Fields("Quality").value
record_var.MoveNext
Next i
db_var_name.Close
vtVal = value
vtDate = times
vtQual = quality
End Sub
The following is sample code for the SetPenDataArray method with hardcoded values. You can use
this code to test or show the functionality of this method. For this example to complete, the Quality(x)
must be equal to 192.
124
Writing Scripts
Dim i As Integer
'Please note that this example can handle a maximum of 500 points.
'following declarations.
record_var.MoveLast
iCount = record_var.RecordCount
record_var.MoveFirst
125
Writing Scripts
For i = 0 To iCount - 1
Value(i) = record_var.Fields("Value").Value
Times(i) = record_var.Fields("Time").Value
Quality(i) = record_var.Fields("Quality").Value
record_var.MoveNext
Next i
db_var_name.Close
dVal = Value
dtDate = Times
lQual = Quality
End Sub
The end time will be calculated as the start time plus the duration. If you are using historical pens, you
can fetch the data again by using:
Chart1.RefreshChartData
126
Writing Scripts
The end time is calculated as the start time plus the duration.
Or use:
Chart1.EndTime = #10/31/98 12:30:00 PM#
The start time is calculated as the end time minus the duration.
If you are using historical pens, you can fetch the data again by using:
Chart1.RefreshChartData
Zooming
If the chart is selectable, you may use the mouse to enclose an area in the chart to zoom to in a
rectangle selector. Alternately, you can use scripts to set the pen Hi and Lo limits to zoom:'Original
limits are 0 to 100, but data is fluctuating
Pen1.HiLimit = 85
Pen1.LoLimit = 55
Pen1.HiLimit = 100
Pen1.LoLimit = 0
Chart.ResetToOriginal
'Or you can also call this method, which would set the
Chart1.AutoScaleDisplayLimits
127
Writing Scripts
Chart1.Pause
'Now, to Resume:
Chart1.Resume
Chart1.Timeout = 60
Chart1.Pause
Keyboard Accelerators
The following keyboard accelerators are available to a selectable chart:
Ctrl + Left Arrow Moves the time cursor one pixel to the left.
Ctrl + Right Arrow Moves the time cursor one pixel to the right.
Shift + Ctrl + Left Arrow Moves the time cursor ten pixels to the left.
Shift + Ctrl + Right Arrow Moves the time cursor ten pixels to the right.
Ctrl + Down Arrow Selects the previous pen to be the current pen.
128
Writing Scripts
Using RefreshChartData
When using historical pens, if any of the time parameters change (StartTime, EndTime, Duration), you
must call the method Chart.RefreshChartData in order to fetch the new data. If you are using
ScrollForward and ScrollBack, calling RefreshChartData is not necessary.
129
Creating Custom Dynamos
This chapter provides an example for creating your own custom Dynamo object and Dynamo set. Once
you become more comfortable building Dynamo objects, you can learn quite a bit about writing VBA
scripts that work with iFIX by examining the scripts behind the Dynamo objects.The following section,
Creating a New Custom Dynamo, displays the actual example.
NOTE: In iFIX Dynamo sets, Dynamo objects are assigned their own properties with Get and Set
functions and subroutines. This is the methodology we suggest for building complex Dynamo objects.
9. In the Dynamo Name field, enter a name, if you do not want to use the default name.
10. Optionally, in the Object Description field, enter a description for the object.
11. In the User Prompt field, enter a prompt such as FillColor.
NOTES:
• Ensure you enter a value here. If you do not enter a value, the user will not be shown the
value in a user prompt, and as a result not have the option of changing it later. However,
you can access this value manually from the Property window.
• If you added multiple animations in this Dynamo object and you wanted them to all use
the same value, enter the same name in all User Prompt fields. This results in one user
prompt that changes all animations.
12. Click OK.
1. Right-click the Dynamo object and select Edit Script from the pop-up menu.
131
Writing Scripts
2. In the Microsoft Visual Basic Editor, on the Insert menu, select UserForm.
3. If the Properties window is not already displayed, on the View menu, select Property
Window.
4. In the Properties window, change the Name property of the form to frmDyn1.
5. On the Tools menu, click Additional Controls.
6. Select the iFIX Expression Editor Control and click OK.
7. Select the Expression Editor control on the toolbox and add it to the form.
8. Add a Command button on the form.
9. Right-click the Command button and select View Code from the pop-up menu.
10. Enter the following script:
frmDyn1.hide
11. Select "General" from the Object Drop Down List (in the upper left of the Code Window).
12. Enter the following script:
'FormVersion: 1.0
frmDyn1.Show
"AnimatedVerticalFillPercentage")
FillObj.Source = frmDyn1.ExpressionEditor1.EditText
End Sub
16. Save your project and close the Microsoft Visual Basic Editor.
1. In the Proficy iFIX WorkSpace, in Ribbon view, on the Home tab, in the New group, click
Dynamo Set.
- Or -
132
Writing Scripts
133
Working with iFIX Security
The examples in this chapter illustrate how to use VBA scripts that work in conjunction with iFIX
Security. Refer to the following sections:Using the Login Subroutine
• Getting User Information
You can read more about iFIX Security in the Implementing Security manual.
strPath = System.ProjectPath
Exit Sub
ErrorHandler:
HandleError
End Sub
135
Writing Scripts
MsgBox "Login Name: " & UserID & vbCr & "Full Name: " _
& UserName & vbCr & "Clearance Level: " & GroupName
End Sub
136
Creating Tag Groups
The examples in this chapter illustrate how to use VBA scripts to create and use tags. It includes the
following sections:Creating the Tag Group File Object
• Retrieving Tag Group Data
• Modifying Tag Group Data
• Manipulating Tag Groups
For more information on tag groups, refer to the Creating Pictures manual.
set TGD = _
CreateObject("TagGroupDefinitionInterfaceDll.TagGroupDefinitionInterface"
)
137
Writing Scripts
Set TGD = _
CreateObject("TagGroupDefinitionInterfaceDll._
TagGroupDefinitionInterface")
'you need to have a Tag Group file named test or you replace
'the "test" parameter with the name of your tag group file.
DescriptionList
'Create the tag group file object and save modified tag group file
Set TGD = _
CreateObject("TagGroupDefinitionInterfaceDll._
138
Writing Scripts
TagGroupDefinitionInterface")
TGD.UpdateDefinition "Test", 4, TokenList, ReplacementList, _
DescriptionList
Set TGD = Nothing
FileName = "Test"
'deletes the specified file form the hard drive. Use with
'caution.
PicPath = System.PicturePath
139
Writing Scripts
End If
If Size = 0 Then
Exit Sub
End If
sSubstitutions(Counter) = Temp$
Next Counter
vaSubstitutions = sSubstitutions
vaDescriptions = sDescriptions
Set TGF = _
CreateObject("TagGroupDefinitionInterfaceDll_
.TagGroupDefinitionInterface")
vaSubstitutions, vaDescriptions
140
Index
A ClosePicture ......................................................66
accessing closing pictures .................................................66
databases....................................................... 83 code
real-time data ................................................ 77 compiling ......................................................17
ActiveX Data Object model ............................. 83 cutting and pasting ........................................26
adding a pen.................................................... 120 saving............................................................17
ADO ................................................................. 83 testing ...........................................................17
alarm areas ........................................................ 21 Code window ....................................................13
animations collections .........................................................26
connecting to data sources ............................ 26 compiling ..........................................................17
Format object................................................ 35 connections
Linear object ................................................. 35 animation objects to data sources .................26
Lookup object ............................................... 35 connecting and disconnecting object's
property.....................................................42
asynchronous
creating direct connection to an object .........91
methods ........................................................ 31
direct .............................................................91
subroutines.................................................... 31
example.........................................................55
Auto-List Members .......................................... 29
making ..........................................................36
Auto-Quick Info ............................................... 30
objects to data sources ..................................35
B
context-sensitive help .......................................30
BaseCount ........................................................ 26
creating
browsing objects ............................................... 34
Dynamos .....................................................131
C
tag groups ...................................................137
charts
D
changing duration ....................................... 113
DAO .................................................................83
changing end time ...................................... 113
data
changing start time ..................................... 113
reading ..........................................................77
duration....................................................... 126
writing ..........................................................77
keyboard accelerators ................................. 128
Data Access Object model ................................83
methods ...................................................... 117
data link ............................................................94
pausing ....................................................... 113
data sources
properties .................................................... 117
changing at run-time .....................................91
scrolling ...................................................... 116
changing data source of a link ......................94
zooming ...................................................... 127
141
Writing Scripts
142
Writing Scripts
143
Writing Scripts
144
Writing Scripts
Z zooming ..........................................................127
145