Sei sulla pagina 1di 506

*()DQXF

ZZZML\LWHFKFRP



Intellut on

Educational Services

354 Student Guide

Using Visual Basic for Applications


with Intellution Dynamics iFIX
Version 2.1 - 7.99

Copyright 1999, Intellution, Inc.


All Rights Reserved

*()DQXF

ZZZML\LWHFKFRP



*()DQXF

ZZZML\LWHFKFRP

Intellut on



Student Information Sheet

Name: _________________________________

Date: ____________________________

Title: __________________________________

Course:

Phone Number: _________________________

Instructor: ________________________

Fax Number: ___________________________

Class Location: ___________________

354 v2.1-7.99

E-mail: _______________________________________________________________________
Company Name and Address: _____________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
Hotel where you are staying: ______________________________________________________
1. Have you used any Intellution, Inc. products?  Yes  No
If so, please note how long you have been working with the product(s):





FIX32 Software (FIX, FIX MMI, PlantTV) ________


Intellution Dynamics iFIX ________
Intellution Dynamics iBatch ________
FIX Paradym-31 ________

2. Have you ever attended an Intellution training class before today?  Yes  No
 FIX Fundamentals (FIX 104)
 iFIX for New Users (154A)
 Advanced FIX (FIX 204)
 iFIX for FIX Users (154B)
 iBatch Basics (114)
 Advanced iFIX (254)
 Other

3. How did you learn about this training class?


 Intellution Educational Services Course Catalog
 Intellutions web site
 Your local Intellution Representative or Distributor
 Other
4. Briefly describe your application: _______________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
For Office Use Only:
Cust: ______
Dealer: ______
Inty Emp: ______

SI: ______
Rep: ______
OEM ______
A&E: ______
Other (explain): _________________

*()DQXF

ZZZML\LWHFKFRP



*()DQXF

ZZZML\LWHFKFRP


Student Guide

Intellution Dynamics iFIX Training _______________________________


Version 2.1

Proprietary Notice

The manual and software contain confidential information which represents trade secrets of
Intellution, Inc. and/or its suppliers, and may not be copied or disclosed except as provided in the
license with Intellution, Inc. The information in this manual is subject to change without notice
and should not be construed as a commitment by Intellution, Inc. Intellution, Inc. assumes no
responsibility for any errors that may be in this document.

1999, Intellution, Inc. All Rights Reserved.


Trademarks
1999 Intellution, Inc. All Rights Reserved. Intellution is a registered trademark. All product
names are trademarks of Intellution, Inc. All other names are property of their respective
holders.
Microsoft Visual Basic Technology. 1996, Microsoft Corporation. All Rights Reserved.
Printed in the United States of America.

One Edgewater Drive, Norwood, MA 02062

The Intelligent Solution

Copyright 1999, Intellution, Inc.

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Table of Contents _____________________________________________


Intellution Dynamics iFIX Training Student Guide
Days One and Two ................................................................................

Days Three and Four............................................................................. xi


Introduction........................................................................................... xii
Overview......................................................................................... 1-1

1.

1.1.
VBA Scripts........................................................................
1.1.1. Understanding Objects ..................................................
1.1.2. Object Properties...........................................................
1.1.3. Object Methods .............................................................
1.1.4. Object Events ................................................................

1-4
1-6
1-8
1-10
1-11

1.2.
Container Objects................................................................ 1-12
1.2.1. iFIX Container .............................................................. 1-14
1.2.2. VBA and iFIX Container............................................... 1-16

1.3.

VBA Code .......................................................................... 1-18

1.4.

VBA Help........................................................................... 1-20

1.5.

iFIX Automation Interface Help.......................................... 1-22

1.6.

Key Terms .......................................................................... 1-26

1.7.

Exercise 1 ........................................................................... 1-27

1.8.

Summary Questions ............................................................ 1-38

2.

VBA Environment.......................................................................... 2-1


2.1.

Review................................................................................ 2-3

2.2.
Visual Basic Editor .............................................................
2.2.1. Project Explorer ............................................................
2.2.2. Property Window ..........................................................
2.2.3. Immediate Window .......................................................
2.2.4. Code Window ...............................................................

2-4
2-6
2-8
2-10
2-12

2.3.

Message Box....................................................................... 2-22

2.4.

Input Box............................................................................ 2-24

2.5.

Exercise 2 ........................................................................... 2-26

2.6.

Summary Questions ............................................................ 2-35

Copyright 1999, Intellution, Inc.

ii

*()DQXF

ZZZML\LWHFKFRP


Student Guide

Table of Contents _____________________________________________

Variables and Constants ................................................................ 3-1

3.

3.1.

4.

Naming Rules....................................................................... 3-3

3.2. Variables ..............................................................................


3.2.1. Integers .........................................................................
3.2.2. Floating Point................................................................
3.2.3. String Data ....................................................................
3.2.4. Variant ..........................................................................

3-4
3-6
3-7
3-8
3-10

3.3. Declaring Variables ..............................................................


3.3.1. Variable Scope ..............................................................
3.3.2. Variable Lifetime ..........................................................
3.3.3. User Defined Data Types...............................................

3-12
3-16
3-17
3-18

3.4.

Arrays .................................................................................. 3-20

3.5.

Constants.............................................................................. 3-24

3.6.

Variable Data in Pictures ...................................................... 3-28

3.7.

Exercise 3............................................................................. 3-30

3.8.

Summary Questions.............................................................. 3-45

Procedures and Functions ............................................................. 4-1

4.1.

VBA References................................................................... 4-4

4.2. Procedures............................................................................
4.2.1. Understanding Events....................................................
4.2.2. Understanding Scope.....................................................
4.2.3. Procedure Arguments ....................................................
4.2.4. Expressions ...................................................................

4-6
4-10
4-12
4-14
4-18

4.3. Code Locations..................................................................... 4-22


4.3.1.
Class Modules ............................................................ 4-24
4.4.

Object Browser..................................................................... 4-28

4.5.

The With Statement.............................................................. 4-32

4.6.

Hints and Tips ...................................................................... 4-34

4.7.

Exercise Example ................................................................. 4-36

4.8.

Lab Exercise 4...................................................................... 4-38

4.9.

Summary Questions.............................................................. 4-49

Copyright 1999, Intellution, Inc.

iii

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Table of Contents _____________________________________________

VBA Debugging ............................................................................. 5-1

5.

5.1.

Review ................................................................................. 5-3

5.2.

Customizing the VBE........................................................... 5-4

5.3.

Introduction to Debugging.................................................... 5-6

5.4.

Understanding Errors............................................................ 5-8

5.5. Debugging Tools ..................................................................


5.5.1.
Stepping Through Procedures.....................................
5.5.2.
Immediate Window ....................................................
5.5.3.
Watch Window...........................................................
5.5.4.
Quick Watch ..............................................................
5.5.5.
Locals Window ..........................................................
5.5.6.
VBE Calls Stack.........................................................
5.5.7.
VBE Debug Floating Toolbar .....................................

5.6.

Style and Technique ............................................................. 5-24

5.7.

Hints and Tips ...................................................................... 5-26

5.8.

Lab Exercise 5...................................................................... 5-30

5.9.

Summary Questions.............................................................. 5-41

6.

5-10
5-12
5-14
5-16
5-18
5-20
5-22
5-23

Introduction to Forms.................................................................... 6-1


6.1.

Forms Overview ................................................................... 6-3

6.2. Creating a Form.................................................................... 6-6


6.2.1.
Form Controls ............................................................ 6-9
6.2.1.
Adding New Controls................................................. 6-20
6.3.

Launching the Form.............................................................. 6-22

6.4.

Form Events ......................................................................... 6-23

6.5.

Form Hints and Tips ............................................................. 6-24

6.6.

Lab Exercise 6...................................................................... 6-25

6.7.

Summary Questions.............................................................. 6-38

Copyright 1999, Intellution, Inc.

iv

*()DQXF

ZZZML\LWHFKFRP


Student Guide

Table of Contents _____________________________________________

Controlling VBA Code................................................................... 7-1

7.

7.1.
Decision Statements............................................................
7.1.1. If Then Else...................................................................
7.1.2. If Then ElseIf ................................................................
7.1.3. Select Case....................................................................
7.1.4. GoTo.............................................................................

7-3
7-4
7-8
7-10
7-12

7.2.
Looping .............................................................................. 7-13
7.2.1. Do Loops ...................................................................... 7-14
7.2.2. For Next Loop............................................................... 7-16
7.3.

DoEvents ............................................................................ 7-18

7.4.

Review of Layers ................................................................ 7-20

7.5.

Lab Exercise 7 .................................................................... 7-24

7.6.

Summary Questions ............................................................ 7-35

Collections and Groups.................................................................. 8-1

8.

8.1.
Grouped Objects .................................................................
8.1.1. ContainedObjects Property............................................
8.1.2. ContainedSelections Property........................................
8.1.3. Grouped Object Properties ............................................
8.1.4. Group Events ................................................................

8-3
8-4
8-6
8-8
8-10

8.2.
Collections..........................................................................
8.2.1. Pre-Defined Collections ................................................
8.2.2. User Defined Collections...............................................
8.2.3. For Each Next Loop ......................................................

8-11
8-12
8-14
8-19

8.3.

Lab Exercise 8 .................................................................... 8-20

8.4.

Summary Questions ............................................................ 8-33

Copyright 1999, Intellution, Inc.

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Table of Contents _____________________________________________

Embedded Objects ......................................................................... 9-1

9.

9.1.

WorkSpace Variable Objects............................................... 9-4

9.2.

Timer Object....................................................................... 9-8

9.3.

Event Object ....................................................................... 9-12

9.4.

Scheduler ............................................................................ 9-16

9.5.

Lab Exercise 9 .................................................................... 9-18

9.6.

Summary Questions ............................................................ 9-24

10. iFIX Automation ............................................................................ 10-1


10.1.

iFIX Automation Reference ................................................ 10-3

10.2.

iFIX Objects ....................................................................... 10-4

10.3.

iFIX Subroutines................................................................. 10-6

10.4. Accessing the Process Database .......................................... 10-8


10.4.1. FindDataSource Subroutine ........................................ 10-10

10.5.

Shell Function..................................................................... 10-12

10.6.

Database Functions ............................................................. 10-14

10.7.

Lab Exercise 10 .................................................................. 10-16

10.8.

Summary Questions ............................................................ 10-26

11. Error Handlers............................................................................... 11-1


11.1.

Introduction to Error Handling ............................................ 11-3

11.2.

Handling Basic Errors ......................................................... 11-6

11.3. Using an Error Handler ....................................................... 11-8


11.3.1. Procedure Based Error Handler .................................. 11-12
11.3.2. Global Based Error Handler........................................ 11-14
11.4.

VBA Error Codes................................................................ 11-16

Copyright 1999, Intellution, Inc.

vi

*()DQXF

ZZZML\LWHFKFRP


Student Guide

Table of Contents _____________________________________________

12. Automation .................................................................................... 12-1


12.1.

Introduction to Automation ................................................. 12-3

12.2.

Adding References.............................................................. 12-4

12.3.

Making the Connection ....................................................... 12-6

12.4. Creating an Instance of the Application............................... 12-8


12.4.1. Dim Statement using New Keyword........................... 12-10
12.4.2. Set Statement.............................................................. 12-11
12.4.3. CreateObject Function................................................ 12-12
12.4.4. GetObject Function .................................................... 12-13
12.5.

Example 1........................................................................... 12-14

12.6.

Example 2........................................................................... 12-16

12.7.

Lab Exercise 12 .................................................................. 12-18

12.8.

Summary Questions ............................................................ 12-31

13. ActiveX, Linking, and Embedding ................................................ 13-1

13.1.

ActiveX .............................................................................. 13-3

13.2.

ActiveX Basic Principles..................................................... 13-4

13.3.

iFIX ActiveX Controls ........................................................ 13-6

13.4.

VBA and ActiveX Controls................................................. 13-8

13.5.

Installing ActiveX Controls................................................. 13-14

13.6.

OLE.................................................................................... 13-16

13.7.

Linking vs. Embedding ....................................................... 13-18

13.8.

Summary Questions ............................................................ 13-19

Copyright 1999, Intellution, Inc.

vii

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Table of Contents _____________________________________________

14. Accessing Relational Databases ..................................................... 14-1


14.1.

Overview ............................................................................ 14-3

14.2. Data Access Objects (DAO)................................................ 14-6


13.2.1. Joint Engine Technology (JET) .................................. 14-8
13.2.2. ODBCDirect .............................................................. 14-9
13.2.3. Example Using DAO.................................................. 14-10
14.3.

ActiveX Data Objects (ADO).............................................. 14-12

Course Appraisal Sheet

Appendixes

A. Glossary ........................................................................................... A-1

B. File I/O ............................................................................................. B-1

B.1.

Opening a File..................................................................... B-3

B.2.
Reading and Writing Data................................................... B-6
B.2.1.
Put Statement ............................................................. B-7
B.2.2.
Get Statement............................................................. B-8
B.2.3.
Input Statement .......................................................... B-9
B.2.4.
Input # Statement ....................................................... B-10
B.2.5.
Write # Statement....................................................... B-11
B.2.6.
Print # Statement ........................................................ B-12

C. Additional Notes .............................................................................. C-1


C.1.

iFIX Object Methods .......................................................... C-2

C.2.

Mathematical Functions ...................................................... C-5

Copyright 1999, Intellution, Inc.

viii

*()DQXF

ZZZML\LWHFKFRP


Student Guide

Table of Contents _____________________________________________

this page intentionally left blank

Copyright 1999, Intellution, Inc.

ix

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Days One and Two ____________________________________________

Section 1
Overview
Introduction to VBA
iFIX and VBA
Container Objects
VBA Code and VBA Help
Automation Interface Help

Section 5
Debugging
Understanding Errors
Debugging Tools
Hints and Tips

Section 6
Introduction to Forms
Creating Forms
Form Controls
Launching Forms
Form Events

Section 2
VBA Environment
Visual Basic Editor
Message Box and Input Box

Section 3
Variables
Data Types
User Defined Data Types
Arrays
Constants

Section 7
Controlling VBA Code
Decision Statements
If Then Else
Case Statement
Loops
For Next Loop
Do Loops

Section 4
Procedures and Functions
Procedures
Class Modules
Expressions
Functions
Object Browser

Copyright 1999, Intellution, Inc.

Section 8
Collections and Groups
Grouped Objects
Group Events
User Defined Collections

*()DQXF

ZZZML\LWHFKFRP


Student Guide

Days Three and Four __________________________________________

Section 9
Embedded Objects
WorkSpace Variable Object
Timer Object
Event Object
Scheduler

Section 12
Automation
Using Automation
Adding References
Automation Examples

Section 13
ActiveX, Linking, and Embedding
ActiveX
iFIX ActiveX Controls
VBA and ActiveX Controls
Installing ActiveX Controls
OLE

Section 10
iFIX Automation
Accessing the Process Database
iFIX Subroutines
Database Functions

Section 11
Error Handling
Using Error Handlers
Error Handle Examples
VBA Error Codes

Section 14
Accessing a Relational Database
Data Access Objects (DAO)
ActiveX Data Objects (ADO)

Copyright 1999, Intellution, Inc.

xi

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Introduction __________________________________________________

Course Description
This course is designed for those who wish to acquire a basic knowledge of Visual Basic for
Applications (VBA) within the iFIX container. This knowledge will allow the student to
generate VBA based solutions for their special system requirements. The student should be
familiar with the iFIX workspace and its features. The course begins with an introduction to
VBA and why VBA is so important in todays applications. Lectures, coding example, and
labs are included in this course on the important aspects of VBA, as well as reference to
Visual Basic syntax. This course will demonstrate to the student how to enhance runtime
operation to solve special problems. Additionally, the material will present information on
adding custom design tools (like ActiveX objects) and adding online maintenance tools such
as operation manuals, part descriptions, and P&ID views.

Audience
This course is principally designed for system integrators, instrumentation engineers and
process engineers who want to use the power of VBA to create unique solutions for their
applications in the process control industry.

Required Prerequisites

Completion of iFIX 154A or 154B is a must!

Familiarity with Microsoft Windows NT (Windows NT Explorer, Text Editor, etc.)

Working knowledge of process control applications.

Suggested Prerequisites

Familiarity with programming (especially Microsoft Visual Basic)

Course Duration
Four (4) days.

Continuing Education Units


This course is worth 3.2 CEU credits.

Copyright 1999, Intellution, Inc.

xii

*()DQXF

ZZZML\LWHFKFRP


Student Guide

1. Overview __________________________________________________

Chapter 1
Overview

Copyright 1999, Intellution, Inc.

1-1

*()DQXF

1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Overview _________________________________________________

Section Objectives
This section provides an introduction to the VBA and the iFIX object Hierarchy. The student
will run through a VBA sample application and discuss how objects are used within VBA. This
includes the following:

Introduction to Visual Basic for Applications (VBA)

VBA and iFIX

Understanding VBA Objects

Container Objects

VBA Help

iFIX Automation Interface

In addition, this section will also introduce important terminology used throughout the course.

Copyright 1999, Intellution, Inc.

1-2

*()DQXF

1.

ZZZML\LWHFKFRP


Student Guide

Overview _________________________________________________
A. What is VBA?

VBA Microsoft Visual Basic for Applications


-

an object-oriented and event-driven development environment that


supports Microsoft forms and ActiveX

usually referred as it is integrated into iFIX

used throughout Microsoft products for customization

Microsoft is licensing VBA as separate product

B. Terminology:

VB Visual Basic
-

usually refers to Microsoft Visual Basic 6.0

this is external to iFIX and VBA

VBA Microsoft Visual Basic for Applications


-

included as a key component of Office 97

VBA version number is 5.0 only for synchronization

VBE Visual Basic Editor

editing environment for VBA

accessible from Intellution WorkSpace

exists in the applications included in Office 97

C. Differences between Visual Basic for Applications and Visual Basic

Visual Basic uses Visual Basic for Applications as its central code engine

VB allows the creation of executables and ActiveX controls

VBA allows you to customize and extend product capabilities

VBA creates script code and does not create executables or .DLLs

Copyright 1999, Intellution, Inc.

1-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.1. VBA Scripts _____________________________________________


A. Uses for VBA

Customize and extend an application, for example:


-

add new dialog boxes and forms, add toolbar buttons

automate tasks, control an application

control e-mail and an Internet browser

Typical users of VBA could be OEMs, system integrators and end users

B. Using VBA scripts to manipulate objects

VBA allows the extending or customizing of applications by creating VBA


scripts

VBA scripts will perform functions like calculations or other minor tasks but the
main power of VBA will be to manipulate application objects

VBA scripts typically access an objects properties, methods, and/or events

VBA code created will be contained in an application as part of a project

Scripting in iFIX allows access to:

standard VBA components

all exposed iFIX objects and their properties, methods, and events

C. Within iFIX, use VBA to:

Animate objects in pictures

Create custom prompts and messages for operators

Read from, write to, and create database blocks

Incorporate custom security features

Automatically run other applications

Access other applications and manipulate their objects

Automatically generate pictures or objects

Incorporate and communicate with third-party custom ActiveX controls

Access ODBC data sources

Write custom wizards for frequently performed tasks

Copyright 1999, Intellution, Inc.

1-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

1.1. VBA Scripts _____________________________________________

VBA Terminology
Objects

Comprised of data and procedures that are treated as a unit


Each object has its own properties, methods, and events that can
be used to write scripts
Examples: Rectangle, Timer, Schedule Event

Properties

Characteristics of an object
Examples: color, size, location in the picture

Methods

Subroutines that effect the behavior of object


Examples: such as scale or refresh

Events

Actions that the object recognizes, such as when a user clicks the
mouse on the object or changes its size

If a script is associated with an event, the script executes when


the event triggers or occurs

Events can occur as a result of user action, program code, or other


occurrences in iFIX

Examples: mouse click, value reaches a threshold

Copyright 1999, Intellution, Inc.

Figure 1-1: VBA Terminology

1-5

*()DQXF

1.1.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Understanding Objects _________________________________

A. Notes

A VBA object is anything in the application that can be referenced and


manipulated

An object represents an element of an application, such as a worksheet, a cell, a


chart, a form, or a report

B. Examples

Common iFIX objects are:


-

Rectangle, Oval, Text, Bitmaps, Pictures

Figure 1-2 contains the iFIX objects that are available within VBA

Objects used frequently within VBA include:


-

Forms, Collections, Applications

C. Additional Notes

The properties, methods, and events available for an individual object are based
on the object class
-

Example:

rectangle objects have their own class

rectangle objects do not have the same font properties as text objects

Objects respond to events based on scripts that are written for each event
-

scripts can be written for one event, some events, or all events, depending
on what needs to be accomplished

Copyright 1999, Intellution, Inc.

1-6

*()DQXF

1.1.1.

ZZZML\LWHFKFRP


Student Guide

Understanding Objects _________________________________

Alarm Summary

Application

Arc

Bitmap

Chart

Chord

Color Button

ControlContainer

DataItem

DataItems

DataLink

DataServer

DataServers

Document

Documents

DynamoSet

Event

ExpressionEditor

FindReplace

FixDataSystem

FixFloatPoint

Format

Group

Group (DataSystem)

Groups

Legend

Line
Lines

Linear

Lookup

Oval

Picture

Pen

Pie

Polygon

Polyline

Procedures

Rectangle

RoundRectangle

Scheduler

ScriptLine

ScriptProcedure

ScriptSource

Sources

System

Text

TimeAxis

Timer

UserGlobals

ValueAxis

Variable

Window
Figure 1-2: iFIX Objects

Copyright 1999, Intellution, Inc.

1-7

*()DQXF

1.1.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Object Properties ______________________________________

A. VBA Object properties

Properties are the set of characteristics that define an object


-

characteristics such as size, color, or screen location, or an aspect of its


behavior, such as whether it is enabled or visible

To change the characteristics of an object, change the values of its properties

Examples: Properties can control the appearance and position of object

B. Viewing Object Properties

Use the Property Window within the WorkSpace to view the properties of an
object
-

there is also a Property Window in the Visual Basic Editor to view


properties of an object

Figure 1-3 shows some of the properties of a picture object using the Property
Window

C. Changing the property of an object

To set the value of a property, follow the reference to an object with a period, the
property name, an equal sign (=), and the new property value

See Figure 1-4 for an example of changing an objects property

D. Additional Notes

Not all property values can be set by the user

The Help topic for each property indicates whether that property is:
-

read-write

read-only

write-only

Copyright 1999, Intellution, Inc.

1-8

*()DQXF

1.1.2.

ZZZML\LWHFKFRP


Student Guide

Object Properties ______________________________________

Figure 1-3: Properties Window Example

Private Sub Rect1_Click()


FermTank.BackgroundColor = vbBlue
End Sub

Figure 1-4: Property Scripting Example

Copyright 1999, Intellution, Inc.

1-9

*()DQXF

1.1.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Object Methods ________________________________________

A. VBA Object Methods

VBA can make the object perform a task by activating a method

A method is an action that an object can perform

See Figure 1-5 for an example of activating an objects method

Figure 1-6 shows examples of iFIX methods

Private Sub CFIXPicture_Initialize()


FermTank.FullView

End Sub

Figure 1-5: Method Scripting Example

Add

BringToFront

Copy

Connect

Enable

FullView

GetCurrentValue

InsertPoint

IsConnected

Open

Refresh

Rotate

ScrollForward

SetWindowLocation

StopTimer

Zoom
Figure 1-6: Sample iFIX Methods

Copyright 1999, Intellution, Inc.

1-10

*()DQXF

1.1.4.

ZZZML\LWHFKFRP


Student Guide

Object Events _________________________________________

A. VBA Object Events

VBA allows you to define a procedure to be run when an event happens

Examples:

the script in Figure 1-4 runs a procedure when a rectangle objects click
event occurs

the script in Figure 1-5 run a procedure when the picture initialize event
occurs

Figure 1-7 lists the events available in iFIX


-

note that not all events are available to all objects

Activated

AlarmAck
Close

Click

ColorChanged

DataChange

DeActivated

DblClick
Edit

EditChange

Initialize

KeyDown

KeyUp

LmouseClick

MouseDown

MouseMove

MouseUp

OnChange

OnChartFull

OnChartRefresh

OnFalse

OnPenSelect

OnTimeOut

OnTrue

RMouseClick

SelectionChanged

UIDeactivate

WhileFalse

WhileTrue
Figure 1-7: iFIX Events

Copyright 1999, Intellution, Inc.

AfterKillFocus

1-11

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.2. Container Objects ________________________________________


A. Application Object

The object that is common to all applications and is at the top of the application
model is the Application Object

The application object is the container for all other objects even other container
objects like the Window object container

Application object has properties, methods and events of its own


-

Properties like StatusBar, Caption, WindowState, and ActiveWindow

Methods like CheckSpelling, Help, Quit, and EnableCancelKey

The iFIX application object is the WorkSpace

All iFIX objects like picture documents, shape objects and more will reside in
WorkSpace

B. Window Object

Window object is also common in many applications

Window object is a container for the open document

Window objects has its own properties, methods and events

Properties like Caption, Height, Width, and WindowState

Methods like Activate, Close, LargeScroll and SmallScroll

iFIX Window object is part of the Picture document

C. Other Containers

VBA projects are also container objects

Each project can contain WorkSpace application objects, references, forms,


modules and class modules

Copyright 1999, Intellution, Inc.

1-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

1.2. Container Objects ________________________________________

Figure 1-8: iFIX Object Hierarchy

Copyright 1999, Intellution, Inc.

1-13

*()DQXF

1.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

iFIX Container _________________________________________

A. Intellution WorkSpace

The Intellution WorkSpace is the iFIX Container


-

it is made up of objects and collections of objects

this collection of objects is what makes up the iFIX application

The iFIX picture document is an object containing other objects


-

User interface objects l like rectangles, polygons, chords, etc.

The iFIX picture document will also contain the VBA script code

B. Objects that are visible at runtime in the iFIX container:

Picture documents (.grf files that compose the screen view)

iFIX Scheduler documents

Fix2D objects (rectangles, text, lines, and such that make up a picture item)

Groups (named collection of shapes that form valves, pumps, tanks, etc.)

Objects that belong to a Collection

Data Link (datasource reference)

this is actually a special type of the Text Objects

Animations (an embedded object attached to visible object)

ActiveX objects inserted to do a runtime function


-

iFIX Alarm Summary object

3rd party controls

C. Intellution WorkSpace allows user interface objects to be manipulated

Object properties can be set at design time or with VBA script

Wizards and Experts are available to add VB scripts to the objects

iFIX Scheduler object creates script when it is configured

D. Intellution WorkSpace allows objects to connect to various datasources

iFIX process database , Historical files, Global variables, OPC servers and other
objects

Copyright 1999, Intellution, Inc.

1-14

*()DQXF

1.2.1.

ZZZML\LWHFKFRP


Student Guide

iFIX Container__________________________________________

Text

iFIX Container
Picture Object

Excel Container

Keyboard

Workbook Object

Mouse

LineObject

Sheet1 Object

RectObject

Sheet2 Object

Modem

TextObject
Object Event VBA Code

NIC

XYZ Container

Serial Port

Form Object
Hard Drive
Container Support Code

Windows NT

Figure 1-9: iFIX Container

Copyright 1999, Intellution, Inc.

1-15

*()DQXF

1.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA and iFIX Container _________________________________

A. VBA within the container has access to different types of objects

iFIX objects
-

Special features via scripting

Custom database additions and deletions

Objects that can be reusable across projects

Forms
-

Allows for custom dialog boxes

Allows for customizing design tools

ActiveX Objects
-

Query special devices via ActiveX

Perform a proprietary calculation

View an AutoCAD DWG file

Send a number to a pager or e-mail for technical support

OLE objects to provide seamless access to other applications


-

Access/Excel for custom reports

AutoCAD or Visio for special drawing

Vendor supplied OPC driver for their device

Copyright 1999, Intellution, Inc.

1-16

*()DQXF

1.2.2.

ZZZML\LWHFKFRP


Student Guide

VBA and iFIX Container__________________________________

B. VBA uses several items to perform its actions

Variables to keep track of values


-

Can be many different data types

Boolean, Integer, Real, and String are typical

Conditionals to determine if something is required or not


-

Test for conditions

Determine the state of an object

Part of a calculation for which item next (sequencing)

Assignment statements to save results and set properties and values


-

sets an object property to a value

copies the result of a calculation into a variable

copies an object property to a variable

System functions to provide for specified action to be done


-

Predefined in the environment library

One of an objects methods

Examples (ClosePicture, CloseDigitalPoint, and MsgBox)

Decision statements to control which items are performed


-

If statement - executes statements when it evaluates to True

Otherwise, executes statements when the If evaluates to False

Looping statements to operate on sets of objects


-

While loop executes statements when the conditional is True

Do loop, same as While loop, but executes statements at least once

For loop, same as While loop, but auto increments a variable each loop

User defined functions and subroutines to execute repetitive tasks


-

Module of code (Visual Basic or Visual C)

One of an object's methods

Values can be passed into the subroutine to allow generalized operation

Function is a subroutine that returns a value

Copyright 1999, Intellution, Inc.

1-17

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.3. VBA Code _______________________________________________


A. Where does VBA Code live?

In iFIX, each picture (*.GRF) is a VBA project


-

creating a new picture in the Intellution WorkSpace (untitled1) will create


a new project called Project_untitled1

the picture document named untiled1 is included as part of that project

the items that can be a part of the project are user forms, modules, and
references

The VBA code within a project is contained within a module


-

Modules, and all other supporting VBA components, make up a VBA


project

in the VBE clicking on the Project_untitled will bring the module into
view in the code window of the VBE

procedures are individual sections of code to perform a specific task

B. What else makes up VBA?

Already mentioned was the concept of modules, procedures and projects

Here is a partial list of topics and concepts that are a part of VBA and will be
discussed in the next chapters:

Within a module, code is divided into procedures

Variables

Constants

Functions

User forms

Looping

Decisions

Debugging

Expressions

Automation

Error Handling

Copyright 1999, Intellution, Inc.

1-18

*()DQXF

ZZZML\LWHFKFRP


Student Guide

1.3. VBA Code _______________________________________________

Figure 1-10: Visual Basic Editor

Copyright 1999, Intellution, Inc.

1-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.4. VBA Help _______________________________________________


A. Using the VBA help with routines

Source for what the functions do

Example of Points to code

Use table of contents, index, or find

B. Accessing the Help

Select from the Help menu

F1

C. Content Tab provides a table of contents for:

System functions and subroutines that provide access to predefined actions

Language Reference

MsForms Reference

Other Visual Basic Applications

D. Find Tab

Provides a matching list to every word in the Help file

Good for general information searches

E. Index Tab

Provide a match to keywords that the Help File developer decides was important

Index works like a book index for Help Topics

Copyright 1999, Intellution, Inc.

1-20

*()DQXF

ZZZML\LWHFKFRP


Student Guide

1.4. VBA Help _______________________________________________

Figure 1-11: VBA Help (Contents tab shown)

Copyright 1999, Intellution, Inc.

1-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.5. iFIX Automation Interface Help _____________________________


A. Tabs

Content - Table of Contents

Index & Find - search for topics by keyword

B. Contents

Objects, Properties, Methods, Events

Subroutines

Database Functions

Figure 1-12: iFIX Automation Help

Copyright 1999, Intellution, Inc.

1-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

1.5. iFIX Automation Interface Help _____________________________

Figure 1-13: iFIX Automation Help Alphabetical List

Copyright 1999, Intellution, Inc.

1-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.5. iFIX Automation Interface Help _____________________________

Figure 1-14: Automation Help Example (Rectangle Object)

Figure 1-15: Automation Help Example (Click Event)

Copyright 1999, Intellution, Inc.

1-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

1.5. iFIX Automation Interface Help _____________________________

Figure 1-16: Automation Help Example (ForegroundColor Property)

Figure 1-17: Automation Help Example (Rotate Method)

Copyright 1999, Intellution, Inc.

1-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.6. Key Terms ______________________________________________

VBA Terminology
Project

Stores all VBA code and any added components: includes


documents, code modules, class modules and form modules

Module

Container in the VBE project that used to store VBA code

Procedure

Unit of VBA code that performs a task or returns a value

Sub Procedure

VBA Procedure that performs a task but does not return a value

Function

VBA Procedure that returns a value

Container

Container objects store other objects within. Intellution


WorkSpace contains Picture objects which contain shape objects

Constant

Represents a numeric or string value that does not change

Variable

Named memory space to store any type of data

Objects

Comprised of data and procedures that are treated as a unit

Each object has its own properties, methods, and events that can
be used to write scripts

Examples: Rectangle, Timer, Schedule Event

Properties

Methods
Events

Characteristics of an object

Examples: color, size, location in the picture


Subroutines that effect the behavior of object

Examples: such as scale or refresh


Actions that the object recognizes, such as when a user clicks the
mouse on the object or changes its size
If a script is associated with an event, the script executes when
the event triggers or occurs
Events can occur as a result of user action, program code, or
other occurrences in iFIX
Examples: mouse click, value reaches a threshold
Figure 1-18: VBA Terminology

Copyright 1999, Intellution, Inc.

1-26

*()DQXF

1.7.

ZZZML\LWHFKFRP


Student Guide

___________________________________________ Lab Exercise 1

Introduction to VBA
Lab Exercise 1

Copyright 1999, Intellution, Inc.

1-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 1


Lab Information
Upon successful completion of this lab exercise, you will be familiar with many terms related
to VBA in iFIX. You will also be familiar with locating and manipulating various features in
the VBE, the Visual Basic Editor.
As you progress through this lab, you will:

Work with the help built into the WorkSpace and the VBE

Navigate through various dialog boxes in the VBE

Become familiar with VBE functionality and locations of options

When you are finished with this lab, turn to page 1-38 and answer the Summary Questions.

Resources:

The iFIX On-line Help and E-Books


The iFIX Visual Basic Editor Help and iFIX Automation Help

Lab Information

During this section, you were introduced to VBA terminology, how to manipulate objects,
how to create code, and how to use online help. Now you will get an opportunity to create a
point of reference for the future when youre confronted with VBA and iFIX terminology.
To give you some hands on experience with the Visual Basic Editor, we will guide you
through various dialog boxes and windows. You will discover how to open various windows
and get details about the objects you are working with.
If you are looking for help remember that help can be found in the Electronic Books and the
Release Notes. There is also Automation Interfaces Help and Database Manager Help. All
of these can be found in the Help & Information folder of the WorkSpace System Tree. And
of course, if you go to the help menu you can get WorkSpace Help and Picture Help. When
you are working with the Visual Basic Editor, you have access to Microsoft Visual Basic
Help and iFIX Automation Help.

Copyright 1999, Intellution, Inc.

1-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 1


A. A quick introduction to VBA.
Please be familiar with the answers to the following questions before continuing.
1. The VBA (Visual Basic for Applications) language is the same in all VBA
applications, from iFIX to AutoCAD to Visio to Microsoft Excel. So, for example,
the VBA Editor in iFIX is the same as the VBA Editor in Excel. However, each
VBA implementation seems to vary. Why?

2. Can you use iFIX VBA to build a stand-alone application that can be complied down
to an EXE, DLL, or OCX?

3. Since VBA is the same across all applications, you could take the VBA code and the
UserForms you developed in iFIX VBA and drop them into Excel. Can you also take
the VBA code and UserForms you developed in iFIX VBA and drop them into
Microsoft Access? How about Visual Basic itself?

4. In your own words, explain the following terms: properties, methods, and events.

5. Next to each term below, write down if it is a property, method, or event.


Color

AddItem

Layer

VerticalPosition

FindObject

Click

KeyUp

OnTimeOut

Name

Edit

BuildObject

VerticalFillDirection

AddPen

ClassName

CurrentImage

MouseMove

Copyright 1999, Intellution, Inc.

1-29

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 1


B. Getting familiar with the Visual Basic Editor (VBE).

1. Create a new picture in the WorkSpace and add the following objects:
3 rectangles
1 polyline
1 arc
1 chord

1 oval
2 polygons
1 pie
1 pushbutton

Your screen could look similar to this:

2. Save the new picture by clicking the File menu then Save.
Use the following file name:
VBAObjects

Copyright 1999, Intellution, Inc.

1-30

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 1

3. You see all your new objects in the System Tree on the left-hand side of the
WorkSpace. You can see that all the objects have unique, though uninteresting
names.
4. Go to the View menu and select the Property Window.
The Property Window appears.
5. Note that when you select an object in the WorkSpace work area, the corresponding
object also is selected in the System Tree and in the Properties Window. You can
also select an object in the System Tree, or by using the drop-down menu in the
Properties Window.

Regardless where you select the object (WorkSpace work area, System Tree, or
Properties Window) the corresponding information about the object is highlighted in
the other two locations.

Copyright 1999, Intellution, Inc.

1-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 1


C. Edit the new picture
Now, we will go to the Properties window and make some changes so that you can see
how that affects your object in the work area.
1. Select one of the rectangles, Rect1 perhaps. Now, in the properties page, modify the
following properties:
Name:
TankFillBarGraph
BackgroundColor:
Yellow
Description:
Ingredient Tank #1 Fill Bar Graph
EdgeColor:
Dark Red
EdgeWidth:
4
FillStyle:
Diagonal Crosshatch
ForegroundColor:
Red
Layer:
1
RotationAngle:
-10
The picture should now resemble the following:

The properties that you just modified in the Properties window can also be modified
with VBA code both at run-time (Run mode) and design-time (Configure mode).
These same properties can have animations assigned to them.

Copyright 1999, Intellution, Inc.

1-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 1

2. Take note of the Properties window. Select the pull-down menu and choose
VBAObjects. There are two things to note:
(a) You are looking at the properties page for the picture where you can leave a
description, comment, information about the author, etc.
(b)

The picture object belongs to a class called CFIXPicture

3. Right click on the TankFillBarGraph object and select the Edit Script.
4. Now that you are in the VBE, go to the View menu and select Immediate Window
and Properties Window. Your display should look something like this:

5. The VBE should be displaying the Project Explorer in the upper left-hand corner.
Below it should be the Properties Window. The lower right-hand corner should be
the Immediate Window and above it the Code Window. Above the Code Window
on the left-hand side is the VBE Object drop-down list. This is a list of objects that
are registered with the VBE. To the right of it is the Event drop-down list.

Copyright 1999, Intellution, Inc.

1-33

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 1


D. Viewing the VBE Configuration

1. Go to the Project Explorer in the VBE, and highlight the Project_VBAObjects


project.
2. Right click it and select Project_VBAObjects Properties from the menu. You
should see the following dialog box. In the figure below we display both tabs.

3. Go to the Project Description field and enter the following:

This lab is hands-on VBE using Shape Objects

4. Now click the Protection tab. Do not change anything here, but be aware that you
can password protect your VBA code so other people can not access it. If someone
were looking at your picture in the WorkSpace and decided to look at your code by
launching the Visual Basic Editor, they would get a prompt that forces them to type in
a user and password.
5. Now, close the Project Properties dialog box by clicking the OK button.

Copyright 1999, Intellution, Inc.

1-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 1


E. Additional VBE Functionality

1. Go to the Project Explorer and highlight the Project_VBAObjects project. Right


mouse click on it and select Insert from the menu, then choose Module.
The screen should now resemble the following:

You have just inserted a module called Module1. You can change the name in the
Properties window.
2. When you look at your Project Explorer you will see VBAObjects located in the
WorkSpace Application Objects. This is where all your picture event code goes
(this will be explained in more detail in the next chapter). In Modules, you will see
the module you just inserted, Module1. You can change the name to something more
meaningful. Also, you can have many modules.
In general, modules contain functions and subroutines called by the picture event
code or by other functions and subroutines.

Copyright 1999, Intellution, Inc.

1-35

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 1

3. Next we shift our attention to the Immediate Window. This window is great for
trying out functions and small bits of code. For example, if you want to know how
many days between today and the first day of the century, enter the following:
print DateDiff("d", Now, #January 1 2000#)

4. Finally, we bring our attention to the code window. Double-click on Module1 in the
Project Explorer, and type the following code in the code window:
Public Sub Rotate10degrees()
With VBAObjects.TankFillBarGraph

.RotationAngle = .RotationAngle - 10
End With
End Sub

The screen should now resemble the following:

Copyright 1999, Intellution, Inc.

1-36

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 1

5. Put your cursor on the word Rotate10degrees and press the <F5> key. If you made
any typos, you may have gotten an error message after hitting <F5>. If not, you just
ran your code.
6. Use <Alt><Tab> to go back to the WorkSpace to see what changed. You should see
that the rectangle rotated 10 degrees.
The screen should resemble the following:

You were able to modify the properties of an object in the WorkSpace and the
WorkSpace was not even in Run mode!

End of Lab Exercise

Copyright 1999, Intellution, Inc.

1-37

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

1.8. Summary Questions ______________________________________

1. What are all the different locations you can look to find help with iFIX objects?

2. Can you make changes to your Visual Basic Code while the WorkSpace is in run mode?
Explain.

3. Is the property window in the VBE the same as the one in the WorkSpace?

4. iFIX is built upon Component Architecture. iCore is the glue in the Intellution Dynamics
family of software products. What are the main ingredients that make up our iCore glue?

5. In addition to shape objects, what other things are stored in the picture file (the GRF
file)?

Copyright 1999, Intellution, Inc.

1-38

*()DQXF

ZZZML\LWHFKFRP


Student Guide

2. VBA Environment___________________________________________

Chapter 2
VBA Environment

Copyright 1999, Intellution, Inc.

2-1

*()DQXF

2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA Environment _________________________________________

Section Objectives
This section provides an introduction to the VBA environment. The discussion will include
VBA projects. The student will also use the Visual Basic Editor to create VBA script. This
includes the following:

Visual Basic Editor

Working in the VBE

Creating Procedures

Creating Modules

MsgBox and InputBox

Copyright 1999, Intellution, Inc.

2-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

2.1. Review__________________________________________________
A. Notes

Projects
-

Open projects are a reflection of what is open in the WorkSpace

In iFIX, each open picture (*.GRF) is a VBA project

Creating a new picture in the Workspace (untitled1) will create a new


project called Project_untitled1

Included in the project will be the picture document

VBA code can reside as part of the picture document or in other areas such
as Modules, Class modules, and User Forms

Picture documents, Modules, User Forms, and Class modules and all other
supporting VBA components, make up a VBA project

Code Modules

Within the Visual Basic Editor the code displayed is the code module

The code displayed can reside in a user defined Module, the Picture
Document, User Forms or a Class Modules

Within a code module, code is divided into procedures

Procedures
-

A self contained block of VBA code that performs a specific task or


returns a value

To perform any VBA task a procedure must be written

Every procedure has a name which must be unique within a module

Copyright 1999, Intellution, Inc.

2-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

2.2. Visual Basic Editor _______________________________________


A. There are multiple ways to access the VBE

From the Workspace menu, select Visual Basic Editor

From the WorkSpace, choose VBE button on toolbar

Right click an object that will contain script and select Edit Script

Use the Taskbar in the VBE to switch back and forth

B. Overview of the VBE Components

Project Explorer
-

Properties Window
-

displays the properties of the selected object

Code Window
-

displays all the VBA projects currently opened in the WorkSpace

displays the code of the selected picture, module, or class module

Immediate Window
-

used to test code functions without running an entire procedure

Copyright 1999, Intellution, Inc.

2-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

2.2. Visual Basic Editor _______________________________________

Project Explorer

Code Window

Property Window

Immediate Window

Figure 2-1: Visual Basic Editor (VBE)

Copyright 1999, Intellution, Inc.

2-5

*()DQXF

2.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Project Explorer _______________________________________

A. Project Explorer

Displays a list of open VBA projects

Open projects list reflects what is open in the application, for example,
WorkSpace
-

Each document in the WorkSpace is a project in the VBE

Examples:

Pictures

Schedules

Toolbars

Globals

this is important when communicating between pictures and other


documents

Projects contain open application objects (such as a picture), modules (if you have
created them), and user forms you have built

Saving a project

Projects can be saved by highlighting the project and selecting Save


Project from the File menu

Also, when the application is saved, such as saving a picture in


WorkSpace, the project will be automatically saved

Copyright 1999, Intellution, Inc.

2-6

*()DQXF

2.2.1.

ZZZML\LWHFKFRP


Student Guide

Project Explorer _______________________________________

Figure 2-2: VBE Project Explorer

Copyright 1999, Intellution, Inc.

2-7

*()DQXF

2.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Property Window ______________________________________

A. The Property Window

Displays properties for highlighted object in Project Explorer

Includes the name of the property and the current property value

Properties can be shown alphabetically or by category

If property window is not shown, press F4 or select from View menu

New values can be typed in, selected from a drop down list, or double-clicked

Copyright 1999, Intellution, Inc.

2-8

*()DQXF

2.2.2.

ZZZML\LWHFKFRP


Student Guide

Property Window ______________________________________

Figure 2-3: VBE Property Window

Copyright 1999, Intellution, Inc.

2-9

*()DQXF

2.2.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Immediate Window _____________________________________

A. Immediate Window

Used to test some code without having to run the entire project

Allows the developer to test expressions, execute code, change values, and debug
an application

See Figure 2-4 for an example


-

the ? is equivalent to the keyword print

From the View menu, select Immediate Window


-

or press CTRL-G

Copyright 1999, Intellution, Inc.

2-10

*()DQXF

2.2.3.

ZZZML\LWHFKFRP


Student Guide

Immediate Window _____________________________________

Figure 2-4: VBE Immediate Window

Copyright 1999, Intellution, Inc.

2-11

*()DQXF

2.2.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Code Window _________________________________________

A. Work (Code) Window

Displays the code modules and other objects such as user forms

To display the module code, highlight the project in the Project Explorer and
perform one of the following:

Double-click the highlighted project

Select View Code from the Project Explorer menu bar

Select Code from View menu

Press F7

To display object-specific code in your project, highlight the object contained in


the project and perform one of the following:
-

Double-click the object, such as a form

Select View Object from the Project Explorer menu bar

Select Object from View menu

Press SHIFT-F7

B. Code Window Components

The code window is comprised of various pieces:

Object list

Procedure list

Declarations section

Procedure separator(s)

Procedure(s)

Note: In some VBA books, the Object List and Procedure List are called the
Wizard Bar

C. Procedures

A self contained block of code is called a procedure

Two types of procedures:


-

Sub Procedure

Function Procedure

Copyright 1999, Intellution, Inc.

2-12

*()DQXF

2.2.4.

ZZZML\LWHFKFRP


Student Guide

Code Window _________________________________________

Figure 2-5: VBE Code Window

Copyright 1999, Intellution, Inc.

2-13

*()DQXF

2.2.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Code Window _________________________________________

D. Object List

Pull down list that shows what objects exist for the highlighted project

Lists all objects associated with the module

Change code view mode from all procedures in module to only selected
object procedure
-

At the bottom left of window, select Full Module View or Procedure


View

A Group of objects is also an object

Includes (General) which refers to any procedures that are not associated with a
particular object

Example Objects
-

Rect1

Oval1

Polygon1

Group1

CFixPicture

Calendar1

Additional Notes
-

If objects do not exist in the object list but are part of the picture

Right Click the object and select Edit Script


OR

Copyright 1999, Intellution, Inc.

From the Edit menu, select Select All and then right click Enable
Scripts

2-14

*()DQXF

2.2.4.

ZZZML\LWHFKFRP


Student Guide

Code Window _________________________________________

Figure 2-6: VBE Object List

Copyright 1999, Intellution, Inc.

2-15

*()DQXF

2.2.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Code Window _________________________________________

E. Procedure List

Lists all procedures and functions in the module


-

Pull down list to show available procedures for selected object

Includes the event procedures

List is different depending on Object type

Event selection will position file to associated VBA code or create it

Object Event Examples


-

Push Button Event

Click

Mouse Events

Click, DblClick

MouseDown, MouseUp

MouseMove

Key Events

KeyDown, KeyUp

KeyPress

Initialize Event

Enter Event

Exit Event

Activated Event

De-Activated Event

Additional Notes
-

Remember, the events that are available are object dependent

Example:

Copyright 1999, Intellution, Inc.

Initialize event is available for an iFIX picture object but does not
exist as an event for a rectangle object

2-16

*()DQXF

2.2.4.

ZZZML\LWHFKFRP


Student Guide

Code Window _________________________________________

Figure 2-7: VBE Procedure (Event) List

Copyright 1999, Intellution, Inc.

2-17

*()DQXF

2.2.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Code Window _________________________________________

F. Function Procedure

Needs to be defined (needs a name) before it can be used

Definition ends with End Function

Definition can include parameters that may be passed to the subroutine

Function procedure typically does not modify its environment but does return a
value

G. Sub Procedure

Needs to be defined (needs a name) before it can be used

Definition ends with End Sub

Definition can include parameters that may be passed to the subroutine

Sub procedure is allowed to modify its environment but it can not return a value

Copyright 1999, Intellution, Inc.

2-18

*()DQXF

2.2.4.

ZZZML\LWHFKFRP


Student Guide

Code Window _________________________________________

Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function

Figure 2-8: Function Procedure Example

Private Sub CommandButton1_Click()

entry = InputBox ("Enter Temperature in Degrees F")


If entry = "" Then

MsgBox "No Value Entered"

Else

MsgBox "Temperature is " & Celsius(entry) & " Degrees C"

End If

End Sub

Figure 2-9: Sub Procedure Example

Copyright 1999, Intellution, Inc.

2-19

*()DQXF

2.2.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Code Window _________________________________________

H. Creating a new Procedure

From the Insert menu, select Procedure


-

see Figure 2-10

Use this dialog to add a new procedure or function

Also, select the appropriate scope for the procedure


-

defines the visibility of a procedure (or an object or variable)

For example, a procedure declared as Public is visible to all other


procedures in all modules within a project

However, this is not true if Option Private Module is in effect

see the Help for more information on this

I. Creating a new Module

From the Insert menu, select Module


-

the new module is added to the project

the new module can be seen in the Project List window

New modules can also be imported


-

from the File menu, select Import File

the module to be imported should be a *.BAS file

when a new module is imported, all the procedures of that module are
imported

this may not be the desired result

to only add a particular procedure, open the *.BAS file in a text


editor and copy/paste the procedure into the VBA code window

use this same technique to copy sample code from the Help system

existing VBA code can likewise be exported

Copyright 1999, Intellution, Inc.

2-20

*()DQXF

2.2.4.

ZZZML\LWHFKFRP


Student Guide

Code Window _________________________________________

Figure 2-10: Add Procedure Dialog Box

Figure 2-11: Import File Dialog Box

Copyright 1999, Intellution, Inc.

2-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

2.3. Message Box ____________________________________________


A. Notes

Allows for message to be sent to the operator and waits for a reply

Displays a message in a dialog box, waits for the user to click a button, and
returns an Integer indicating which button the user clicked

Requires at least the string message as a literal

To specify more than the first named argument, use MsgBox in an expression
-

to omit some positional arguments, include the corresponding comma


delimiter

B. Syntax
MsgBox (prompt[, buttons] [, title] [, helpfile, context])
-

prompt Required

string expression displayed as the message in the dialog box

buttons Optional

numeric expression that is the sum of values specifying the number


and type of buttons to display, the icon style to use, the identity of
the default button, and the modality of the message box

title Optional

string expression displayed in the title bar of the dialog box

if the title is omitted, the application name is placed in the title bar

helpfile Optional

string expression that identifies the Help file to use to provide


context-sensitive Help for the dialog box

context Optional

Copyright 1999, Intellution, Inc.

numeric expression that is the Help context number assigned to the


appropriate Help topic by the Help author

2-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

2.3. Message Box ____________________________________________

Figure 2-12: VBA - Help MsgBox Topic

Copyright 1999, Intellution, Inc.

2-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

2.4. Input Box _______________________________________________


A. Notes

Displays a prompt in a dialog box, waits for the user to input text or click a
button, and returns a String containing the contents of the text box

If the user clicks OK or presses Enter, the InputBox function returns whatever is
in the text box

If the user clicks Cancel, the function returns a zero-length string ("")

To specify more than the first named argument, use InputBox in an expression
-

to omit some positional arguments, include the corresponding comma


delimiter

B. Syntax
InputBox (prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])
-

prompt Required

string expression displayed as the message in the dialog box

title Optional

string expression displayed in the title bar of the dialog box

default Optional

string expression displayed in the text box as the default response


if no other input is provided

if you omit default, the text box is displayed empty

xpos Optional

numeric expression that specifies, the horizontal distance of the left


edge of the dialog box from the left edge of the screen

if xpos is omitted, the dialog box is horizontally centered

ypos Optional

numeric expression that specifies, the vertical distance of the upper


edge of the dialog box from the top of the screen

If ypos is omitted, the dialog box is vertically positioned


approximately one-third of the way down the screen

helpfile same as MsgBox

context same as MsgBox

Copyright 1999, Intellution, Inc.

2-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

2.4. Input Box _______________________________________________

Private Sub CommandButton1_Click()


response = MsgBox("Convert a Temperature?", vbYesNo, "Question")

If response = vbYes Then


entry = InputBox("Enter Temperature in Degrees F")
If entry = "" Then
MsgBox "No Value Entered"
Else
MsgBox "Temperature is " & Celsius(entry) & " Degrees C"
End If

Else
MsgBox "No Conversion"
End If

End Sub

Figure 2-13: MsgBox and InputBox Example

Copyright 1999, Intellution, Inc.

2-25

*()DQXF

2.5.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

___________________________________________ Lab Exercise 2

Objects, Events, and VBA Code


Lab Exercise 2

Copyright 1999, Intellution, Inc.

2-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 2


Learning Objectives:
Upon successful completion of this lab exercise, you will be more familiar with locating and
manipulating various features in the VBE, the Visual Basic Editor.
As you progress through this lab, you will:

Continue to work with the on-line help built into the WorkSpace and the VBE

Create new modules and new procedures

When you are finished with this lab, turn to page 2-35 and answer the Summary Questions.

Resources:
The iFIX On-line Help and E-Books
The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

During lecture you covered the VBA Editor and many of its settings and windows. This lab
will give you some hands-on with the VBA Editor.

Note: Throughout the exercise, the following object naming conventions are used:

Prefix:
Root:
Suffix:

What the object represents such as Pipe, Valve, Tank, Pump


Properties of the object such as Color, Position, Number
What type of shape was used such as Rectangle, Polyline, Bitmap

Common prefixes used: Valve Vlv, Pump Pmp, Header Hdr, Level Lvl,
Mixer Mix, Temperature Tmp, Label Lbl, Pipe Pipe, Tank Tank or Tk,
Reactor Rea, Conveyor Cnv, Packaging Station Pkg, Palletizer Plt
Common suffixes used: Group Grp, Polygon Pgn, Polyline Pln, Oval Ovl,
Rectangle Rct, Rounded Rectangle Rrt, Bitmap Bmp, Text Txt, Line Lin
Datalink Lnk, Command Button Cmd, Chord Crd, Arc Arc, Pie Pie

Copyright 1999, Intellution, Inc.

2-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 2


A. Creating a new picture with some simple objects
In the previous lab, you created many shape objects. You could see how they correlated
to the objects and properties in the Properties dialog box both in the WorkSpace and in
the Visual Basic Editor. With this lab you will see how the Event code in the Visual
Basic Editor correlates to the objects in the WorkSpace.
1. Create a new picture in the WorkSpace and draw a rectangle, line, oval, polygon, and
polyline.
The picture should resemble the following:

2. Save this picture with the following name:


IngredientTank

Copyright 1999, Intellution, Inc.

2-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 2

3. Using the Property Window, modify the properties of the objects as follows:
Rect1:

Name:
Description:
EdgeWidth:
ForegroundColor:

Tank1Rct
Ingredient Tank#1
4
Blue (16711680)

Line1:

Name:
Description:
EdgeColor:
EdgeWidth:

PipeTk1ToVlv1Lin
Tank #1 Pipe to Transfer Valve
Black (0)
9

Oval1:

Name:
Description:
EdgeWidth:
ForegroundColor:

Vlv1XoutOvl
Valve #1 background
4
Light Gray (12632256)

Polygon1:

Name:
Description:
EdgeWidth:
ForegroundColor:

Vlv1XoutPgn
Valve #1 rotary-valve
4
Dark Gray (8421504)

PolyLine1:

Name:
Description:
EdgeColor:
EdgeWidth:

PipeXoutPln
Transfer Out Pipe
Black (0)
9

Copyright 1999, Intellution, Inc.

2-29

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 2

4. Next, make sure the center of rotation for your polygon is the actual center of the
polygon. To do this, click on the polygon to select it. Then, click the Object menu
followed by Rotate.
You will see the center of rotation and rotation handles appear.

Center of
Rotation

5. If the center is not in the middle of the polygon, click on the center of rotation, and
while holding down the mouse button, drag the center of rotation to the center of the
polygon.

Copyright 1999, Intellution, Inc.

2-30

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 2


B. Adding scripts to the picture
Add some scripts to change properties of the objects in the picture.
1. Right mouse click on Tank1Rct and from the menu, choose Edit Script.
You will now find yourself in the VB Editor.

2. Instead of working with the Click event, we want the MouseMove event, so from the
event drop-down menu, select MouseMove.

Copyright 1999, Intellution, Inc.

2-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 2

3. You will now type the MouseMove event code as in the figure below. It is also good
programming practice to use comments, so you will be typing those in also, as you
see fit.
'
'
'
'

Mouse-move event for the rectangle that represents our


tank. Any time you move the mouse over the rectangle, the
vertical fill value of the rectangle is decreased. The
tank is immediately refilled when it goes empty.

Private Sub Tank1Rct_MouseMove(ByVal Button As Integer, _


ByVal Shift As Long, ByVal X As Double, ByVal Y As Double)
With Tank1Rct
.VerticalFillPercentage = .VerticalFillPercentage - 1

If .VerticalFillPercentage < 1 Then .VerticalFillPercentage = 100


End With
End Sub

When finished, the code window should look something like the following:

Copyright 1999, Intellution, Inc.

2-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 2

4. Next, use <Alt><Tab> to go back to the WorkSpace.


5. Right mouse click on Vlv1XoutPgn and from the menu, choose Edit Script.
You will now be back in the VB Editor.
6. Again we do not want to put code behind the Click event, we want the MouseMove
event, so from the event drop-down menu, select MouseMove. You will now type
the MouseMove event code as in the figure below adding comments as you see fit.

'
'
'
'
'

Mouse-move event for the Polygon that represents


Transfer out Valve. Any time you move the mouse
polygon, the rotation angle value of the polygon
increased. The valve is immediately flipped back
original position when it goes upside down.

our
over the
is
to its

Private Sub Vlv1XoutPgn_MouseMove(ByVal Button As Integer, _

ByVal Shift As Long, ByVal X As Double, ByVal Y As Double)

With Vlv1XoutPgn

.RotationAngle = .RotationAngle + 5

If .RotationAngle > 180 Then .RotationAngle = 0

End With

End Sub

Copyright 1999, Intellution, Inc.

2-33

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 2


C. Viewing the picture in Run Mode

1. Use <Alt><Tab> to get back to the WorkSpace.


2. Save your work.
3. Go to Run mode to see what happens.
The picture should resemble the following:

End of Lab Exercise

Copyright 1999, Intellution, Inc.

2-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

2.6. Summary Questions ______________________________________

1. In the iFIX object hierarchy, what object serves as the container for all shape objects and
ActiveX controls?

2. As you work with iFIX, you will see that each picture has its own VBA programming
project. Is the VBA programming project a container object? What does it contain?

3. Explain the advantages of cutting and pasting code into a module versus importing an
entire code module.

4. Suppose you create an object in a picture and then task-switch to the VBE. The object
does not appear in the Object List. What can you do to get the object to appear in the
Object List?

5. Explain IntelliSense. What is it and how can it be used?

Copyright 1999, Intellution, Inc.

2-35

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

2.6. Summary Questions ______________________________________

this page intentionally contains no data

Copyright 1999, Intellution, Inc.

2-36

*()DQXF

3.

ZZZML\LWHFKFRP


Student Guide

Variables and Constants____________________________________

Chapter 3
Variables and Constants

Copyright 1999, Intellution, Inc.

3-1

*()DQXF

3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Variables and Constants____________________________________

Section Objectives
This section provides an introduction to the concept of variables and constants in VBA. This
includes a look at variable data types, variable arrays, and constants. This includes the
following:

Variables

Variable Data Types

User Defined Data Types

Arrays

Constants

Copyright 1999, Intellution, Inc.

3-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.1. Naming Rules____________________________________________


A. Use the following rules when naming procedures, constants, variables, and arguments in
a code module

The first character must be a letter as

Do not use a space, period (.), exclamation mark (!), or the characters @, &, $, #
in the name

Names can't exceed 255 characters in length

Generally, dont use any names that are the same as the functions, statements, and
methods in VBA
-

this will cause the keyword to be shadowed

if the keyword is to be called in code, it will need to be referenced as


follows:
VBA.keyword

B. Notes

VBA is not case-sensitive, but it preserves the capitalization in the statement


where the name is declared

Names within the same level of scope can not be repeated

For example, two variables named tank within the same procedure can not
be declared

However, a private variable named tank and a procedure-level variable


named tank can be declared within the same module.

Copyright 1999, Intellution, Inc.

3-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.2. Variables ________________________________________________


A. Used to store temporary values for use in later statements or calculations

Variables are declared using the Dim (dimension) statement

If you use a variable that has not been declared VBA will create it
-

Not recommended practice

Typically a variable type and scope is included when declared

B. Scope of variable can be one of three types

Procedure level
-

Module level
-

Only statements in the same procedure can access variable


Statements in multiple procedures have access to variable

Public Scope
-

Statements in different modules or projects have access to variable

C. The following is a list of variable data types and recommended characters usage

Boolean

bool

Byte

byte

Currency

cur

Date

dat

Decimal

dec

Double

dbl

Integer

int

Long

lng

Object

obj

Single

sng

String

str

Variant

var

Copyright 1999, Intellution, Inc.

3-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.2. Variables ________________________________________________

Figure 3-1: Data Type Help Screen

Copyright 1999, Intellution, Inc.

3-5

*()DQXF

3.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Integers ______________________________________________

A. Use to represent whole numbers

Property values, like an objects border style

Modes like None, Slow, and Fast

B. Integer Data Types

Byte
-

Integer (Short)
-

0 to 255, 8 bits/1 byte of memory


-32768 to 32767, 16 bits/2 bytes of memory

Long
-

-2,147,483,648 to 2,147,483,647, needs 32 bits/4 bytes of memory

C. Defining

Dim ival as Integer for short or end with %

Dim lval as Long for long or end with &

Dim bval as Byte for byte

Use as constants, like 1, 10000, or -32

Copyright 1999, Intellution, Inc.

3-6

*()DQXF

3.2.2.

ZZZML\LWHFKFRP


Student Guide

Floating Point _________________________________________

A. Use to represent numbers with fractional parts

Property values like screen position

Scaling factors

Two precision, single and double

B. Floating Point Data Types

Single
-

+/- sign (plus is assumed)

7 digit mantissa, with optional decimal point

2 digit exponential, optional 0 assumed

4 bytes of memory

from +/1.401298E-45 to +/-3.402823E38

Dim sval as Single for explicit declaration

sval! = 23.4 for implicit declaration

Use as constants like 1.45, 2.3E1, or 100!

Double
-

+/- sign (plus is assumed)

15 digit mantissa, with optional decimal point

3 digit exponential, optional 0 assumed

8 bytes of memory

from +/-4.94065645841247E-324 to +/-1.79769313486232E308

Dim dval as Double for explicit declaration

dval# = 23.4 for implicit declaration

Use as constants like 1.45#, 23E1#, or -2.3E-1#

Copyright 1999, Intellution, Inc.

3-7

*()DQXF

3.2.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

String Data ____________________________________________

A. Notes

There are two kinds of strings: variable-length and fixed-length strings.


-

variable-length string can contain up to approximately 2 billion (231)


characters

fixed-length string can contain 1 to approximately 64K (216) characters

B. String Concatenation

Use the & operator to build up a single string from several short ones

Example
-

mystring = "initial text"

mystring = mystring & " and more text"

Displayed string would be "initial text and more text"

C. String Conversions

For string operations VBA does numeric to string conversions

Example

mystring = object.name

mystring = mystring & ":" & object.foregroundcolor

Displayed string would be "object:255"

Copyright 1999, Intellution, Inc.

3-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.2.3. String Data _____________________________________________

Figure 3-2: Help - String Concatenation

Figure 3-3: Help - & Operator Example

Copyright 1999, Intellution, Inc.

3-9

*()DQXF

3.2.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Variant _______________________________________________

A. Variant type can hold all types of variables

If variable type is not declared it is considered a variant

Variants take more memory and must be converted to real type


-

Variant is only variable type that can contain a Null


-

Good practice would be to provide variables with a type


Null indicates that the Variant variable intentionally contains no valid data

Variant has its own unique default string value Empty


-

The value Empty denotes a Variant variable that hasn't been initialized

A Variant containing Empty is 0 if it is used in a numeric context and a


zero-length string ("") if it is used in a string context

Don't confuse Empty with Null

B. Note

To determine the data type of a Variant value, use the VarType function
-

See the Help for more information

C. Using the Variant Error value

In a Variant, Error is a special value used to indicate that an error condition has
occurred in a procedure
-

Unlike for other kinds of errors, normal application-level error handling


does not occur

This allows the developer, or the application itself, to take some


alternative action based on the error value

Error values are created by converting real numbers to error values using the
CVErr function

Copyright 1999, Intellution, Inc.

3-10

*()DQXF

3.2.4.

ZZZML\LWHFKFRP


Student Guide

Variant _______________________________________________

Figure 3-4: Help - Variant Variable

Copyright 1999, Intellution, Inc.

3-11

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.3. Declaring Variables _______________________________________


A. Declaring Variables

When declaring variables, Dim, Public, Static or Private keywords are used

The keywords provide the scope or availability to other procedures


-

Dim and Static keywords, used in a variable declaration statement ,can be


placed within a procedure to create a procedure-level variable

Dim, Public and Private keywords used in a variable declaration statement


may be placed at the top of a module, in the Declarations section, to create
a module-level variable

B. Notes on Variable Declaration

Use meaningful variable names


-

see page 3-3 for details

Variables can be passed to another procedure as an argument

Variables are initialized with a value by default


Numeric

Strings

(empty)

Dates

10/26/1998 14:23:00 PM (current time and date)

Boolean

False

Variants

Empty

User defined data types can be defined to provide a means to store more than one
type of data within a variable

Copyright 1999, Intellution, Inc.

3-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.3. Declaring Variables _______________________________________

Option Explicit
Dim intBeepCount As Integer
Dim dblObjRotAngle As Double
Static intVal As Integer
Public intTotalSales As Integer
Dim strAlarmext1 As String, strAlarmext2 As String
Dim TotHiAlms

Figure 3-5: Declaring Variable Example

Copyright 1999, Intellution, Inc.

3-13

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.3. Declaring Variables _______________________________________


C. Implicit vs. Explicit Declaration

Implicit Declaration
-

VBA does not require the user to declare a variable before using it

If VBA encounters an undefined variable, it creates one of type Variant

In general, this is not recommended

Explicit Declaration
-

Variant variables require more memory than most other variables

Explicit declaration allows for a better choice of data type and for
troubleshooting ease of use

Note:
-

Fixed arrays and dynamic arrays must be explicitly declared

D. Using the Option Explicit Statement

Determines whether explicit variable declarations are required in modules

Use Option Explicit declaration to ensure variable name has been declared

Enter Option Explicit at the top of a module

see Figure 3-5 for an example

An error will be generated when a name is used but not declared

Automatically adding Option Explicit


-

From the Tools menu in the VBE, select Options

Enable the Require Variable Declaration check box

Selecting this adds the Option Explicit statement to general declarations in


any new module

Copyright 1999, Intellution, Inc.

3-14

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.3. Declaring Variables _______________________________________

Figure 3-6: Requiring Explicit Variable Declaration

Copyright 1999, Intellution, Inc.

3-15

*()DQXF

3.3.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Variable Scope ________________________________________

A. Recall:

Scope is the availability of the variable or constant to other procedures

B. Using the Public Statement

Use the Public statement to declare public module-level variables

Public variables can be used in any procedures in the project


-

If a public variable is declared in a module, it can also be used in any


projects that reference the project where the public variable is declared

C. Using the Private Statement

Use the Private statement to declare private module-level variables

Private variables can be used only by procedures in the same module

Note:

When used at the module level, the Dim statement is equivalent to the
Private statement

Using the Private statement can make the code easier to read and interpret

D. Using the Static Statement

When you use the Static statement instead of a Dim statement, the declared
variable will retain its value between calls.

Copyright 1999, Intellution, Inc.

3-16

*()DQXF

3.3.2.

ZZZML\LWHFKFRP


Student Guide

Variable Lifetime _______________________________________

A. Understanding Lifetime

The time during which a variable retains its value is known as its lifetime

The lifetime is based on the how the scope of the variable was declared

When a variable loses scope, it no longer has a value

B. When a procedure begins running, all variables are initialized

A numeric variable is initialized to zero

A variable-length string is initialized to a zero-length string ("")

A fixed-length string is filled with the character represented by the ASCII


character code 0, or Chr(0)

Variant variables are initialized to Empty

Each element of a user-defined type variable is initialized as if it were a separate


variable

C. Variable scope

A variable declared at the module level retains its initialized or assigned value
until it loses scope

Scope is retained until the program is no longer running

Value is retained until the program is no longer running

A variable declared at the procedure level retains a value until the procedure is
finished running
-

If the procedure calls other procedures, the variable retains its value while
those procedures are running as well

If a procedure-level variable is declared with the Static keyword, the variable


retains its value just as if it was declared at the module level

If the Static keyword is used before a Sub or Function statement, the values of all
the procedure-level variables in the procedure are preserved between calls
-

Value is retained until the program is no longer running

Variables declared at the class module-level differ from other variables


-

In a class module, it retains its value as long as an instance of the class


exists

Module-level variables consume memory resources until you reset their


values, so use them only when necessary.

Copyright 1999, Intellution, Inc.

3-17

*()DQXF

3.3.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

User Defined Data Types ________________________________

A. Notes

A custom data type can be defined by using the Type statement

User-defined data types can contain one or more elements of a data type, an array,
or a previously defined user-defined type

B. The Type Statement

Used at module level to define a user-defined data type containing one or more
elements

See the Help for details on the syntax of the Type statement

The Type statement can be used only at module level

Once a user-defined type has been declared, a variable can be declared of


that type anywhere within the scope of the declaration

Use Dim, Private, or Public to declare a variable of a user-defined type

In standard modules, user-defined types are public by default


-

this visibility can be changed using the Private keyword

Copyright 1999, Intellution, Inc.

3-18

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.3.3. User Defined Data Types _________________________________

Type EquipmentLog

' Create user-defined type.

ID As Integer

' Define elements of data type.

Name As String * 20
Location As String * 30
LastMaint As Date
End Type

Sub CreateRecord()
Dim MyRecord As EquipmentLog

' Declare variable.

' Assignment to EquipmentLog variable must occur


' in a procedure.

MyRecord.ID = 12003

' Assign values to elements.

MyRecord.Name = "Vlv03"

MyRecord.Location = "Production Line 12"

End Sub

Figure 3-7: User Defined Data Type Example 1

Type AlarmType
almNodeName As String

' Stores Node Name.

almTagName As String

' Stores Tag Name.

almDate As Date

' Stores alarm date.

almValue As Integer

' Stores alarm value.

End Type

Figure 3-8: User Defined Data Type Example 2

Copyright 1999, Intellution, Inc.

3-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.4. Arrays __________________________________________________


A. Notes

An array is a single variable with many compartments to store values


-

A typical variable has only one storage compartment in which it can store
only one value

see Figure 3-7 for an example

An array is a set of values of the same data type

Refer to the array as a whole when you want to refer to all the values it holds, or
refer to its individual elements
-

For example, to store daily quantities for each day of the year, declare one
array variable with 365 elements, rather than declaring 365 variables

see Figure 3-8 for an example

in this example, an array is declared with 365 elements

an initial value of 100 is assigned to each element in the array

by default, an array is indexed beginning with zero, so the upper


bound of the array is 364 rather than 365

B. Changing the Lower Bound

Use the Option Base statement at the top of a module to change the default index
of the first element from 0 to 1
-

see Figure 3-9 for an example

Use a To clause to explicitly set the lower bound of an array


-

see Figure 3-10 for an example

strValue

Tank1

arrayValues

Tank1

Tank2

Tank3

Tank4

Figure 3-7: Array Example

Copyright 1999, Intellution, Inc.

3-20

Tank5

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.4. Arrays __________________________________________________

Sub FillArray()
Dim dailyQuantity(364) As Integer
Dim intI As Integer
For intI = 0 to 364
dailyQuantity (intI) = 100
Next
End Sub

Figure 3-8: Array Code Example

Option Base 1

Dim dailyQuantity(365) As Integer

Figure 3-9: Array Lower Bound Example 1

Dim dailyQuantity(1 To 365) As Integer

Figure 3-10: Array Lower Bound Example 2

Copyright 1999, Intellution, Inc.

3-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.4. Arrays __________________________________________________


C. Using Multidimensional Arrays

In VBA, arrays can have up to 60 dimensions


-

in most cases, one to three dimensions is enough

Think of the array as a matrix, where the first argument represents the rows and
the second argument represents the columns

Use nested For...Next statements to process multidimensional arrays

Example
-

The procedure in Figure 3-11 fills a two-dimensional array with Single


values

the array is a 2-dimensional, 5-by-10 array

D. Storing Variant Values in Arrays

There are two ways to create arrays of Variant values


-

One way is to declare an array of Variant data type, as shown in


Figure 3-12

The other way is to assign the array returned by the Array function to a
Variant variable, as shown in Figure 3-13

The elements in an array of Variant values are identified by index, no matter


which technique is used create the array
-

For example, the following statement can be added to either of the


preceding examples:

MsgBox "Data for " & varData(0) & " has been recorded."

Copyright 1999, Intellution, Inc.

3-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.4. Arrays __________________________________________________

Sub FillArrayMulti()
Dim intI As Integer, intJ As Integer
Dim sngMulti(1 To 5, 1 To 10) As Single
' Fill array with values.
For intI = 1 To 5
For intJ = 1 To 10
sngMulti(intI, intJ) = intI * intJ
Debug.Print sngMulti(intI, intJ)
Next intJ
Next intI
End Sub

Figure 3-11: Multiple Dimension Array Example

Dim varData(3) As Variant

varData(0) = "Intellution, Inc"


varData(1) = "One Edgewater Drive"
varData(2) = 02062
varData(3) = Format("01-01-1999", "General Date")

Figure 3-12: Variant Data Array Example 1

Dim varData As Variant


varData = Array("Intellution, Inc", "One Edgewater Drive", _
38, _ Format("01-01-1999", "General Date"))

Figure 3-13: Variant Data Array Example 2

Copyright 1999, Intellution, Inc.

3-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.5. Constants _______________________________________________


A. Notes

A named item that retains a constant value throughout the execution of a program

Use constants anywhere in VBA code in place of actual values

A constant can be a string or numeric literal, another constant, or any combination


that includes arithmetic or logical operators

B. User Defined Constants

User defined constants are declared within a procedure or at the module level
-

Module level constants can be public or private

Use the Const statement to declare a constant and set its value

After a constant is declared, it cannot be modified or assigned a new value

A constant can be declared within a procedure or at the top of a module, in the


Declarations section

Module-level constants are private by default

To declare a public module-level constant, precede the Const statement


with the Public keyword

A private constant can be explicitly declared by preceding the Const


statement with the Private keyword to make code easier to read

Copyright 1999, Intellution, Inc.

3-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.5. Constants _______________________________________________

' Constants are Private by default


Const TankLvl = 5000
' Declare Public constant
Public Const FilePath = "c:\dynamics"
' Declare Private Integer constant
Private Const MaxNumber As Integer = 16

' Declare multiple constants on same line.

Const MyStr = "Hello", MyDouble As Double = 3.4567

Figure 3-14: Declaring Constants Examples

Copyright 1999, Intellution, Inc.

3-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.5. Constants _______________________________________________


C. Predefined Constants

Built in predefined constants start with two-letter prefix

VBA constants start with vb

vbBlack, vbRed, vbGreen (color change)

vbOKOnly, vbOKCancel (MsgBox)

Excel constants start with xl


-

xlMminimized (minimize window)

xlNormal (normal window state)

Copyright 1999, Intellution, Inc.

3-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.5. Constants _______________________________________________

Constant
vbBlack
vbRed
vbGreen
vbYellow
vbBlue
vbMagenta
vbCyan
vbWhite
vbSunday
vbMonday
vbTuesday
vbWednesday
vbThursday
vbFriday
vbSaturday
vbKeyLButton
vbKeyRButton
vbKeyBack
vbKeyTab
vbKeyClear
vbKeyReturn
vbKeyShift
vbKeyControl
vbKeyMenu
vbKeyPause
vbKeyCapital
vbKeyEscape
vbKeySpace
vbKeyPageUp
vbKeyPageDown
vbKeyEnd
vbKeyHome
vbKeyLeft
vbKeyUp
vbKeyRight
vbKeyDown
vbKeySelect
vbKeyPrint
vbKeyInsert
vbKeyDelete
vbKeyHelp
vbKeyF1

Description
Black
Red
Green
Yellow
Blue
Magenta
Cyan
White
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Left mouse button
Right mouse button
Backspace Key
Tab Key
Clear Key
Enter Key
Shift Key
Ctrl Key
Menu Key
Pause Key
Caps Lock Key
Esc Key
Spacebar Key
Page Up Key
Page Down Key
End Key
Home Key
Left Arrow Key
Up Arrow Key
Right Arrow Key
Down Arrow Key
Select Key
Print Screen Key
Insert Key
Delete Key
Help Key
F1 Function Key

Constant
vbKeyNumlock
vbKeyMultiply
vbKeyAdd
vbKeySeparator
vbKeySubtract
vbKeyDecimal
vbKeyDivide
vbCr
vbLf
vbTab
vbCrLf
vbBack
vbOKOnly
vbOKCancel

vbYesNo

vbAbortRetryIgnore
vbYesNoCancel

vbRetryCancel

vbCritical
vbQuestion
vbExclamation
vbInformation
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
vbDefaultButton4

vbApplicationModal
vbSystemModal
vbOK
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo

Figure 3-15: Sample of VBA Predefined Constants

Copyright 1999, Intellution, Inc.

3-27

Description
Num Lock Key
Multiply sign (*) key
Plus sign (+) key
Enter key
Minus sign () key
Decimal point (.) key
Division sign (/) key
Carriage return char.
Linefeed character
Tab character
Carriage return
linefeed combination
Backspace character
OK button only
OK and Cancel
buttons
Abort, Retry, and
Ignore buttons
Yes, No, and Cancel
buttons
Yes and No buttons
Retry and Cancel
buttons
Critical message
Warning query
Warning message
Information message
First button is default
2nd button is default
3rd button is default
4th button is default
Application modal
message box (default)
System modal
message box
OK button pressed
Cancel button pressed
Abort button pressed
Retry button pressed
Ignore button pressed
Yes button pressed
No button pressed

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.6. Variable Data in Pictures __________________________________


A. Text Object

One of the easiest ways of displaying VBA variables in a picture is to use a Text
object in a picture

Within a script, simply set the value of the variable equal to the caption property
of the text object
-

Specifies the caption text of a Text object

See Figure 3-16 for an example

can be used to set the caption of the Window or Application object

B. Formatting the Text Object

Returns a String containing an expression formatted according to instructions


contained in a format expression

Example

Figure 3-17 shows various uses of the Format function to format values
using both named formats and user-defined formats

For the date separator (/), time separator (:), and AM/ PM literal, the
formatted output displayed depends on the local PC settings

MyTime and MyDate are displayed in the development environment using


current system short time setting and short date setting

Private Sub Text1_Click()


If Fix32.thisnode.tk9lvl_ai.f_cv > 0 Then
Text1.Caption = Fix32.thisnode.tk9lvl_ai.f_cv
Else
Text1.Caption = "Zero"
End If
End Sub

Figure 3-16: Using the Caption Property

Copyright 1999, Intellution, Inc.

3-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.6. Variable Data in Pictures __________________________________

Dim MyTime, MyDate, MyStr


MyTime = #17:04:23#
MyDate = #January 27, 1993#

' Returns current time in the system-defined long time format.


MyStr = Format(Time, "Long Time")

' Returns current date in the system-defined long date format.


MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")

' Returns "17:4:23".

MyStr = Format(MyTime, "hh:mm:ss AMPM")

' Returns "05:04:23 PM".

MyStr = Format(MyDate, "dddd, mmm d yyyy")


' Returns
"Wednesday, Jan 27 1993".

' If format is not supplied, a string is returned.

MyStr = Format(23)

' Returns "23".

' User-defined formats.


MyStr = Format(5459.4, "##,##0.00")
MyStr = Format(334.9, "###0.00")
MyStr = Format(5, "0.00%")

' Returns "5,459.40".


' Returns "334.90".
' Returns "500.00%".

MyStr = Format("HELLO", "<")

' Returns "hello".

MyStr = Format("This is it", ">")

' Returns "THIS IS IT".

Figure 3-17: Using the Format Function

Copyright 1999, Intellution, Inc.

3-29

*()DQXF

3.7.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

___________________________________________ Lab Exercise 3

Variables and Constants


Lab Exercise 3

Copyright 1999, Intellution, Inc.

3-30

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 3


Learning Objectives:
Upon successful completion of this lab exercise, you will be more familiar with locating and
manipulating various features in the VBE, the Visual Basic Editor. You will also learn to
work with variables, arrays, and constants. You will see variables used with differing scopes.
As you progress through this lab, you will:

Continue to work with the on-line help built into the WorkSpace and the VBE

Dimension variables used in the VB Editor

When you are finished with this lab, turn to page 3-45 and answer the Summary Questions.

Resources:
The iFIX On-line Help and E-Books
The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

During lecture you covered working with variables. This lab will give you some hands-on
with the VBA Editor and working with variables.

Copyright 1999, Intellution, Inc.

3-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 3


A. Importing a new code Module.
In the exercises up to this point, we have written all our code in event procedures. That
is, the code is triggered by an event. In this exercise, the code in the module will not be
triggered by an event, instead it is called from some other sub procedure.
1. Open the IngredientTank picture in the WorkSpace.
The picture should resemble the following:

2. With the picture open, go to the Visual Basic Editor.

Copyright 1999, Intellution, Inc.

3-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 3

3. From the Insert menu in the VBE, select Module


Notice in the Project Explorer that a module named Module1 has been added to the
project.
4. Using the Property Window, rename Module1 to ColorAssign
The screen should now resemble the following:

This module will contain constants that represent the 4 colors from the system default
color pallet. You will go on to create an array of these color values and
corresponding names.

Copyright 1999, Intellution, Inc.

3-33

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 3


B. Creating Constants.
Create constants to represent 4 colors from the default color palate.
1. Add the following lines of code to the module ColorAssign:
' This compiler option means all variables must
' be defined before run-time
Option Explicit
' iFIX primary colors as defined in the
' default color palette
Public Const FdBrightRedCLng As Long = 255
Public Const FdBrightYellowCLng As Long = 65535
Public Const FdBrightBlueCLng As Long = 16711680

Public Const FdBrightGreenCLng As Long = 65280

2. Lets examine this code. At the top we have the Compiler Option, Option Explicit.

When placed at the top of your module, VBA does not allow you to use variables
without declaring them first. Why is this a good thing? It prevents spelling errors
and typos from introducing major problems into your code.

3. Next we see 4 constants. It is good programming technique to declare constants after


the compiler options. Each of these constants represents a color used in VBA.
Instead of assigning ForegroundColor = 16711680 in your code, you can assign
ForegroundColor = FdBrightBlueCLng. This makes the code easier to read and
debug.
Using constants in place of cryptic numbers is another good programming technique.
We declare these constants Public because we want to use them not only in this
module but also in the event code for this project. If you know that other pictures
would also use these constants, then you should declare them in a module inside
Project_User which is where global procedures, variables and constants go.

Copyright 1999, Intellution, Inc.

3-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 3


C. Create User Defined Data Type.
Create a user defined data type to hold the color constant and a description.
1. Add the following lines of code to the module ColorAssign below the constant
declarations:
' User defined data type that allows us to have a table of
' VBA color values and color names we assign
Type FdColorChoicesUddt
FdPrimaryColorLng As Long

' Primary colors used in FIX

AltColorNameStr As String

' Description for the colors

End Type

2. Again, look at this new code. The user defined data type is very simple - it is simply
the name of a color and the numeric equivalent only two entries in our record.

The code should now resemble the following:

Copyright 1999, Intellution, Inc.

3-35

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 3


D. Create an Array.
Create an array of the new data type to store the color information.
1. Add the following lines of code to the module ColorAssign below the user defined
data type declarations:
'Create an array of the colors so we can easily choose one
'4 elements in this array 1..4
Public FdPriColor(1 to 4) As FdColorChoicesUddt
'this variable will be used to index the array
Public FdColorIndexByt As Byte

Because we know our array will not change (there are only 4 colors defined in this
exercise), we use a fixed-size array.

2. By now youve noticed the suffixes on the variables we have presented. In Visual
Basic, it is common to find these extensions used as prefixes. You can choose to
follow either convention, or you can choose not to append any data type indicator to
your variables. What ever you choose, the most important thing is that you stick with
your convention throughout your entire application.

Copyright 1999, Intellution, Inc.

3-36

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 3


E. Import a new Module.
Import a code module containing some color functions.
1. From the File menu, select Import File
2. Select the following file from the PIC directory:
ColorFunctions.BAS
Notice in the Project Explorer that a module named Module1 has been added to the
project.
3. Rename Module1 to ColorFunctions

4. This new code module has two functions. These two functions are public so that we
can call them from anywhere inside the project. You will find it necessary later in
this lab to call these functions from the event code of your picture

The function NewColor simply returns the next color in our array of colors.

Function ColorName takes the value of a color as an argument and returns the color
name if there is a match.

Functions and procedures will be covered in more detail later in the course.

Copyright 1999, Intellution, Inc.

3-37

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 3

The code for this imported module should resemble the following:

Copyright 1999, Intellution, Inc.

3-38

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 3


F. Adding event code.
Now that we have useful functions that we can call from our event code, we can finish off
the event code for the objects we have so far.
NOTE: Recall from earlier exercises that our picture, IngredientTank, belongs to a
class called CFixPicture. From the Event drop-down list, we see that the picture
has an Initialize event. Whereas Activate and Deactivate events happen every time
the picture gains or loses focus, the Initialize event happens only once, when the
picture is opened.
1. Add code to your ColorAssign module such that when the picture is first opened, we
call the code and load our color array with information. Remember the array holds
two types of data: the default color and the color name. Use color name defaults
red, yellow, blue, and green.

2. Name the procedure InitializeColorArray. To write the VBA code you need to
know the name of the array and the name of the two data types you will be setting.
You will be setting four elements of the array. You will have to do this twice within
the procedure. Once for the default color, and once for the default color name.
Hints:

Try using the following

arrayname(element).variablename = default

Add the following line as the last line in your procedure. This will preset the
index to 1 which is the color red
FdColorIndexByt = 1

Copyright 1999, Intellution, Inc.

3-39

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 3

3. To run the code when the picture opens , type the name of public sub procedure
InitializeColorArray in the CFixPicture Initialize event, as shown below:

Copyright 1999, Intellution, Inc.

3-40

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 3

4. Use the VBE Object drop-down list to select Tank1Rct, and use the Event dropdown list to select the Click event. Here, type the code that will change the
foreground color of our rectangle to a new color each time it is clicked. The code will
look something like the following:
Private Sub Tank1Rct_Click()
Tank1Rct.ForegroundColor = NewColor
End Sub

5. Again use the Event drop-down list, this time to select the DblClick event. Here type
the code that will change the edge color of our rectangle to a new color. Hint, this
code will be very similar to the previous step.

Copyright 1999, Intellution, Inc.

3-41

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 3


G. Adding additional code.
Now that we have useful functions that we can call from our event code, we can finish off
the event code for the objects we have so far.
1. Again use the Event drop-down list, this time to select the KeyUp event. When the
operator hits the <spacebar>, this is what we want to see in the WorkSpace.

2. How will we do this? First, we look into the on-line help to see what the arguments
for the KeyUp event do. We find that KeyCode returns the value of which key was
pressed, so if we want to test for the <spacebar> we would have a statement like:

If KeyCode = vbKeySpace Then

3. Next, we see the message box. Again we go to the on-line help to look up the
arguments for the MsgBox. If we want to display a message and prompt the operator
for a yes/no input, we would have a statement like:

If MsgBox(MessageStr, vbYesNo, "Object Properties") = vbYes Then

4. Next, we need to determine how to concatenate the message string. This is easy. We
first declare a local (not public) string variable like MessageStr. Then we set it equal
to our strings and properties using the ampersand ( & ) to concatenate everything.
But how do we put information on separate lines? Well give you a hint: Chr$(13).
Feel free to return to on-line help to see what this does.
5. Dont forget that .ForegroundColor and .EdgeColor return numeric values, not
names of colors. How do we convert the numeric values to names? We would have a
statement like: ColorName(.ForegroundColor). If you recall, ColorName is a
public function in the module we created.

Copyright 1999, Intellution, Inc.

3-42

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 3

6. What happens if the operator hits Yes? You will want to set the .ForegroundColor
= FdBrightBlueCLng, set the .EdgeColor = FdBlackCLng, and finally reset the
tank level with a statement like: .VerticalFillPercentage = 100
The entire procedure could look something like the following:

Copyright 1999, Intellution, Inc.

3-43

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 3


H. Save and Run.
Now that all the code has been added, save and switch to run mode to test the code.
1. Exit the VBE and return to the WorkSpace.
2. Save the changes to the picture.
3. Switch to run mode.
4. Click on the Rectangle and press the Space Bar.
The screen should resemble the following:

End of Lab Exercise

Copyright 1999, Intellution, Inc.

3-44

*()DQXF

ZZZML\LWHFKFRP


Student Guide

3.8. Summary Questions ______________________________________

1. If you want to set a variable to a property value, you should make sure both are the same
type, for example integer. How do you determine what data type a property is?

2. How do you create user-defined data types and why would you use them? Give
examples.

3. How do you create an array? What do you do if you dont know the size needed for the
upper bound of the array?

4. What is the purpose of the Option Base command when creating an array?

5. What is the difference between variable scope and variable lifetime?

Copyright 1999, Intellution, Inc.

3-45

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

3.8. Summary Questions ______________________________________

this page intentionally contains no data

Copyright 1999, Intellution, Inc.

3-46

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4. Procedures and Functions ___________________________________

Chapter 4
Procedures and Functions

Copyright 1999, Intellution, Inc.

4-1

*()DQXF

4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Procedures and Functions __________________________________

Section Objectives
This section provides an introduction to the different types of Procedures. The Object Browser
will be used to find out information on an objects properties, methods and events. Students will
work with VBA sub procedures and functions. This includes the following:

Sub Procedure and Function Scope

VBA References

Expressions

Object Browser

Copyright 1999, Intellution, Inc.

4-2

*()DQXF

4.

ZZZML\LWHFKFRP


Student Guide

Procedures and Functions __________________________________

Figure 4-1: VBA Icons

Copyright 1999, Intellution, Inc.

4-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.1. VBA References__________________________________________


A. Before working with an object you must set up a reference to the servers object library

References are accessed while in the VBE

iFIX automatically creates a references to its own object libraries when an object
is added to a Workspace project and edited in the VBE

To add a new reference highlight the project in the VBE in which the objects
reference will be used
-

From the Tools menu, select References and check the new library from
list

Reference list will contain object libraries and automation servers

Checked items are listed in priority

see Figure 4-2 for an example

Priority resolves object names which are the same

Unchecked items in the list are listed alphabetically

Checked references are available to browse in the Object Browser

The available list is based on the application installation and registry settings
-

Stored in Registry MyComputer\HKEY_CLASSES_ROOT\TypeLib\

Copyright 1999, Intellution, Inc.

4-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.1. VBA References__________________________________________

Figure 4-2: Reference Listing

Copyright 1999, Intellution, Inc.

4-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.2. Procedures ______________________________________________


A. VBA code that you write will be contained in procedures

Unit of code that performs a task

Two types of procedures


-

Sub procedures (subroutines)

Function procedures

Procedures are a units of code that performs a task

Procedures should be modular reusable code units

Procedures are run based on an event occurring or called by other procedures

B. VBE allows multiple ways to add procedures and code to a module:

From the VBE select the project then:


-

Select the object from object list

Select the event from the procedure list

A new sub procedure is inserted

Write code in the VBE

Or, select the object in the iFIX WorkSpace right click it and select edit script
-

Or, just start typing using proper syntax in the VBE workspace
-

A new sub procedure is inserted with the objects default event


Typically done this way when defining a sub procedure that will be called

Or, from the Input menu in the VBE, select Procedure


-

Brings up dialog box with selections

See Figure 4-3

Copyright 1999, Intellution, Inc.

4-6

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.2. Procedures ______________________________________________

Figure 4-3: Add Procedure Dialog Box

Private Sub Oval1_Click()


(Code Body)
End Sub

Figure 4-4: Default Script Example

Copyright 1999, Intellution, Inc.

4-7

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.2. Procedures ______________________________________________


C. Function Procedures perform a task and do return a value

Typically called when needed from a sub procedure

The returned value can be displayed to the user

Functions are often stored in modules that can be accessed globally

D. Sub Procedures perform a task but do not return a value

Example: On a click event a task is performed

Example: On picture initialize a task is performed

A procedure is called from another procedure and run

A project can contain as many sub procedures as needed

E. Predefined Procedures

VBA is full of predefined functions and sub procedures

Examples:

MsgBox displays an informational dialog box

InputBox displays a dialog box that accepts data from the user

DoEvents yields the VBA thread to the operating system

this will be discussed later in the course

Rnd returns a random number between 0 and 1

CInt convert value to an Integer

CStr convert value to a String

Beep Sounds a tone through the computer's speaker

See the Help for a complete list of functions

Copyright 1999, Intellution, Inc.

4-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.2. Procedures ______________________________________________

Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function

Private Sub CommandButton1_Click()


entry = InputBox ("Enter Temperature in Degrees F")
If entry = "" Then
MsgBox "No Value Entered"
Else

MsgBox "Temperature is " & Celsius(entry) & " Degrees C"


End If
End Sub

Figure 4-5: Procedure Example

Private Sub CommandButton1_Click()


Dim sngX As Single
Dim intY As Integer

sngX = Rnd

' generate a random number from 0 to 1

intY = CInt(sngX * 1000)

' convert value from 0 to 1000

Beep

' beep PC speaker

MsgBox "The value between 0 and 1000 is " & intY


End Sub

Figure 4-6: Random Number Example

Copyright 1999, Intellution, Inc.

4-9

*()DQXF

4.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Understanding Events __________________________________

A. Notes

An event is something that happens to an object

Examples:
-

Code can be written to respond to an event


-

click of a button, changing of text, opening a picture, closing a form


this code is referred to as an Event Procedure

Event procedures can be written in a picture code module or a form code module

B. The sequence of mouse-related events is:

MouseDown

MouseUp

Click

DblClick

MouseUp
-

MouseUp is listed twice because it is called again as part of DblClick

Copyright 1999, Intellution, Inc.

4-10

*()DQXF

4.2.1.

ZZZML\LWHFKFRP


Student Guide

Understanding Events __________________________________

Event

Occurs when

Activated

a window gets the user focus.

AfterKillFocus

focus is taken away from the Expression Editor control.

AlarmAck

an alarm is acknowledged.

Click

the user releases the left mouse key in the Run-time environment.

Close

a page container is shut down or closed in Run-time environment.

ColorChanged

a new color is selected in the Run-time environment.

DataChange

a data sources value changes by more than the deadband limit.

DblClick

the user double clicks the mouse in the Run-time environment

DeActivated

a window loses the focus (when another document receives focus).

Edit

the user double clicks an object in the Configuration environment, or the user
pastes an object into a page from a Dynamo Set.

EditChange

the text in the edit box portion of the Expression Editor is changed.

Initialize

a document is opened in the Run-time environment.

KeyDown

the user presses a key on the keyboard.

KeyUp

the user presses a key on the keyboard.

LmouseClick

the user clicks the left mouse button on the Alarm Summary object in the
Configuration or Run-time environment.

MouseDown

the user presses a mouse button.

MouseMove

the user moves the mouse over an object.

MouseUp

the user releases any of the mouse keys.

OnChange

the current value of a Variable object is changed.

OnChartFull

the data for a Chart object scrolls all the way to the right and hits the edge when
the ScrollDirection property is set to LeftToRight

OnChartRefresh

the Chart object's data automatically scrolls. The event occurs at an interval
defined by the RefreshRate property.

OnFalse

an expression in an Event object changes from non-zero to zero.

OnPenSelect

the user changes the currently active Pen by selecting another Pen.

OnTimeOut

a Timer Objects timeout period expires based on the TriggerType of the Timer.

OnTrue

an expression in an Event object changes from zero to non-zero.

RMouseClick

the user clicks the right mouse button on the Alarm Summary object in the
Configuration or Run-time environment.

WhileFalse

the value of an Event object is zero. This event is called back at an interval
specified by the Interval property of the Event object.

WhileTrue

the value of an Event object is non-zero. This event is called back at an interval
specified by the Interval property of the Event object.

Figure 4-7: Common VBA Events

Copyright 1999, Intellution, Inc.

4-11

*()DQXF

4.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Understanding Scope___________________________________

A. Scope of a Procedure

Scope refers to the availability of a procedure to be used by another procedure

There are two scope levels for procedures:


-

private module-level

public module-level

B. Private Procedures

Private means the procedure can only be used inside its own module

Private is default when editing a iFIX object

C. Public Procedures

Public means other projects can use the procedures or functions as well
-

Project must have established a reference to the other VBA project

D. Setting the scope for functions and sub procedures can be done when defining each
procedure or once at the top of the module for all procedures

For a individual procedure include the keyword private or public in the procedure
name definition

Public Sub CFixPicture_Initialize()

For all, set Option Private Module (or public) at the top of the module
-

Option Private Module

Copyright 1999, Intellution, Inc.

4-12

*()DQXF

4.2.2.

ZZZML\LWHFKFRP


Student Guide

Understanding Scope___________________________________

Option Explicit
Public Sub CFixPicture_Initialize()
Dim fixalarms As CfixAlarms
Set fixalarms = New CfixAlarms
End Sub

Private Sub Rect1_Click()


Dim nodeentry
Dim fixalarms As CfixAlarms
Set fixalarms = New CfixAlarms

nodeentry = InputBox("Enter Node Name")


fixalarms.NodeName = (nodeentry)

Text1.Caption = fixalarms.NodeName
End Sub

Private Sub Rect2_Click()


Dim tagentry
Dim fixalarms As CfixAlarms
Set fixalarms = New CfixAlarms
tagentry = InputBox("Enter TagName")
fixalarms.tagName = (tagentry)
Text2.Caption = (tagentry)
End Sub

Figure 4-8: Public and Private Procedures

Copyright 1999, Intellution, Inc.

4-13

*()DQXF

4.2.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Procedure Arguments __________________________________

A. Arguments (parameters) can be passed to a sub procedure or function

The arguments passed can be mandatory or optional

Use the optional keyword before the argument to make it optional

When using the optional keyword the function isMissing can be used in the VBA
code to determine if the argument was passed or not

Arguments are defined within the parentheses of the procedure or function


needing them and passed to them by the calling procedure

Arguments can be a variable, constant or expression

B. Arguments can be passed to the procedure in the order they appear in the procedure
definition or by name

Passing the argument in the defined order just requires the values to be passed
separated by a comma

Passing the argument by name requires using the argument name, followed by a
semi colon, followed by an equal sign and then the value

Each argument is separated by a comma but can be in any order

Copyright 1999, Intellution, Inc.

4-14

*()DQXF

4.2.3.

ZZZML\LWHFKFRP


Student Guide

Procedure Arguments __________________________________

Sub ProcedureName(argument1,optional argument2)


(Code Body)
End Sub

Figure 4-9: Argument Definition Example

Public Sub mywait(delay As Integer)

Dim starttime As Long


starttime = Timer
Do While Timer - starttime < delay

DoEvents
Loop

End Sub

Public Sub mycount()


Dim counter

For counter = 1 To 10
'display the counter message
Application.StatusBar = "Counter Value: " & counter
txtcount.Caption = "Counter Value: " & counter
mywait (5)
Next counter
End Sub

Figure 4-10: Using Arguments Example

Copyright 1999, Intellution, Inc.

4-15

*()DQXF

4.2.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Procedure Arguments __________________________________

C. Passing variables as arguments

Instead of declaring a variable at the module level to be used in any procedure a


variable can be passed from one procedure to another
-

Normally used if only a couple of procedures need to use the variable

Variables can be passed by Reference or by Value

D. Pass by Reference

By reference passes the pointer of the original variable to another procedure


-

Any changes made to the variable affect all procedures using it

By default, arguments are passed to procedures by reference unless specified


-

arguments passed by reference take the same amount of time to pass and
the same amount of space within a procedure regardless of the data type

the amount of space used is 4 bytes

E. Pass by Value

Passing an argument by value copies the original variable

Any changes made to the variable only affect that procedure using it

Changes to the argument within the procedure are not reflected back to the
original variable

Pass an argument by value by including the ByVal keyword in the procedure


declaration
-

Arguments passed by value consume from 2 16 bytes within the


procedure, depending on the argument's data type

Larger data types take slightly longer to pass by value than smaller ones

Because of this, String and Variant data types generally should not
be passed by value

F. Example

See Figure 4-11

Without including ByVal in the function declaration, the preceding Print


statements would display 1 and 0
-

This is because MyVar would then refer to variable S, which is reduced by


1 until it equals 0

Copyright 1999, Intellution, Inc.

4-16

*()DQXF

4.2.3.

ZZZML\LWHFKFRP


Student Guide

Procedure Arguments __________________________________

Function Factorial(ByVal MyVar As Integer)


MyVar = MyVar - 1
If MyVar = 0 Then
Factorial = 1
Exit Function
End If
Factorial = Factorial(MyVar) * (MyVar + 1)
End Function

Public Sub PrintFactorial()

Dim S As Integer
S = 5

Debug.Print Factorial(S)

Debug.Print S

End Sub

Figure 4-11: Argument Passing Example

Copyright 1999, Intellution, Inc.

4-17

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.2.4. Expressions ____________________________________________


A. Used to establish relationships among variables and program objects

Variables are useless unless you do something with them


-

Expressions are often what is to the right of the =


-

Expressions are that something


see Figure 4-12 for examples

Think of them as a mini user defined function


-

Just like a function, an expression returns a result

However, an expression completes in one statement

Programmer defines the expression

Functions can be called and used in multiple statements


-

Many functions are pre-defined

Programmer can define custom functions

Provide a variable with a value

B. Expressions will allow you to do many things

Mathematical calculations

Format numbers, strings, dates, time, etc.

Compare values

Produce Boolean results

Combine variables and other values

Copyright 1999, Intellution, Inc.

4-18

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.2.4. Expressions ____________________________________________


C. Expressions use operands and operators

Operands are input values used by the expression


-

Variables, Object properties, Functions, Literal

Operators are symbols that combine the operands to produce a result


-

Assignment operator

Arithmetic operators

+, -, *, /, \, ^, Mod

Comparison operators

=, >, <, >=, <=, <>, Like

Logical operators

And, Eqv, Imp, Or, Xor, Not

Concatenation operator

&

message = "Thanks for the message"

Application.StatusBar = "Counter Value: " & counter

Celsius = (fDegrees - 32) * 5 / 9

Figure 4-12: Example Expressions

Copyright 1999, Intellution, Inc.

4-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.2.4. Expressions ____________________________________________


D. Predefined Functions are one of the operands that can be used in an expression

Math functions
-

Can be used to convert the result of an expression

Example: Square root, cosine, absolute value

Financial functions
-

Can be used to calculate the results on an expression

Example: Rate, payment, future value

String functions
-

Can be used to convert the result of a string expression

Example: Trim characters, convert to uppercase, send character code

Date and time functions

Can be used to convert the result of an expression to Time or Date values

Example: Convert expression result to date, day or time

Format function
-

Can be used to format how the result of an expression looks

Example: Add dollar sign, comma, percent sign

Numeric data type conversion function


-

Changes the result of expression to particular data type

Example: Currency, integer, byte

E. Example

Celsius function call


-

ReadValue queries the F_CV value directly from the database

The value returned by ReadValue is passed to the Celsius function

The converted value returned by Celsius is passed to the MsgBox for


display

See Figure 4-13

Copyright 1999, Intellution, Inc.

4-20

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.2.4. Expressions ____________________________________________

Figure 4-13: Writing a Function Example

Copyright 1999, Intellution, Inc.

4-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.3. Code Locations __________________________________________


A. VBA code can reside in a number of areas

As part of a iFIX Picture project


-

Associated with the iFIX picture

Associated with one or more forms

Included in a user defined module

Within a Class Module

As part of the FIX Globals Page


-

Project name is Project_User

Associated with one or more forms

Included in a user defined module

Within a Class Module

In other projects
-

In modules that can be accessed publicly

B. Before creating code, decide where the code should reside by considering the following:

Will the code be shared among other projects?

Are there common functions that need to be shared?

Are there common forms that need to be shared?

Is it of value to store code in a module instead of the picture?

Does code need to be available globally?

Copyright 1999, Intellution, Inc.

4-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.3. Code Locations __________________________________________

Figure 4-14: Code Locations

Copyright 1999, Intellution, Inc.

4-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.3.1. Class Modules __________________________________________


A. Understanding Class Modules

Class modules and regular code modules are both just a place in which to write
code but differ in what code is inside the module
-

Acts as a place to hide and protect code

Class modules are an extension of user defined data types discussed in the
Variables section

Instead of static data that makes up a user defined data type a Class Module will
represent a new object with its own characteristics

B. Using Class Modules

The Class module will contain code that defines a template for a new object and
its properties and methods
-

The Class module does not contain the object but rather creates it when
the code is invoked

When all is done the new object can be used like any other object accessing and
changing its properties and using its methods

Copyright 1999, Intellution, Inc.

4-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.3.1. Class Modules __________________________________________

Figure 4-15: Displaying Class Properties Example

Copyright 1999, Intellution, Inc.

4-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.3.1. Class Modules __________________________________________


C. VBA code that creates a class object and its readable properties

After declaring a new object members are added to represent the properties

Members are internal class variables usually designated with the m_

Get procedures returns the current value of a property

Used to define what properties will return a value

Must be defined in the class module

D. VBA code that creates a class object and its changeable properties

Let procedure lets the user assign new values to the properties

Must be defined in the class module

Option Explicit

Dim fixalarms As New CfixAlarms


Private m_almNodeName As String
Private m_almTagName As String
Private m_almDate As Date
Private m_almValue As Integer

Public Property Get NodeName() As String


NodeName = m_almNodeName
End Property
continued on next page...

Figure 4-16: Creating a Class Module Script Example

Copyright 1999, Intellution, Inc.

4-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.3.1. Class Modules __________________________________________

Public Property Get tagName() As String


tagName = m_almTagName
End Property

Public Property Get almDate() As Date


almDate = m_almDate
End Property

Public Property Get almValue() As Integer


almValue = m_almValue

End Property

Public Property Let NodeName(node As String)


m_almNodeName = node

End Property

Public Property Let almDate(newdate As Date)


m_almDate = newdate

End Property

Public Property Let tagName(Tag As String)


m_almTagName = Tag
End Property

Public Property Let almValue(newVal As Integer)


m_almValue = newVal
End Property

Figure 4-16: Creating a Class Module Script Example (continued)

Copyright 1999, Intellution, Inc.

4-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.4. Object Browser __________________________________________


A. Understanding Objects

Objects have their own set of properties, methods and events which can be used to
control the object

A group of objects of the same type is called a collection

Application objects will be represented in an Object Model

B. The Object Browser will help to keep track of all the objects in a Object Model

Lists all objects, properties, methods, constants and events

Search text capability

Use whole word search to ensure valid response

C. Notes

The available object libraries reflect available references that are checked in the
VBE Reference list

From the Tools menu, select References

Copyright 1999, Intellution, Inc.

4-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.4. Object Browser __________________________________________

Copyright 1999, Intellution, Inc.

Figure 4-17: VBE Object Browser

4-29

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.4. Object Browser __________________________________________


D. The Object Browser contains various windows

Library and projects list drop down window


-

Search text window


-

Enter a search string

Example foreground

Search result window


-

Lists libraries and projects referenced by any module

Shows library, class and member of search

Classes window
-

Shows available object classes for selected library

Shows globals such as enumerations for selected library

Shows methods, properties and events for selected class

Display by group or alphabetically

Code template window

Members window

Displays code you can paste into a module

copies an object property to a variable

Copyright 1999, Intellution, Inc.

4-30

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.4. Object Browser __________________________________________

Figure 4-18: VBE Object Browser Search Function

Copyright 1999, Intellution, Inc.

4-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.5. The With Statement _______________________________________


A. Notes

Executes a series of statements on a single object or a user-defined type

Allows for the specification of an object or user-defined type once for an entire
series of statements
-

Makes code run faster and helps avoid repetitive typing

Once a With block is entered, object can't be changed


-

As a result, a single With statement can not affect a number of different


objects

With statements can be nested by placing one With block within another

Do not jump into or out of With blocks

B. Example:

To change a number of different properties on a single object:


-

place the property assignment statements within the With control structure

refer to the object once instead of referring to it with each property


assignment

Figure 4-19 illustrates use of the With statement to assign values to several
properties of the same object

Copyright 1999, Intellution, Inc.

4-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.5. The With Statement _______________________________________

With MyObject
.Height = 100
.Caption = "Hello"

' Same as MyObject.Height = 100


' Same as MyObject.Caption = "Hello"

With .Font
.Color = Red

' Same as MyObject.Font.Color = Red

.Bold = True

' Same as MyObject.Font.Bold = True

End With
End With

Figure 4-19: With Statement Example

Copyright 1999, Intellution, Inc.

4-33

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

4.6. Hints and Tips ___________________________________________


A. Moving Code

Code and be dragged and dropped within the Code Window

Drag selected code to:


-

A different location in the current Code window

Another Code window

The Immediate and Watch windows

The Recycle Bin

B. Code View

Use the Procedure View and Full Module View buttons at the bottom of the Code
Window
-

Full Module View allows for viewing of all procedures in a module

procedures are separated by a procedure separator

Procedure View shows only one procedure in the window at a time

C. Split Window

From the Window menu of the VBE, select Split

Dragging this bar down, splits the Code window into two horizontal panes, each
of which scrolls separately
-

This allows for viewing of different parts of the code at the same time

The information that appears in the Object box and Procedures/Events box applies
to the code in the pane that has the focus

Dragging the bar to the top or the bottom of the window or double-clicking the
bar closes a pane

D. Formatting Code

Use indenting to make code more readable

Select a section of code, and press <TAB> or <SHIFT><TAB> to increase or


decrease the indentation
-

Alternatively, use the Indent buttons on the Edit toolbar

Copyright 1999, Intellution, Inc.

4-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.6. Hints and Tips ___________________________________________


E. Commenting Code

It is good practice to comment code to add readability

Use Comment Block to comment out a section of code


-

This is useful when debugging

Use UnComment Block to return the code to normal

Comment Block and UnComment Block are on the Edit toolbar

F. List Properties/Methods

The Intellisence of VBA provides a list of applicable properties and methods as


code is typed

This can be forced by pressing <CRTL> J

G. List Constants

When entering functions that accept enumerated values as parameters, VBA can
list available constants

This can be done by pressing <CRTL><SHIFT> J

H. Parameter Information

When entering parameters into functions, VBA can display a list of the
parameters, data types, and any default values

This can be done by pressing <CRTL><SHIFT> I

I. Word Completion

VBA can complete words as they are typed

This can be done by pressing <CRTL><SpaceBar> as the code is being typed

Copyright 1999, Intellution, Inc.

4-35

*()DQXF

4.7.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Exercise Example _______________________________________

A. Level of the tank (in centimeters, cm)

The tank has a level transmitter


-

values from 0 to 100%

The height of the tank goes from 0 to 160 cm


-

0 to 70 in the tapered end, and 70 to 160 in the cylindrical end

B. Volume of the tank (in cubic centimeters, cm3)

Multiply the area inside the tank with the current height to get the volume

Volume above 70 cm (the cylindrical end)


-

Use the formula in Figure 4-20 to determine the volume of a cylinder

where the height is really h-70, and where r = 55

Volume below 70 cm (tapered end of tank)


-

Ra = the radius of the lower end of the cone

for this tank, Ra = 10

Be sure to add the value of the total volume of the tapered end!

Rb = the radius of the cone at the level of the tank

for this tank, Rb =

9
h + 10 , where h = the level of the tank
14

See Figure 4-21 for the formula for this tank

V = (r 2 )(h 70)

h( Ra 2 + ( Ra )( Rb ) + Rb 2 )
3
90 2 27 3
= (100 h +
h +
h )
14
196

V =

= (3025)( h 70)
Figure 4-20: Formula for Volume of
a Cylinder (top part of tank)

Copyright 1999, Intellution, Inc.

Figure 4-21: Formula for Volume of


a Cone (bottom part of tank)

4-36

*()DQXF

4.7.

ZZZML\LWHFKFRP


Student Guide

Exercise Example _______________________________________

110

100%

Level Transmitter

90

Rb

Ra
0%

20

Figure 4-22: Tank used in Lab Exercise 4

Copyright 1999, Intellution, Inc.

4-37

70

*()DQXF

4.8.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

___________________________________________ Lab Exercise 4

Mathematical Functions
Lab Exercise 4

Copyright 1999, Intellution, Inc.

4-38

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 4


Learning Objectives:
Upon successful completion of this lab exercise, you will be more familiar with creating
function procedures and working with the existing VBA math functions. You will continue
to work with variables, arrays, and object properties as you did with previous exercises.
As you progress through this lab, you will:

Revisit some of the naming conventions talked about in the previous lab.

Work with some of the math functionality built into VBA

Build your own math functions for converting between English and Metric
units

When you are finished with this lab, turn to page 4-49 and answer the Summary Questions.

Resources:

The iFIX On-line Help and E-Books


The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

During lecture you covered the Object Browser, working with procedures, building
expressions, numeric variable data types. This lab will give you plenty of hands-on with the
VBA Editor, working with variables, building expressions, and working with function
procedures.
You will be helped along with some hints but for the most part you will be left to your own
devices.

Copyright 1999, Intellution, Inc.

4-39

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 4


A. Develop a VBA function for converting between units of measure
With this lab you will see how you can build your own math functions for converting
values between units of measure. You will then create additional code to call the
function providing it with a new parameter and finally displaying the result to the user.
1. Open the picture called WaterTank in the configure mode of the WorkSpace. You
should see a picture that looks similar to the following:

Copyright 1999, Intellution, Inc.

4-40

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 4

2. Switch to Run mode and you can see that some of the functionality exists.

Notice the following:


(a)

The Level Transmitter displays values from 0 to 100%. This information is


coming from a database tag called TK9LVL_AI

(b)

The temperature displays values from 60 to 212 degrees F. This information is


coming from a database tag called TK9TMP_AI

(c)

The Actual Level and the Volume values never change this is the goal of this
exercise

(d)

As you move the mouse over the tank, the level decreases. Double click the
tank to fill it. Or you can manually enter a percentage in the text object.

(e)

As you move the mouse over the thermometer, the temperature increases.
Double click the thermometer to set the temperature to 60. Or you can
manually enter a temperature in the text object.

Copyright 1999, Intellution, Inc.

4-41

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 4

3. With the WorkSpace in Run mode, from the Workspace menu, select Visual Basic
Editor.
The screen should resemble the following:

Make sure the current project selected in the Project Browser is the WaterTank
picture.

Copyright 1999, Intellution, Inc.

4-42

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 4


B. Create a function to convert percent to centimeters.

1. Insert a new module into Project_WaterTank.


This module will be used to store the new function procedures.
2. Rename the new module using the following:
TankCalcs
3. Insert a new procedure into this new module.
The new procedure will be a function with a public scope and will have the following
name:
PercToCm
This function will be used to convert the percent of the level transmitter to a value in
centimeters.

4. Because the relationship between the level transmitter (0 to 100) is linear with the
level of the tank (0 to 160), it is easy to determine the level of the tank in centimeters.
Use the following formula:

8
centimenters = percent
5

Therefore, your function in VBA code should resemble the following:


Public Function PercToCm(ByVal Percent as Double)
' this function converts a percent from 0 to 100
' into a value in centimeters from 0 to 160.

PercToCm = (8 / 5) * percent

End Function

Copyright 1999, Intellution, Inc.

4-43

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 4

5. From the View menu in the VBE, select Immediate Window


The Immediate Window appears at the bottom of your Code Window
6. Use the Print keyword to test your formula in the Immediate window. Here are a
few test cases for you to try:
Print PercToCm (0) =

Print PercToCm (100) = 160


Print PercToCm (50) =

80

When finished, the code should resemble the following:

Copyright 1999, Intellution, Inc.

4-44

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 4


C. Viewing the Data in a Picture.
Create an event script such that, when the user clicks on the text object displaying the
level in centimeters, the value is updated.
1. Now, return to the WorkSpace configure mode.
2. Right mouse click on the text object representing the Actual Level in Centimeters and
select Edit Script
The VBE opens to the WaterTank Module and a new event procedure is created.
3. Create code in that procedure that does the following:
(a)

Passes the value of FIX32.THISNODE.TK9LVL_AI.F_CV to the new


PercToCm function.

(b)

Takes this new value and sets it equal to the caption of the Actual Level text
object.

Hints: This new code is event code, not simply some function.

Make sure you put the code in the correct place. It belongs in the picture
module.
Use the Text objects caption property
This procedure can be completed in one line of code!

4. When you feel this is working correctly, move on to the next page.

Copyright 1999, Intellution, Inc.

4-45

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 4


D. Create the functions to convert level to volume.
We need to determine the volume of the tank. However, the tank is oddly shaped. It is
really a cylinder on top of a cone. So, we will create three functions: one to determine
the volume of a cylinder, one to determine the volume of a cone, and one to add them
together.
1. Insert three new functions into the TankCalcs module.
The new functions will have public scope and will have the following names:
volumeCone
volumeCylinder
volumeTank
2. volumeCone - Use the following formula to determine the volume of a cone:

Volume = (100 h +

90 2 27 3
h +
h )
14
196

where h is the height (or level) of the tank in centimeters.

3. volumeCylinder - Use the following formula to determine the volume of a cylinder:

Volume = (3025)(h 70)

where h is the height (or level) of the tank in centimeters.

Hints: Use the PercToCm function as a model when creating these two functions.
Both of these functions use . If you want the easy way out, just create a
variable for equal to 3.14159. Or, if you want a more accurate answer, use
the on-line Help to get a better value for !

Copyright 1999, Intellution, Inc.

4-46

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 4

4. Now, the easy part is determining the height of the whole tank, right? Well, not quite.
Remember, we need to determine if the level of the tank is greater than 70 or not. If
it is less than 70, we simply use the cone volume. If the level is greater than 70, we
use the cylinder volume and add in the full cone volume. The code for this will look
something like this:
Public Function volumeTank(ByVal h As Double)
If h <= 70 Then
volumeTank = volumeCone(h)
Else
volumeTank = volumeCone(70) + volumeCylinder(h)
End If
End Function

5. Test your formula in the Immediate window. Here are a few test cases for you to try:
volumeCone (70) =

269,391.57

volumeCylinder (160) =

855,298.60

volumetank (160) =

1,124,690.17

volumetank (0) =

0.00

6. Now, go back to the WorkSpace configure mode. Create an event script such that,
when the user clicks on the text object displaying the volume, the value is updated.
Obviously, you will need the functions you just created.
Hints: This new code is event code, not simply some function.
Make sure you put the code in the correct place.
Use the Text objects caption property
This procedure can be completed in one line of code!
Use the previous example as a model.
7. Save your picture when finished.

Copyright 1999, Intellution, Inc.

4-47

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

CHALLENGE LAB ________________________________ Lab Exercise 4


If you are finished with the exercise and other students are working, feel free to try these
challenge exercises.
A. Advanced functions.
Here are a few somewhat advanced exercises to try. Make sure the first part of the
application is working before trying these.
1. Use an Event Object in the picture to update the level and the volume whenever the
value in the database changes by more than one percent. Do not use a loop to do this!
2. Change the application so that only two decimal digits appear in the text objects in
the picture.

3. Create a push button on the screen to change the temperature displayed in the link
between Celsius and Fahrenheit. The conversion function is in a Module within the
WaterTank project. Make sure to change the text label too!

4. After completing the step above, have the same pushbutton change the level to
display values in inches and display volume in gallons. The conversion function is in
a Module within the WaterTank project. Make sure to change the text label too!

End of Lab Exercise

Copyright 1999, Intellution, Inc.

4-48

*()DQXF

ZZZML\LWHFKFRP


Student Guide

4.9. Summary Questions ______________________________________

1. List some ways you can use the Object Browser.

2. How can you set the scope for a function or sub procedure? Is there a way to make a
function or sub procedure global / accessible to all pictures?

3. Lets say you needed to work with a function such as inverse cosine. You quickly
discover that inverse cosine does not exist as a function in VBA. How do you derive the
function for inverse cosine? (Hint take a look at the on-line help).

4. What is the difference between division using the forward slash / and division using
back slash \ ?

5. VBA is very forgiving when it comes to data type conversion. If you dont specify the
proper data type, VBA will do the conversion for you, although not always the way you
might expect. There is a special set of functions to handle conversion between type
what are these functions?

Copyright 1999, Intellution, Inc.

4-49

*()DQXF

4.9.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Summary Questions _____________________________________

this page intentionally contains no data

Copyright 1999, Intellution, Inc.

4-50

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5. VBA Debugging ____________________________________________

Section 5
VBA Debugging

Copyright 1999, Intellution, Inc.

5-1

*()DQXF

5.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA Debugging __________________________________________

Section Objectives
In this section you will become familiar with how to use the debugging tools of the Visual Basic
Editor. Topics to be discussed in this section include the following:

Customizing the Visual Basic Editor

Syntax errors

Common errors

Immediate window

Break point insertion and removal

Watch window

Display variable contents while halted

Copyright 1999, Intellution, Inc.

5-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.1. Review__________________________________________________
A. Project Structure

Projects
-

Each picture (*.GRF) is a VBA project

VBA code within a project can reside in Modules, Class modules, and/or
user forms

Code Modules
-

Module code can exist in the picture document, user defined modules or
Class modules

Within a module, code is divided into procedures

Procedures
-

A self contained block of VBA code that performs a specific task or


returns a value

A procedure can either be a sub procedure or a function

B. Visual Basic Editor


Code Window

Project Explorer
-

displays the code of the selected picture, module, or class module


displays all the VBA projects currently opened in the WorkSpace

Properties Window
-

displays the properties of the selected object

Copyright 1999, Intellution, Inc.

5-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.2. Customizing the VBE _____________________________________


A. Toolbars

There are four default toolbars available in the VBE


-

Standard

Edit

Debug

UserForm

From the View menu, select Toolbars

B. Menu Bar

Items can be added to the drop-down menus in the VBE

From the View menu, select Toolbars, and select the Commands Tab
-

simply drag the commands to the appropriate menu option to add it

Copyright 1999, Intellution, Inc.

5-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.2. Customizing the VBE _____________________________________

Figure 5-1: Available Toolbars

Figure 5-2: Customizing the Menu Bar

Copyright 1999, Intellution, Inc.

5-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.3. Introduction to Debugging _________________________________


A. There are basically four types of errors to debug

Syntax errors
-

Compile errors
-

these errors are detected when the program executes

Runtime errors
-

these errors are generally detected as the code is written

these errors can be dealt with using Error Handlers, which is covered later
in the course

Logic errors
-

these are generally the hardest errors to deal with

this chapter focuses on approaching logic errors

B. VBE has mechanisms to help you to debug your code

Pausing a procedure

Stepping through a procedure

Monitoring values in a procedure

Dynamically plug in new values to variables for expressions

C. VBE debug tools will include:

Watch Window

Breakpoints

Immediate Window

Locals Window

Quick Watch

Call Stack

VBE View Menu

Copyright 1999, Intellution, Inc.

5-6

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.3. Introduction to Debugging _________________________________

Figure 5-3: Commonly used Debugging Tools

Copyright 1999, Intellution, Inc.

5-7

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.4. Understanding Errors _____________________________________


A. Most syntax errors are caught by VBA when you enter statements

Misspelled keywords, missing keyword, incorrect punctuation

VBA converts font of statement to red when syntax error encountered

VBA may also provide a error message


-

Example message: Expected: List separator or )

Syntax errors occur immediately as statement is created and at the following:


-

Compile before switching to Run mode

Compile while in Run mode

When executing a module while in Run that has changed

B. Compile errors occur as VBA looks at the code you run

The statement with the problem is highlighted


Example: Statement with a missing End If

Message is created providing information on error

C. Runtime errors occur during the execution of a procedure

Could be method or property with wrong object

Could be divide by zero error

Runtime errors produces a dialog box

Message in dialog box may not be very descriptive

Have a choice to select the debug button on dialog box

May have to use more debug tools to find problem

D. Logical errors are harder to find

No error messages are created

Logic may produce incorrect results

Procedure may be stuck in loop

Statements do not function

May have to trace through a procedure one step at a time

May need to check individual variables to ensure they are correct

Copyright 1999, Intellution, Inc.

5-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.4. Understanding Errors _____________________________________

Figure 5-4: Syntax Error displayed at compile time

Copyright 1999, Intellution, Inc.

5-9

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.5. Debugging Tools _________________________________________


A. Setting breakpoints is one way to enter break mode

Break Mode is a state which VBA is paused while executing

After setting breakpoints you can step through your procedure

Combined with the debugging windows you can monitor values in your statement

The script stops before running the statement at which the breakpoint exists

B. Using breakpoints

Breakpoints can be set a number of ways in the VBE


-

Click on left margin of code window on each statement to set breakpoint

Place cursor on statement and from the Debug menu, select Toggle
Breakpoint

Place cursor on statement RMC select Toggle Breakpoint

Use keyword Stop within the code

When breakpoint reached during execution, the program halts and VBE is
displayed

You can Inspect data values before breakpoint

Breakpoints can be set at most statements except comments and labels

Figure 5-5: Data Tips Window

Copyright 1999, Intellution, Inc.

5-10

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.5. Debugging Tools _________________________________________

Figure 5-6: Break Points in the VBE

Copyright 1999, Intellution, Inc.

5-11

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.5.1. Stepping Through Procedures ____________________________


A. Stepping Into a procedure means you will execute one line

Use with or without breakpoints

If you are debugging you will be using breakpoints

To step into a procedure:

From the Debug menu, select Step Into, or

Press F8, or

Select the Step Into button on Debug Toolbar

Note to enable the ability to step through a procedure expecting an argument


passed, comment out the argument definition

B. Stepping Over a procedure is useful when a procedure calls another procedure

You may not want to step through the called procedure


-

Note: Called procedure still runs normally you just dont step through it

Step to the procedure you want to step over or set a breakpoint at the procedure

To step over the procedure:

From the Debug menu, select Step Over, or

Press SHIFT-F8, or

Select the Step Over button on Debug Toolbar

C. Stepping Out allows you to get out of a procedure without stepping through it

To step out of a procedure:


-

From the Debug menu, select Step Out, or

Press CTRL-SHIFT-F8 or

Select the Step Out button on Debug Toolbar

Copyright 1999, Intellution, Inc.

5-12

*()DQXF

5.5.1.

ZZZML\LWHFKFRP


Student Guide

Stepping Through Procedures ___________________________

Figure 5-7: Breakpoint Insertion and Immediate Window

Copyright 1999, Intellution, Inc.

5-13

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.5.2. Immediate Window ______________________________________


A. Immediate Window will allow you to evaluate the value in an expression

Type or paste expressions into the window

To evaluate an expression set a breakpoint within a procedure

Type ? or Print then the expression in the immediate window

Press Enter to execute the statement

The value of the expression will be displayed

B. Viewing the Immediate Window

From the View menu, select Immediate Window

It can be Dockable or Floating

C. The Immediate can also be used as a place to send information while script executes

See Figure 5-9 for an example

Use the Call keyword to call a sub routine from the Immediate Window

D. Additional Notes

The Immediate Window can hold 200 lines of output


-

Use the Debug.Print expression to send data to the Immediate Window

As it fills, information scrolls down the window

To clear the Immediate Window, press <CTRL><SHIFT><HOME> to select all


the code to the top of the window, and then press <DEL> to delete it

Copyright 1999, Intellution, Inc.

5-14

*()DQXF

5.5.2.

ZZZML\LWHFKFRP


Student Guide

Immediate Window _____________________________________

Figure 5-8: Immediate Window

Public Function PercToCm(percent)

' this function converts a percent of 0 to 100


' to a value in centime ters from 0 to 160.
PercToCm = (8 / 5) * percent
Debug.Print PercToCm

End Function

Figure 5-9: Sending Data to the Immediate Window

Copyright 1999, Intellution, Inc.

5-15

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.5.3. Watch Window__________________________________________


A. Watch Window is used to view the value of a watch expression

Watch expression is an expression in your code that VBA evaluates automatically

Watch expression defines what you want to monitor

Need to set up a watch expression before monitoring it in the Watch Window

Use the Add Watch function to add new items to monitor

Highlight item in script and drag and drop into watch window

Edit watch window using RMC to change or add items

Watch Window will allow you to determine values in your expressions


-

Variables

Constants

Property values

Functions

Operators

Object values

All of the above must evaluate to a single value

Figure 5-10: Add Watch Window

Copyright 1999, Intellution, Inc.

5-16

*()DQXF

5.5.3.

ZZZML\LWHFKFRP


Student Guide

Watch Window ________________________________________

Figure 5-11: Watch Window

Figure 5-12: Watch Window (shown in VBE)

Copyright 1999, Intellution, Inc.

5-17

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.5.4. Quick Watch____________________________________________


A. Quick Watch evaluates expressions on the fly

While in break mode select an expression, select Quick Watch

Display what module you are in

Inspect variable values during breakpoints and steps

B. Viewing the Quick Watch dialog box

From the View menu, select Locals Window, or

SHIFT-F9 or

Quick Watch button on Debug toolbar

Copyright 1999, Intellution, Inc.

5-18

*()DQXF

5.5.4.

ZZZML\LWHFKFRP


Student Guide

Quick Watch __________________________________________

Figure 5-13: Quick Watch Dialog

Copyright 1999, Intellution, Inc.

5-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.5.5. Locals Window _________________________________________


A. Locals Window allows monitoring of all variables in the current procedure

Display variables that are dimensional in the current procedure

View variable that changes as you step through the program

Variables appear in the window when being accessed

Do not have to define what variables to monitor

B. Viewing the Locals Window

From the View menu, select Locals Window

Dockable

Floating

Copyright 1999, Intellution, Inc.

5-20

*()DQXF

5.5.5.

ZZZML\LWHFKFRP


Student Guide

Locals Window ________________________________________

Figure 5-14: Locals Window

Copyright 1999, Intellution, Inc.

5-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.5.6. VBE Call Stack__________________________________________


A. VBE Call stack is a list of the active procedure calls

Basically shows a chain of procedure calls

Current procedure is on top of list

The procedure that called the current procedure is next

Sometimes problems are in the procedure that calls another procedure

B. From the View menu, select Call Stack or the click the ellipsis button in the Locals
Window

Display what module you are in

Display the current procedure

Display all the procedures that were called

Figure 5-15: Call Stack Window

Copyright 1999, Intellution, Inc.

5-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.5.7. VBE Debug Floating Toolbar ______________________________


A. VBE debug floating toolbar

Brings all the Debugging features to a convenient place

Useful for controlling breakpoint and step operations

Launches all debugging window

Figure 5-16: Debug Toolbar

Copyright 1999, Intellution, Inc.

5-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.6. Style and Technique ______________________________________


A. Comments

Comments can explain a procedure or a particular instruction to someone reading


the code
-

VBA ignores comments when it runs a procedure

Comment lines begin with an apostrophe (') or with Rem followed by a space
-

Comments can be added anywhere in a procedure

To add a comment to the same line as a statement, insert an apostrophe


after the statement, followed by the comment

By default, comments are displayed as green text

B. Indenting

By Indenting sections of code, the code is easier to read and troubleshoot

Shifts all lines in the selection to the next tab stop


-

All lines in the selection are moved the same number of spaces to retain
the same relative indentation within the selected block

Change the tab width on the Editor tab of the Options dialog box

C. Bookmarks

Bookmark areas in code to make that line standout

Use the bookmark tool to mark as many areas in the code as you want
-

the bookmark tools allow for quick searches to the next or previous
bookmark in a code module

Copyright 1999, Intellution, Inc.

5-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.6. Style and Technique ______________________________________

Figure 5-17: Code Style Example

Copyright 1999, Intellution, Inc.

5-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.7. Hints and Tips ___________________________________________


A. Removing Breakpoints

Remove all breakpoints in code at once by:


-

From the Debug menu, select Remove All Breakpoints, or

CTRL-SHIFT-F9

B. Changing Values in the Local Window

Double-click the Value column enter a new value

This is a good way to test special cases in the code

C. Using Watch Expressions

If an expression is highlighted before opening the Add Watch dialog box, VBA
will automatically fill in the Expression field with the highlighted expression

D. Writing to the Immediate Window

Use Debug.Print as an easy way to get information to the screen

Alternatively:

use a MsgBox when it is not practical to keep the Immediate Window


open

write to a Text object (caption property) when it is not practical to have a


MsgBox open

E. Use Explicit Declaration

Make sure Option Explicit is in the declaration section of all modules

F. Comment out whole procedures

Use the comment tool to comment out all the statements in a procedure

Copyright 1999, Intellution, Inc.

5-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.7. Hints and Tips ___________________________________________

Key Stroke

Description

F1

Get context-sensitive Help on functions, statements, methods, properties,


or events.

F2

Display the Object Browser.

SHIFT+F2

Go to the definition of the selected procedure.

CTRL+SHIFT+F2

Go back to the last position in your code.

F3

Find Next: repeat text search down through your code. If no text search
has been done, the Find dialog box is displayed.

SHIFT+F3

Find Previous: repeat text search up through your code. If no text search
has been done, the Find dialog box is displayed.

F4

Display the Properties window (design time only).

F5

Run a Sub/UserForm or macro.

ALT+F5

Runs the error handler code or returns the error to the calling procedure.
Does not affect the setting for error trapping on the General tab of the
Options dialog box.

F6

Switch between Code window panes (when the window is split).

F7

Open the Code window for the selected object.

CTRL+F7

Move the insertion point into the Object box.

F8

ALT+F8

Execute code one line at a time (single step).


Steps into the error handler or returns the error to the calling procedure.
Does not affect the setting for error trapping on the General tab of the
Options dialog box.

SHIFT+F8

Execute code one procedure at a time (procedure step).

F9

Set or remove a breakpoint.

CTRL+SHIFT+F9

Clear all breakpoints.

SHIFT+F10

View shortcut menu.

Figure 5-18: Function Key Shortcuts

Copyright 1999, Intellution, Inc.

5-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.7. Hints and Tips ___________________________________________

Key Stroke

Description

CTRL+C

Copy the selected text to the Clipboard.

CTRL+G

Displays the Immediate window.

CTRL+I

Turn on Quick Info.

CTRL+SHIFT+I

Turn on Parameter Info.

CTRL+J

Turn on List Properties/Methods.

CTRL+J

Bring to front (affects overlapping controls at design time only).

CTRL+SHIFT+J

Turn on List Constants.

CTRL+K

Send to back (affects overlapping controls at design time only).

CTRL+V

Paste the Clipboard contents at the insertion point.

CTRL+X

Cut the selected text to the Clipboard.

CTRL+Y

Cut the current line to the Clipboard.

CTRL+Z

Undo the last editing action in the current line.

CTRL+SPACEBAR

Turn on Complete Word.

Figure 5-19: Standard Keyboard Shortcuts

Key Stroke

Description

SHIFT+CTRL+ALPHA

Select a property in the Property list of the Properties window.

ALPHA

Enter a value in the Properties window for the selected property.

CTRL+CLICK

Add or remove a control from the selection.

CLICK+DRAG

Select multiple controls.

SHIFT+CLICK

Select multiple controls.

CTRL+CLICK+DRAG

Add or remove controls from the current selection.

Double-click on the split bar

Delete the split bar.

Figure 5-20: Miscellaneous Shortcuts

Copyright 1999, Intellution, Inc.

5-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.7. Hints and Tips ___________________________________________

Key Stroke

Description

CTRL+BACKSPACE

Delete to the beginning of the word.

CTRL+BREAK

Stop running a Visual Basic application.

DELETE or DEL

Delete the selected text or controls without placing them on the


Clipboard.

CTRL+DELETE

Delete to the end of the word.

END

Go to the end of the line.

CTRL+END

Go to the end of the module.

HOME

Go to the beginning of the line.

CTRL+HOME

Go to the beginning of the module.

PAGE DOWN

Page down through the procedures in your code.

CTRL+PAGE DOWN

Go to the bottom of the current procedure.

PAGE UP

Page up through the procedures in your code.

CTRL+PAGE UP

Go to the top of the current procedure.

TAB

In a form, cycle forward through controls in tab order.

CTRL+TAB

Switch between windows.

SHIFT+TAB

SHIFT+TAB

In a form, cycle backward through controls in tab order.


Remove indent.

Figure 5-21: Special Keyboard Shortcuts

Key Stroke

Description

CTRL+DOWN ARROW

Display the next procedure.

CTRL+UP ARROW

Display the previous procedure.

CTRL+RIGHT ARROW

Go one word to the right.

CTRL+LEFT ARROW

Go one word to the left.

Figure 5-22: Arrow Key Shortcuts

Copyright 1999, Intellution, Inc.

5-29

*()DQXF

5.8.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

___________________________________________ Lab Exercise 5

Debugging Techniques
Lab Exercise 5

Copyright 1999, Intellution, Inc.

5-30

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 5


Learning Objectives:
Upon successful completion of this lab exercise, you will be more familiar with using the
VBA debugging tools.
As you progress through this lab, you will:

Practice using the VBA debugging tools on code created in a earlier exercise

Use the VBA debugging tools on broken code

When you are finished with this lab, turn to page 5-41 and answer the Summary Questions.

Resources:
The iFIX On-line Help and E-Books
The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

During the lecture you were introduced to the debugging tools that are used with VBA. This
lab will give you plenty of hands-on work with these tools.

Copyright 1999, Intellution, Inc.

5-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 5


A. Practicing with existing code
First, we will practice using the Debugging tools on some code from an earlier exercise.
1. Open the picture called WaterTank in the configure mode of the WorkSpace.
You should see a picture that looks similar to the following:

2. Switch to Run mode and make sure the picture works correctly.
3. Open the VBE and look at the three code modules associated with this picture. They
are:
WaterTank
Conversions
TankCalcs

Copyright 1999, Intellution, Inc.

contains the code for the WaterTank picture


contains conversion functions
contains the function used to determine tank volume

5-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 5

4. The code for TankCalc should resemble the following (but dont worry if it is not
exactly like this):
Public Function PercToCm(ByVal Percent As Double)
PercToCm = (8 / 5) * Percent
End Function

Public Function volumeCone(ByVal h As Double)


volumeCone = 4 * Atn(1) * (100 * h + (90 / 14) * _
(h ^ 2) + (27 / 196) * (h ^ 3))

End Function

Public Function volumeCylinder(ByVal h As Double)

volumeCylinder = 4 * Atn(1) * 3025 * (h - 70)

End Function

Public Function volumeTank(ByVal h As Double)


If h <= 70 Then
volumeTank = volumeCone(h)
Else
volumeTank = volumeCone(70) + volumeCylinder(h)
End If
End Function

Note that the comments have all been removed to conserve space, but you should be
sure to document your code clearly! That is a great debugging tool too!

Copyright 1999, Intellution, Inc.

5-33

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 5

5. Now, experiment with some of the debugging tools discusses in this chapter. Be sure
to try the following:
Setting Breakpoints
Stepping into/through code
Immediate Window
Locals Window
Watch Window
Using Bookmarks
VBE Call Stack

Copyright 1999, Intellution, Inc.

5-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 5


B. Debugging some buggy code
In this part of the exercise, you will be working with a picture called IngredientTanked.
The new picture has two problems. First it dumps to debug on initialization, and second
the color of the rectangle stays at red when the Tank is clicked on.
1. With the WorkSpace in Configure mode, open the picture called IngredientTanked.
The following screen appears:

2. Switch to Run mode and notice VBE debug comes up immediately.


3. The VBE has two code modules associated with this picture. They are:
ColorAssign
ColorFunctions

Copyright 1999, Intellution, Inc.

contains the code for assigning colors


contains color functions

5-35

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 5


C. Using the Locals window

1. The debug stopped in the InitializeColorArray procedure. The first thing we want to
do is find out information using the Locals window.
2. Open the Locals window and you should see the ColorAssign module with a plus
sign. You can click on the plus sign to see the initialized values.

Since the script stopped, it has not completed initialization.

3. Notice anything in the window seeming out of place? Fix the problem.

Use Intellisense Data Tips to help identify the problem.

Copyright 1999, Intellution, Inc.

5-36

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 5


D. Using Breakpoints to verify it works

1. To make sure the problem is fixed and it no longer dumps to debug, return to
WorkSpace configure mode then back to Run mode to re-initialize.
2. Because the code will no longer stop on its own, a breakpoint must be set. Many
times you may want to force the code to stop. In this case we want to look at the
information after initialization to ensure the code did what we wanted.
3. To set a breakpoint, open the VBE and double click on ColorAssign module to bring
the code into View. Scroll down to the InitializeColorArray code.

4. Place a breakpoint at the End Sub statement in this procedure. This will bring up the
VBE directly after initialization.

5. Return to WorkSpace Configure mode than to Run mode and the VBE should pop up.
Check the results.

6. Check the Locals window again to ensure the initialization information is now correct
and the erroneous entry no longer exists in the Locals window.
7. Remove breakpoint.

Copyright 1999, Intellution, Inc.

5-37

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 5


E. Using the Watch window

1. Now that our picture is initializing correctly, check to see if the colors change when
the Tank1Rct is clicked
2. Notice it turns Red but not any other colors. We may want to check the actual value
using the Watch window then step through code to find more information.
3. Open the VBE then from the Debug menu add a Watch window. For the expression
add the picture name IngredientTanked. For the procedure and module select All.
4. Notice in the Watch window there is a plus sign on IngredientTanked. Drill down to
Tank1Rct and ForegroundColor to find current color.

5. We now know the color value of Tank1Rct is 255(Red) which of course we could see
but we now know how to find the value using the Watch window.

Copyright 1999, Intellution, Inc.

5-38

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 5


F. Using Intellisense while Stepping through code

1. Now lets look further - dock the Watch window so it is available.


The code for IngredientTanked should be active code window in the VBE.
2. Find the Click event for Tank1Rct, place the cursor in the procedure, and press the F8
key. This will start stepping through code.
3. Stepping into the Tank1Rct click event will bring you to the function called
NewColor. This is where the color of the rectangle gets changed by increasing the
color index that will correspond to the color array elements.

4. Place the cursor on the first line of the NewColor function on top of the text
FdColorIndexByt. The intellisense will show the current value.

5. Continue to step through the code a number of times emulating multiple clicks.

Notice the FdColorIndexByt does not increment. It resets to empty, changes to 1


and resets again. No wonder the color does not change.

6. To track this better, highlight the text FdColorIndexByt and drag it into the Watch
window. This will make it easier to track.

Copyright 1999, Intellution, Inc.

5-39

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 5


G. Using Definition function

1. The definition function points to where in the code a variable or constant is defined.
If it does not recognize it the variable has not been defined or misspelled. To try this,
highlight FdColorIndexByt. Go to the VBE View menu and select Definition.
2. That is strange - it seems it is not recognized. This is a variable that needed to be
defined somewhere!
That explains something else. Notice in the Watch window, what type
FdColorIndexByt is. A Variant! Do we want it to be a Variant? No!
VBA makes a variables type a Variant if it does not know the type or Option
Explicit is not set and it creates new variables on the fly even if a spelling error
occurs.

3. This is a clue that Option Explicit was not used and the variable definition is
spelled wrong. Check this out in the ColorAssign module where FdColorIndexByt
is defined.

4. Its those little things. Now if the variable name was fixed. Step through the code
you should see the indexing work 1-4, and the color values change.

All this can be seen from the Watch window without having to go to the WorkSpace
to test.

End of Lab Exercise

Copyright 1999, Intellution, Inc.

5-40

*()DQXF

ZZZML\LWHFKFRP


Student Guide

5.9. Summary Questions ______________________________________

1. What is a breakpoint? How are they added? How can they be used?

2. One could argue that Quick Watch Expressions are not often needed when debugging
VBA code. Why is this?

3. Which window can be used to watch the value of a variable change while the script is
running?

4. Why is it is good idea to explicitly declare variables?

5. What is the purpose of the Calls Stack dialog?

Copyright 1999, Intellution, Inc.

5-41

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

5.9. Summary Questions ______________________________________

this page intentionally contains no data

Copyright 1999, Intellution, Inc.

5-42

*()DQXF

ZZZML\LWHFKFRP


Student Guide

6. Introduction to Forms _______________________________________

Section 6
Introduction to Forms

Copyright 1999, Intellution, Inc.

6-1

*()DQXF

6.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Introduction to Forms ______________________________________

Section Objectives
In this section you will become familiar with these Microsoft Forms and Entry objects supplied
via the VBA engine. Topics to be discussed in this section include the following:

VBA MSForm

Forms - Events, Methods, and Properties

Form Controls

Copyright 1999, Intellution, Inc.

6-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

6.1. Forms Overview__________________________________________

Label

Windows NT
iFIX Container

Picture Object - Name: Tankview

Picture Object - Name: Profile


ForegroundColor: 255 VerticalPostiton:25

FIX2D Object - Name: Profile


FIX2D Object - Name: Xaxis

FIX2D Object - Name: Text1

Keyboard
Mouse
NIC
Modem

Serial Port

MSForm - Name: OpMess


HorizontalPostiton: 35
VerticalPostiton:25
Event VBA
Code

Text Object
Label Object
Button Object

Object Event VBA Code

Scheduler Project1

Scheduler

User Global Routines

Container Support Code

User Global Variables

FIX32 Database

FIX Global Subroutine

Figure 6-1: Container Diagram


Copyright 1999, Intellution, Inc.

6-3

Hard Drive

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

6.1. Forms Overview__________________________________________


A. MsForms are Objects

Forms are objects that will be a part of a VBE project

The forms object is actually a collection object containing controls that provide
a means of user interaction with the application
-

Check Boxes, Toggle Buttons, List Boxes

Scroll Bars, Spin Buttons, Multipage

TabStrip, Text Labels

Forms are associated with a iFIX picture document

Forms are separated from the picture document in the VBE project

Each form has its own event code module

Form design can emulate a windows style dialog box

Figure 6-2: Form Example

Copyright 1999, Intellution, Inc.

6-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

6.1. Forms Overview__________________________________________

Figure 6-3: Predefined Forms Example

Copyright 1999, Intellution, Inc.

6-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

6.2. Creating a Form __________________________________________


A. In the VBE menu Insert a form in a VBA project

Use the Insert menu from the VBE command bar

Adjust form to desired size

Add appropriate controls to the form

Add VBA code for Form object and control objects

Change any form properties such as caption as needed

Forms have their own set of properties, methods and events that will be used to
manipulate the form and from controls

Using sizing controls on toolbar to center, make same size and align

B. Additional Notes on Forms

VB and VBA forms are not interchangeable

However, VB5.0 can import and use forms from VBA

Forms in Access are not interchangeable with other MS 97 applications

Forms can be exported and imported (.FRM)

Forms can be dragged to another project

Make forms meaningful


-

From the properties window change the name to a meaningful name

Change the caption to something the user would understand

Copyright 1999, Intellution, Inc.

6-6

*()DQXF

ZZZML\LWHFKFRP


Student Guide

6.2. Creating a Form __________________________________________

Figure 6-4: Operator Request Creation (Configure Mode)

Figure 6-5: Operator Request Creation (Run Mode)

Copyright 1999, Intellution, Inc.

6-7

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

6.2. Creating a Form __________________________________________


C. Placing objects on the form

The objects added to forms are called ActiveX controls


-

these controls are components that are added to a form to exhibit some
behavior when the form is run

Adding controls to the form from the toolbox


-

Click on the entry object to be added in the toolbox

Then click on the form in the upper left corner of the item's initial position

Hold the mouse down and drag the control to the desired size

Some typical controls are shown in the Toolbox below

Select Object
Label
Text Box

Combo Box
List Box
Check Box
Option Button
Toggle Button
Frame

Figure 6-6: Default Form Toolbox

Command Button
Tab Strip
MultiPage
Scroll Bar
Spin Button
Image

Figure 6-7: Default Form Toolbox

Copyright 1999, Intellution, Inc.

6-8

*()DQXF

6.2.1.

ZZZML\LWHFKFRP


Student Guide

Form Controls _________________________________________

A. Select Objects

Select Objects is the only item in the Toolbox that doesn't draw a control

Select it to resize or move a control that has already been drawn on a form

B. Label

Used for placing descriptive text on the screen

Used for accelerator key markers in the tab order

Properties
-

Name is the name used by any VBA script or Tab order efforts

Caption is the actual text shown

Accelerator is the short cut key to position on the following object

C. Text Box

Used for displaying information to the user

Needs a label for accelerator key marker in the tab order

Used for querying information from the user

Properties

Name is the name used by any VBA script or Tab order efforts

Text is the actual text shown

Copyright 1999, Intellution, Inc.

6-9

*()DQXF

6.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Form Controls _________________________________________

D. Command Button

Command Buttons are typically used to accept selections in the forms or to cancel
without any changes

Runs command on mouse click

Properties

If cancel property is true the button is selected when user presses Esc

Caption is the text on the button

If default property is set to true the button is selected when user presses
Enter

Example (see Figure 6-8)


-

This form shows a pre defined list of directories with an accept button and
a cancel button

Figure 6-8: Button Object Example

Copyright 1999, Intellution, Inc.

6-10

*()DQXF

6.2.1.

ZZZML\LWHFKFRP


Student Guide

Form Controls _________________________________________

Private Sub CommandButton1_Click()


Dim iDoc As Object
comboval = ComboBox1.Value
If ComboBox1.Value = "" Then
MsgBox "No Path Selected"
Else
Set iDoc = Application.Documents.Open(comboval)
End If

Unload Me
End Sub

Figure 6-9: Accept Button Code

Private Sub CommandButton2_Click()


Unload Me
End Sub

Figure 6-10: Cancel Button Code

Copyright 1999, Intellution, Inc.

6-11

*()DQXF

6.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Form Controls _________________________________________

E. List Box

The ListBox is the simplest of the user selection controls

Used to allow user a selection from a list of items

Pre configure the selections available or allow other VBA script to set using the
additem method

Properties

MultiSelect property allows user to select multiple items

Value property represents user selection

Example
-

Figure 6-11 shows a form using a ListBox

F. Check Box

Displays the selection state of an item

Use a CheckBox to give the user a choice between two values such as Yes/No,
True/False, or On/Off

When the user selects a CheckBox, it displays a special mark (such as an


X) and its current setting is Yes, True, or On

If the user does not select the CheckBox, it is empty and its setting is No,
False, or Off

Depending on the value of the TripleState property, a CheckBox can also


have a null value

If a CheckBox is bound to a data source, changing the setting changes the value of
that source

A disabled CheckBox shows the current value, but is dimmed and does not allow
changes to the value from the user interface

Copyright 1999, Intellution, Inc.

6-12

*()DQXF

6.2.1.

ZZZML\LWHFKFRP


Student Guide

Form Controls _________________________________________

Figure 6-11: Example showing List Box and Check Box

Copyright 1999, Intellution, Inc.

6-13

*()DQXF

6.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Form Controls _________________________________________

G. Frame

Used to organize a set of controls into a logical group

Controls inside a frame are treated as a unit, moving the frame moves the controls

Used to organize option buttons so only one can be selected

Properties
-

Name is the name used by any VBA script or Tab order efforts

Caption is the actual text display on the frame

H. Option Buttons

Used to allow user a selection choice

Typically only one option at a time can be selected from a group

Properties

If value property is true the button is activated

Use GroupName property for the options you want to group

If buttons are not grouped by a frame or GroupName property all option


buttons on form are treated as a group

I. Toggle Buttons

Toggle button is in a state of pressed or unpressed

Properties
-

If value property is true button is in pressed state

Copyright 1999, Intellution, Inc.

6-14

*()DQXF

6.2.1.

ZZZML\LWHFKFRP


Student Guide

Form Controls _________________________________________

J. Image

Displays a picture on a form

Use it to display a picture as part of the data in a form


-

The Image allows for cropping, sizing, or zooming a picture


-

Example - display equipment photographs in a maintenance form


It does NOT allow you to edit the contents of the picture

The Image supports the following file formats:


-

*.bmp

*.ico

*.cur

*.jpg

*.gif

*.wmf

Figure 6-12: Example showing Frame, Option Button, Toggle Button, and Image

Copyright 1999, Intellution, Inc.

6-15

*()DQXF

6.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Form Controls _________________________________________

K. Combo Box

The ComboBox combines the text box with the list box
-

Drop down displays text box

User has option to type directly into textbox

Properties
-

Value property represents user selection

MatchRequired property forces user to type only what is in list

L. Spin Buttons

Clicking a SpinButton changes only the value of the SpinButton

Code can be written that uses the SpinButton to update the displayed value of
another control

Example: use a SpinButton to scroll through a range of values or a list of items, or


to change the value displayed in a text box
-

see Figure 6-14

Figure 6-13: Combo Box Control

Copyright 1999, Intellution, Inc.

6-16

*()DQXF

6.2.1.

ZZZML\LWHFKFRP


Student Guide

Form Controls _________________________________________

Private Sub UserForm_Initialize()

SpinButton1.Value = 50
SpinButton1.Max = 100
SpinButton1.Min = 0

End Sub

Private Sub SpinButton1_SpinDown()

TextBox1.Text = SpinButton1.Value - 1

End Sub

Private Sub SpinButton1_SpinUp()

TextBox1.Text = SpinButton1.Value + 1

End Sub

Figure 6-14: Spin Button Example

Copyright 1999, Intellution, Inc.

6-17

*()DQXF

6.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Form Controls _________________________________________

M. Scroll Bars

Used by themselves will allow the user to select a value between a predefined
minimum and maximum value

Properties
-

Value property returns or sets current value of the scroll bar

LargeChange returns or sets the amount the value changes when user
clicks between scroll bars

SmallChange returns or sets the amount the value changes when user
clicks one of the scroll arrows

N. Tab Strips

Used to show different data in the same controls by tabbing

Same set of controls are shown in each tab

Can show a series of buttons instead of tab strip

O. MultiPage

Each tab represents a separate form called a page

Shows a new set of controls each time the user selects a tab

Each page is a separate object

Copyright 1999, Intellution, Inc.

6-18

*()DQXF

6.2.1.

ZZZML\LWHFKFRP


Student Guide

Form Controls _________________________________________

Figure 6-15: Additional Control Examples

Copyright 1999, Intellution, Inc.

6-19

*()DQXF

6.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Adding New Controls ___________________________________

A. Customize the Toolbox by

Adding pages to it

Adding controls to an existing page


-

using the Additional Controls command from the Tools menu

B. Adding New Pages

To add a new page, simply right click an existing tab and choose New Page

Rename the tab by right clicking the tab and selecting Rename

When a page is added, a Select Objects tool is always available on the page

C. Adding Controls to a Page

To add a new control to a page, simply right click a blank part of the page and
choose Additional Controls
-

a list of the registered ActiveX Controls appears

Copyright 1999, Intellution, Inc.

6-20

*()DQXF

6.2.2.

ZZZML\LWHFKFRP


Student Guide

Adding New Controls ___________________________________

Figure 6-16: Adding Pages and Adding Controls

Figure 6-17: Additional Controls Dialog Box

Copyright 1999, Intellution, Inc.

6-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

6.3. Launching the Form ______________________________________


A. Click and Edit events

Click event can be used in a button or any other object in a iFIX picture

Click event is invoked while in the iFIX Workspace run mode

The event code can launch the form by using the forms Show method

Key event can be any key on the keyboard like F5 and can be defined to a single
picture document or across all picture documents

Edit event can be used to launch form from the VBE for testing

Note that forms are modal, forms must be unloaded or hidden before any other
user events take place

Private Sub Rect5_Click()

UserForm1.Show

End Sub

Copyright 1999, Intellution, Inc.

Figure 6-18: Click Event Code

6-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

6.4. Form Events _____________________________________________


A. Form Events

VBA code can monitor and react to events once the form is displayed

Basic events like Click, DoubleClick, KeyUp and KeyDown

B. Other form events that can add value:

Initialize
-

Called when form is first loaded via a Load or Show method

Entry objects should be initialized here

Activate
-

Called when the form becomes active or gains focus

Called when the form's Show method is used

Deactivate
-

Called when the form becomes inactive or loses focus

Also called when the form's Hide method is used

Terminate

Called when the form is unloaded

Any cleanup, like copying values, should be down here

Copyright 1999, Intellution, Inc.

6-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

6.5. Form Hints and Tips ______________________________________


A. Modality

A UserForm is modal unless code is written to allow focus on another object


while the form is still loaded and visible
-

When modal the user must respond before using any other part of the
application

When modal no subsequent code is executed until the UserForm is hidden


or unloaded

B. Understanding Me

Use the Me keyword to refer to the current instance of the object where the code
is running

All procedures associated with the current object have access to the object
referred to as Me

Using Me is particularly useful for passing information about the current instance
of an object to a procedure in another module

Example:
-

use Unload.Me to unload the current form

Copyright 1999, Intellution, Inc.

6-24

*()DQXF

6.6.

ZZZML\LWHFKFRP


Student Guide

___________________________________________ Lab Exercise 6

Using Forms
Lab Exercise 6

Copyright 1999, Intellution, Inc.

6-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 6


Learning Objectives:
Upon successful completion of this lab exercise, you will be comfortable working with forms
to solicit input from the operator. Forms can also be used for presenting information in a
well visually organized manner. For example, you could have an application where you click
on a tank and the click event brings up a form describing real-time plant-floor attributes
about that tank. With this exercise we continue to build and leverage the information you
learned in previous labs while incorporating forms as another tool for you to use.
As you progress through this lab, you will:

Build a form that will be used later to log maintenance information

Build a form that displays specific layers in a picture.

When you are finished with this lab, turn to page 6-38 and answer the Summary Questions.

Resources:

The iFIX On-line Help and E-Books


The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

The first part of the lab will work create a more complex form that will contain option
buttons, check boxes, frames, and more.
The second form you create will allow you to display any combination of sets of objects.
This is done using layers. We will guide you through information that talks about layers.

Copyright 1999, Intellution, Inc.

6-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 6


A. View an existing picture.
Open a picture that displays equipment maintenance information.
1. Open the MaintOverview picture in the WorkSpace in configure mode
The screen should resemble the following:

2. Switch to Run mode to explore the functionality of this picture.


This screen shows the down-time of various equipment in the application.
Occasionally the status of the equipment goes into Maintenance mode as part of the
application.
You can force the equipment into Maintenance mode by clicking the Maint Now
button. After a minute or two, the status returns to a normal status.
3. Experiment with the Maint Now buttons to understand the pictures functionality.

Copyright 1999, Intellution, Inc.

6-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 6


B. Insert a new form.
Create a form that takes information from the user and create a log file.
1. Switch to the VBE
2. Insert a new form into the MaintOverview project
3. Rename the new form frmMaintLog
The screen should resemble the following:

Copyright 1999, Intellution, Inc.

6-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 6


C. Add Objects to the Form.

When finished, the form you will create will look like the following:

Use this picture as a model as you add controls to the form. It is very important to
use the object names as defined in the exercise. Otherwise, the code samples will not
work correctly.

1. Change the form caption to Log Maintenance Report

2. Add the following Controls to the to the form. Use the names provided below.

Hints:
(a)

Use the UserForm Toolbar to make the form easier to design.

(b)

Make the form larger than needed to format the form easier. When finished,
reduce the size to make a reasonable size.

Control

Name

Caption

Frame

fraTank

Tank

Frame

fraEquipment

Equipment

Frame

fraAction

Action

Option Button

optTank1

Tank 1

Option Button

optTank2

Tank 2

Option Button

optTank3

Tank 3

Copyright 1999, Intellution, Inc.

6-29

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 6

3. Continue adding Controls to the to the form. Use the names provided.

Control

Name

Caption

Option Button

optBulk

Bulk

Option Button

optReclaim

Reclaim

Option Button

optMixTank

Mix Tank

Option Button

optReactor

Reactor

Option Button

optValve

Valve

Option Button

optPump

Pump

Option Button

optMixer

Mixer

Check Box

chkRepaired

Repaired

Check Box

chkReplaced

Replaced

Check Box

chkCalibrated

Calibrated

Text Box

txtName

Name:

Combo Box

cmbCause

Cause:

Command Button

cmdSend

Send

Command Button

cmdCancel

Cancel

Command Button

cmdHelp

Help

4. Change the Send button so the caption appears disabled. Hint: Think about which
property is needed to accomplish this. No scripting is needed.

Copyright 1999, Intellution, Inc.

6-30

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 6


D. Add Code to the Maintenance log form.
Now that your form is complete event code needs to be added.
1. Double click any empty area of the form.
An empty code module appears. This is the form code. It resides in a module
within the form itself.
2. Enter the following code in the form code module:
Option Explicit
Dim Msg1Str As String
Dim Msg2Str As String
Dim Msg3Str As String
Dim Msg1LineStr As String

Dim Msg3LineStr As String

This code simply declares a few String variables. These variables will be used to
store the selected information on the form.

3. Enter the following code in the form code:

Private Sub WriteLog()


Application.StatusBar = Msg1LineStr
System.SendOperatorMessage Msg1LineStr
MsgBox Msg3LineStr, vbInformation
End Sub

This procedure will be called from the Send button and the Cancel button. It is used
to display information to the WorkSpace status bar and to a Message Box.

Copyright 1999, Intellution, Inc.

6-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 6

4. Add a procedure to the form code module. The procedure will enable the caption of
the Send button when the Repaired Check Box is selected.
5. Create two similar procedures for the Replaced Check Box and the Calibrated
Check Box.
The screen should resemble the following:

Copyright 1999, Intellution, Inc.

6-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 6

6. Enter the following code in the form code module:


Private Sub CmdCancel_Click()
Msg1Str = Mid$(fraTank.ActiveControl.Name, 4) & _
" " & "Maintenance event cancelled " & Now

Msg1LineStr = Msg1Str
Msg3LineStr = Msg1Str

Call WriteLog
Unload Me

End Sub

This procedure is called when the Cancel button is selected. The procedure simply
gathers the current form selections, displays the information using the WriteLog
procedure, and then unloads the form.

Copyright 1999, Intellution, Inc.

6-33

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 6

7. Enter the following code in the form code module:


Private Sub UserForm_Initialize()
txtName = "<type your name here>"

With cmbCause
.AddItem ("Scheduled Maintenance")
.AddItem ("Just plain wore out")
.AddItem ("Jammed up")
.AddItem ("Gummed up")
.AddItem ("Screwed up")

.AddItem ("Froze up")


.AddItem ("Overheated")

.AddItem ("Looks Ok but doesnt work")


.AddItem ("Operator broke it")

.AddItem ("Other")

End With

End Sub

This code is called when the form is initialized. It adds a text string into the Name
field, and it fills the Combo Box with descriptions for the equipment failure.

Copyright 1999, Intellution, Inc.

6-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 6


E. Cut and Paste Code.
Add code from a text file to the form code module.
1. There is one more procedure to add. Instead of typing it in, you can copy it from a
text file located in the PIC directory.
2. Using Notepad (or some other text editor), open the following file:
C:\Dynamics\Pic\MaintFormCode.txt
The following code appears:

3. Copy the code from this text file and paste it into the form code module.
4. From the Debug menu, select Compile.
This will check the code modules for errors.

Copyright 1999, Intellution, Inc.

6-35

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 6


F. Picture Code Module.
Add code to the picture code module.
1. So far in this exercise, you have been adding code to the Form code module. Now,
look at the event code for the picture.
2. From the Project Explorer, select the MaintOverview picture code module.
It should resemble the following:

Copyright 1999, Intellution, Inc.

6-36

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 6

3. Within each procedure, add a line of code to open the form you just created. For
example, the code for the CmdMixMaintNow button will resemble the following:
Private Sub CmdMixMaintNow_Click()
CloseDigitalPoint "fix32.node8.mixmaint.F_CV"
frmMaintLog.Show
End Sub

4. Repeat this for each procedure in the picture code module.


5. Close the VBE and look at the picture in Run mode.

6. Click the buttons in the picture to force the equipment to go into maintenance mode.
Fill out the form and experiment with the Cancel and Send buttons.

7. When finished, return to Configure mode and Close the MaintOverview picture.

End of Lab Exercise

Copyright 1999, Intellution, Inc.

6-37

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

6.7. Summary Questions ______________________________________

1. Lets say you have a detailed form for entering process data into Excel. Is it possible to
copy or export the form from Excel and paste or import it into iFIX? Is it possible to take
an iFIX form and bring it into Excel?

2. When working with a picture, we have 12 events we can use to activate code. How many
events does a form have? List those events that a form has but a picture does not.

3. By now you have discovered that single threaded VBA will not process scripts while a
message box is opened. Will VBA be processed if a form is opened?

4. With iFIX, there are two ways to present a pop-up window that displays mostly text data
and/or solicits operator input. You could build a small picture (*.GRF) that contains your
information, or you could build a form. Discuss the pros / cons of each approach.

5. We saw that it is possible use Globals \ User as a place to store global objects, and global
subroutines and functions. Is it possible to use Globals \ User to store global forms? If
so, what code would you have to write to open one of these forms?

Copyright 1999, Intellution, Inc.

6-38

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7. Controlling VBA Code _______________________________________

Chapter 7
Controlling VBA Code

Copyright 1999, Intellution, Inc.

7-1

*()DQXF

7.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Controlling VBA Code ______________________________________

Section Objectives
This section provides information on decision making in VBA programs. The student will work
with different ways to make decisions in the VBA code and the impact of Looping. This
includes the following:

Decision Statements

Looping

Do Loops

DoEvents

The student will also explore alternatives to looping.

Copyright 1999, Intellution, Inc.

7-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.1. Decision Statements _____________________________________


A. Decision statements are procedures that perform a test and decide what to do next

Decision statements will use one or more conditions and statements

Condition is what to look for and is interpreted as true or false


-

Logical expression returning a true or false

Expression returning a numeric value

Numeric are sometimes used as Boolean

non-zero = True and zero = False

Statement is one or more VBA statements to run if condition is true

If condition is false the statement will be skipped over

Copyright 1999, Intellution, Inc.

7-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

7.1.1. If Then Else ____________________________________________


A. If Statement

Consists of a conditional and a body

The body is a group of statements

The body is executed if the conditional is True

The body is terminated with an END IF or ELSE statement

B. ELSE statement

Is paired with an IF statement

Consists of just a body

The body is executed if the conditional of IF statement is False

Body terminates with an END IF statement

Copyright 1999, Intellution, Inc.

7-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.1.1. If Then Else ____________________________________________

If Total >= 79 Then


code body performed when conditional is True
End If

Figure 7-1: If code sample

If Fvalue < 2 Then

code body performed when conditional is True

Else

code body performed when conditional is False


End If

Figure 7-2: Then Else code sample

Copyright 1999, Intellution, Inc.

7-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

7.1.1. If Then Else ____________________________________________


C. If Then Else and MsgBox Example Code

Code uses assignments for arguments for MsgBox function

Call to MsgBox Function to query the user

If Then Else to test the user response

New MsgBox shows results

Private Sub IfThenElse_Click ()


Dim Msg, Style, Title, Help, Context, Response, MyString

Msg = Click Yes or No

Style = vbYesNo + vbExclamation + vbDefaultButton2


Title = If Then Else Demonstration

Response = MsgBox(Msg, Style, Title)

If Response = vbYes Then

define message

define buttons

define title

display message

user chose yes

MyString = Yes

perform some action

MsgBox You Clicked Yes

Else

user chose no

MyString = No

perform some action

Response = MsgBox(MyString, vbInformation, You Clicked No)


End If
End Sub

Figure 7-3: If Example Code

Copyright 1999, Intellution, Inc.

7-6

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.1.1. If Then Else ____________________________________________


D. If Then Else and MsgBox Example Code (continued)

Clicking If Then Else & MsgBox will show Figure 7-4

Clicking Yes button results in the following Figure 7-5


-

Default title and default query

Clicking No button results in the following Figure 7-6


-

Different title and style set to information bubble

Figure 7-4: Request a Response

Figure 7-5: Yes Response


Figure 7-6: No Response

Copyright 1999, Intellution, Inc.

7-7

*()DQXF

7.1.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

If Then ElseIf __________________________________________

A. Using ElseIf

If more than a single condition needs to be tested, EsleIf may be used


-

Note the conditionals must be mutually exclusive

The Else and ElseIf clauses are both optional

Many ElseIf clauses can be used in a block If, but none can appear after an Else
clause

Block If statements can be nested


-

that is, contained within one another

B. Syntax for ElseIf (see Figure 7-7)

When executing a block If, the condition is tested

If condition is True, the statements following Then are executed

If condition is False, each ElseIf condition (if any) is evaluated in turn

When a True condition is found, the statements immediately following the


associated Then are executed

If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the
statements following Else are executed

After executing the statements following Then or Else, execution continues with
the statement following End If

Copyright 1999, Intellution, Inc.

7-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.1.2. If Then ElseIf ___________________________________________

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements] ...
[Else
[elsestatements]]
End If

Figure 7-7: ElseIf Syntax

Dim intTankLevelPercent, intTankZone

If intTankLevelPercent < 25 Then


intTankZone = 1
ElseIf intTankLevelPercent < 50 Then
intTankZone = 2
ElseIf intTankLevelPercent < 75 Then
intTankZone = 3
Else
intTankZone = 4
End If

Figure 7-8: ElseIf Example

Copyright 1999, Intellution, Inc.

7-9

*()DQXF

7.1.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Select Case ___________________________________________

A. Using Case Statements

Executes one of several groups of statements, depending on the value of an


expression

Similar to using ElseIF


-

Using Case is sometimes easier to read

B. Syntax for Case (see Figure 7-9)

If testexpression matches any Case expressionlist expression, the statements


following that Case clause are executed up to the next Case clause, or, for the last
clause, up to End Select
-

Control then passes to the statement following End Select

If testexpression matches an expressionlist expression in more than one


Case clause, only the statements following the first match are executed

The Case Else clause is used to indicate the elsestatements to be executed if no


match is found between the testexpression and an expressionlist

Although not required, it is a good idea to have a Case Else statement in your
Select Case block to handle unforeseen testexpression values

If no Case expressionlist matches testexpression and there is no Case Else


statement, execution continues at the statement following End Select

Multiple expressions or ranges can be used in each Case clause

Select Case statements can be nested


-

Each nested Select Case statement must have a matching End Select
statement

Copyright 1999, Intellution, Inc.

7-10

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.1.3. Select Case ____________________________________________

Select Case testexpression


[Case expressionlist-n
[statements-n]] ...
[Case Else
[elsestatements]]
End Select

Figure 7-9: Select Case Syntax

Dim intValveNum

Select Case intValveNum

Case intValveNum < 5

Debug.Print intValveNum & " is Between 1 and 5"

Case 6, 7, 8

Debug.Print intValveNum & " is Between 6 and 8"

Case Is > 8 < 12


Debug.Print intValveNum & " is Between 9 and 11"
Case 12 To 15
Debug.Print intValveNum & " is Between 12 and 15"
Case Else
Debug.Print intValveNum & " is Not between 1 and 15"
End Select

Figure 7-10: Select Case Example

Copyright 1999, Intellution, Inc.

7-11

*()DQXF

7.1.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

GoTo _________________________________________________

A. Notes

Branches unconditionally to a specified line within a procedure

The required line argument can be any line label or line number

GoTo can branch only to lines within the procedure where it appears

See Figure 7-11 for an example

B. Style

Too many GoTo statements can make code difficult to read and debug
-

Use structured control statements (Do...Loop, For...Next, If...Then...Else,


Select Case) whenever possible

The GoTo statement is used in Error Handling


-

Error Handling is discussed later in the course

Sub GotoDemo(Number as Integer)

Dim Number, MyString

If Number = 1 Then GoTo Line1 Else GoTo Line2


Line1:
MyString = "Number equals 1"
GoTo LastLine

Line2:
MyString = "Number equals 2"
LastLine:
Debug.Print MyString
End Sub

Figure 7-11: GoTo Example

Copyright 1999, Intellution, Inc.

7-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.2. Looping_________________________________________________
A. Looping will allow for more efficient non repetitive VBA coding

For Next Loop

Do Loop

For Each Next Loop

B. iFIX has alternatives to looping and provides the following recommendations

Do not use loops in scripts if there is an alternative

VBA is single threaded, if one script is looping, others cannot run

Use the scheduler to accomplish tasks as opposed to a loop

Use the Timer Object (iFIX or Microsofts)

If you must use a loop, use the DoEvents Function

Check condition
at the top of the
loop
Check condition
at the bottom of
the loop
(always executes
the loop at least
once)

Loop Until Condition


is True

Loop While Condition


is True

Do Until <condition>

Do While <condition>

<statements>

<statements>

Loop

Loop

Do

Do

<statements>
Loop Until <condition>

<statements>
Loop While <condition>

Figure 7-12: Various Forms of the Do Loop

Copyright 1999, Intellution, Inc.

7-13

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

7.2.1. Do Loops ______________________________________________

A. Do Loops are typically executed when a condition is true or until it becomes true

Do While Loop

Do Until Loop

B. Do While Loop

Consists of a conditional and a body

The body is a group of statements

The body is executed when the conditional is True

If the conditional is False the loop is not executed at all

C. Do While Loop Example (see Figure 7-13 and Figure 7-14)

Clicking on Yes, displays the box, again

Clicking on No, exits the loop

Response = vbYes

need this to make it happen once

Do While Response = vbYes

Response = MsgBox (Msg, Style, Title, Help, Context)

Loop

Figure 7-13: Do While Loop example code

Figure 7-14: Do While Loop MsgBox

Copyright 1999, Intellution, Inc.

7-14

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.2.1. Do Loops ______________________________________________


D. Do Until Loop Example (see Figure 7-15 and Figure 7-16)

Clicking on Yes, displays the box, again

Clicking on No, exits the loop

Do
Response = MsgBox (Msg, Style, Title, Help, Context)
Loop Until Response = vbNo

Figure 7-15: Do Until Loop example code

Figure 7-16: Do Until Loop MsgBox

Copyright 1999, Intellution, Inc.

7-15

*()DQXF

7.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

For Next Loop _________________________________________

A. For Next Loop is most common loop

Use if you know the exact amount of times a group of statements need repeating
-

For Next loop uses a counter variable whose value is increased or


decreased with each repetition of the loop

B. Syntax for For Next (see Figure 7-17)

Counter - a numeric variable used as a loop counter

Start - the Initial value of the counter

End - the final value to terminate the loop

Step

optional value to increment the counter

if step value is omitted, then 1 is assumed

step value can be a negative number

Statements
-

the group of code statements executed each pass through the loop

Next
-

Next used with counter name defines the end of the loop

the counter name in the Next statement is optional, but can make the code
more readable

C. Additional Notes

Changing the value of counter while inside a loop can make it difficult to read and
debug the code

Any number of Exit For statements may be placed anywhere in the loop as an
alternate way to exit

For...Next loops can be nested by placing one For...Next loop within another
-

Give each loop a unique variable name as its counter

D. For Next Loop Example (see Figure 7-18)

First Pass through the loop is shown in Figure 7-19

The Last pass looks as shown in Figure 7-20

Copyright 1999, Intellution, Inc.

7-16

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.2.2. For Next Loop __________________________________________

For counter = start To end [Step step]


[statements]
[Exit For]
[statements]
Next [counter]

Figure 7-17: For Next Loop Syntax

Private Sub ForLoop_Click ()

For i = 0 To 4
Response =

MsgBox(i, vbExclamation, For Loop Example)

Next i

End Sub

Figure 7-18: For Next Loop Example

Figure 7-19: For Next Loop MsgBox


when I is 0

Copyright 1999, Intellution, Inc.

Figure 7-20: For Next Loop MsgBox


when I is 4 (last loop)

7-17

*()DQXF

7.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

DoEvents _______________________________________________

A. Understanding DoEvents

DoEvents are often used inside the Do While Loop structure


-

DoEvents can be used anywhere in VBA code

Passes control to the operating system


-

Yields the VBA thread to the operating system

Control is returned to the script after operating system processes events

DoEvents will allow user to cancel a process

B. Additional Notes

DoEvents is a VBA command not a iFIX function

Alternatives to DoEvents are Timer Object or moving task to an ActiveX or EXE

Copyright 1999, Intellution, Inc.

7-18

*()DQXF

7.3.

ZZZML\LWHFKFRP


Student Guide

DoEvents _______________________________________________

Public Sub mycount()


Dim counter

For counter = 1 To 10
'display the counter message
Application.StatusBar = "Counter Value: " & counter
txtcount.Caption = "Counter Value: " & counter

'wait (call mywait timer procedure)


mywait (10)
Next counter

Application.StatusBar = False

End Sub

Public Sub mywait(delay As Integer)


Dim starttime As Long

starttime = Timer
Do While Timer - starttime < delay
DoEvents
Loop
End Sub

Figure 7-21: Example of DoEvents and Do While loop

Copyright 1999, Intellution, Inc.

7-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

7.4. Review of Layers _________________________________________


A. Notes

Layering objects is a way to control specific objects in a complex picture

One of the most common uses for layering is in conjunction with large displays

Use layers to be able to easily distinguish specific parts of the picture

By assigning a layer or multiple layers to objects in the picture, you


determine which objects within the picture are visible

Further, layers are an effective security feature in that you can turn off a specific
layer so that certain objects cannot be viewed by one or a set of operators

B. Setting Layers

Establish layering using the Set Layer and Display Layers buttons in the
WorkSpace

Setting a layer assigns a layer to a selected object

Displaying layers applies to the entire picture and determines what layers
are displayed in the picture

C. To set a layer for an object

1. Select the object

2. Click the Set Layer button on the Tools toolbar or the Toolbox
-

see Figure 7-22

3. Click the button that represents the number of the layer to be assigned
-

To assign multiple layers, select the Allow for Multiple Layers check
box and then click the numbered buttons, or click Select All

If a mistake is made, click Deselect All and repeat this step

4. Click OK
D. To display layers in a picture
1. Click the Display Layers button on the Tools toolbar or the Toolbox
-

see Figure 7-23

2. Click the button that represents the layer to be displayed


-

To select all possible layers to be displayed, click Select All Layers

If a mistake is made, click Deselect All Layers and repeat this step

3. Click OK

Copyright 1999, Intellution, Inc.

7-20

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.4. Review of Layers _________________________________________

Figure 7-22: Setting a Layer for an Object

Figure 7-23: Displaying Layers in a Picture

Copyright 1999, Intellution, Inc.

7-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

7.4. Review of Layers _________________________________________


E. Understanding an Objects Layer Property

Object can be assigned to one (or more) of 30 layers in the WorkSpace

Each layer is represented to iFIX as a bit

Example
-

If an object is part of layer 8, bit #7 is set

layers begin with bit #0

Doing the binary math, 27 = 128

Therefore, the value of the objects Layer property is 128

See Figure 7-24

F. Understanding a Pictures Layer Property

Recall that the picture can display any combination of 30 layers

Again, each layer is represented as a bit

Example
-

If layer 8 and layer 3 are being displayed, then bit #7 and bit #2 will be set

Doing the binary math, 2 + 22 = 132

Therefore, the value of pictures DisplayLayer property is 132

See Figure 7-25

Special case:
-

DisplayLayer = -1

this represents displaying all layers

Copyright 1999, Intellution, Inc.

7-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.4. Review of Layers _________________________________________

Figure 7-24: Layer Property of an Object

Figure 7-25: Display Layer Property of a Picture


Copyright 1999, Intellution, Inc.

7-23

*()DQXF

7.5.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

___________________________________________ Lab Exercise 7

Decision Statements
Lab Exercise 7

Copyright 1999, Intellution, Inc.

7-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 7


Learning Objectives:
Upon successful completion of this lab exercise, you will be comfortable working with
decision statements and loops. You will create a form that displays information about the
layers of a picture. The form will also display or hide layers in a picture.
As you progress through this lab, you will:

Use your skills to work with object properties.

Use decision statements to evaluate which layer an object is in.

When you are finished with this lab, turn to page 7-35 and answer the Summary Questions.

Resources:
The iFIX On-line Help and E-Books
The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

You will create a form to allow you to display any combination of sets of objects. This is
done using layers. We will guide you through information that talks about layers.

Copyright 1999, Intellution, Inc.

7-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 7


A. View an existing picture.
Open a picture that displays equipment maintenance information.
1. Open the picture called ProdOver in the configure mode of the WorkSpace.
The screen should resemble the following:

2. Switch to Run mode to explore the functionality of this picture.


This picture is a Production Overview that displays many different pieces of
information. You can change the temperature of the tanks as well as change the level
of the tanks as well. You can also turn pumps on and off. However, there is logic
running the process that may override your settings.
The goal of this exercise is to show a form that will allow you to pick and choose the
items of the picture that are displayed.

Copyright 1999, Intellution, Inc.

7-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 7


B. Develop a form that allows you to select layers in a picture
In some cases, displaying all objects in a picture simultaneously presents more confusion
than information. For that reason, we will create a form that allows us to select a subset
of objects.
1. Return to Configure mode, and go to the VBE.
2. Insert a new form and rename it to frmPickLayer
3. Change caption of the form to Pick Layer
The form should resemble the following:

Copyright 1999, Intellution, Inc.

7-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 7


B. Develop a form that allows you to select layers in a picture (continued)

4. Add the following Controls to the to the form. Use the names provided below.
Control

Name

Caption

Layer
Displayed

Check Box

chkTanks

Tanks

Check Box

chkTempGauges

Temperature Gauges

Check Box

chkPackStat

Packaging Station

Check Box

chkPallStat

Palletizer Station

Command Button

cmdClear

Clear

N/A

Command Button

cmdReset

Reset

N/A

Command Button

cmdFinished

Finished

N/A

Label

lblCurPic

Current Picture:

N/A

Text Box

txtCurPic

The form should now resemble the following:

Copyright 1999, Intellution, Inc.

7-28

N/A

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 7


C. Adding Code to Change and Display Layer Information

Below is a table listing some of the procedures needed to complete this exercise:

Procedure
Name

Procedure
Type

Purpose

Approximate
Lines of Code

cmdClear_Click()

Sub Procedure

Not display any layered


objects

cmdReset_Click()

Sub Procedure

Display all layered objects

cmdFinished_Click()

Sub Procedure

Close the Pick Layer


dialog box (form)

Sub Procedure

Determine the currently


displayed layers and show
them in the dialog box
when it opens

6 to 8

UserForm_Initialize()

Sub Procedure

Adjust the displayed layers


to include or not include
the tanks

Sub Procedure

Adjust the displayed layers


to include or not include
the temperature gauges

chkPackStat_Click()

Sub Procedure

Adjust the displayed layers


to include or not include
the packaging station

chkPallStat_Click()

Sub Procedure

Adjust the displayed layers


to include or not include
the palletizer station

AdjustLayer()

Sub Procedure

Adjust the currently


displayed layers

8 to 10

DispLayerBitStat()

Function

Determine if a particular
layer is currently being
displayed

8 to 10

chkTank_Click()

chkTempGauges_Click()

Note: These names are just a guideline. Feel free to use whatever functions you feel
will get the job done!

Copyright 1999, Intellution, Inc.

7-29

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 7


C. Adding Code to Change and Display Layer Information (continued)

1. AdjustLayer Enter the following sub procedure into the form code module for the
frmPickLayer form:

Public Sub AdjustLayer(LayerArg As Long, CheckBoxArg As Boolean)


Dim crntDisplay As Long
crntDisplay = Application.ActiveDocument.Page.DisplayLayer
LayerArg = 2 ^ (LayerArg - 1)

If CheckBoxArg = True Then


crntDisplay = crntDisplay Or LayerArg

Else

crntDisplay = crntDisplay Xor LayerArg

End If

Application.ActiveDocument.Page.DisplayLayer = crntDisplay

End Sub

This sub procedure needs to set bits in the DisplayLayers property of the picture.
The LayerArg is the layer of the object (1 to 30), and CheckBoxArg is a true of false.
We use OR and XOR to clear and set bits in the DisplayLayers property. Remember
that the DisplayLayers value is essentially a bit pattern.
2. cmdFinsihed_Click() Create the code to hide the form when the Finished button is
clicked. This can be done with one line of code!

Copyright 1999, Intellution, Inc.

7-30

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 7


C. Adding Code to Change and Display Layer Information (continued)

3. cmdReset_Click() This procedure will set all the checkboxes to true. That is, it
sets the four layers to be visible. This function can be written with 5 lines of code.
4. cmdClear_Click() This procedure will set all the checkboxes to false. That is, it
sets the four layers to be not visible. This function can be written with 5 lines of
code.
5. DispLayerBitStat - This function is used to test a layer to see if it is currently
displayed. The function could use the AND operator to test your bit value. For
example if our bit pattern is 00110, and we want to see if the third bit is set, we could
take 00110 AND 00100 = 00100. So if we AND two values and we get a non-zero
value, we know the bit we are interested in is set.

Function DispLayerBitStat(DispLayerValue As Long, _


TestBit As Integer)

Dim testLayer As Long


Dim LayerBeingTested

LayerBeingTested = 2 ^ (TestBit - 1)
testLayer = DispLayerValue And LayerBeingTested
If testLayer = 0 Then
DispLayerBitStat = False
Else
DispLayerBitStat = True
End If
End Function

Copyright 1999, Intellution, Inc.

7-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 7


C. Adding Code to Change and Display Layer Information (continued)

6. chkTank_Click() For every checkbox on the form, there is a click event. Use the
following code below as a hint to creating this procedure.

Private Sub chkTanks_Click()

'code for the checkbox click event

Call AdjustLayer(1, chkTanks.Value)


End Sub

Now, repeat this code for the other three Check Boxes.

7. UserForm_Initialize - You will want to initialize your form when you open it so that
it accurately shows which layers are currently being displayed. You will have to
check each bit of the DisplayLayer property value, and if the bit is set, then you will
have to set the checkbox Value property to true.

Dont forget our special case, -1, which should set all your checkbox values to true.
Consider the code fragment below as you choose your strategy for writing this code.

txtCurPic.Value = Application.ActiveDocument.Name
With Application.ActiveDocument.Page
'
'
'
'

write to a function called DispLayerBitStat that


takes the value of the display layer and which
bit you want to test and returns True if the bit
is set, False if it is not set.

chkTanks.Value = DispLayerBitStat(.DisplayLayer, 1)
chkTempGauges.Value = DispLayerBitStat(.DisplayLayer, 6)
chkPackStat.Value = DispLayerBitStat(.DisplayLayer, 8)
chkPallStat.Value = DispLayerBitStat(.DisplayLayer, 9)
End With

Copyright 1999, Intellution, Inc.

7-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 7


D. Add Code to a Picture Command Button
Create the code to open the form.
1. Return to the WorkSpace Configure mode with the ProdOver picture open.
2. With the Layers button selected, right mouse click and select Edit Script.
3. Enter the following script in the button Click Event:
Private Sub DisplayLayersCmd_Click()
Dim Pic As Object
On Error GoTo ErrorHandler
Set Pic = Application.ActiveDocument.Page

'No documents open


If TypeName(Pic) = "Nothing" Then
Exit Sub

End If

'Show the Display Layers form


frmPickLayer.Show

Exit Sub

ErrorHandler:

MsgBox "Cannot open form.", vbCritical, "Run-time error"


End Sub

4. Exit the VBE and save the picture.


5. Switch to Run mode to test the form, event code, and procedures.

Copyright 1999, Intellution, Inc.

7-33

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

CHALLENGE LAB ________________________________ Lab Exercise 7


If you are finished with the exercise and other students are working, feel free to try these
challenge exercises.
A. Advanced functions.
The Prod Over picture actually contains objects in 13 layers.
1. Adjust the form to display 13 check boxes. Use the following as a guide:
Tanks
Pumps and Screw Conveyors
Pipes and Headers
Valves
Mixers
Temperature Gauges
Tank Fill Level Graphics
Packaging Station
Palletizer Station
Text Labels
Pushbutton Controls
Temperature Data Links
Tank Level Data Links

1
2
3
4
5
6
7
8
9
10
11
12
13

2. Change the form code to account for the new layers.

End of Lab Exercise

Copyright 1999, Intellution, Inc.

7-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

7.6. Summary Questions ______________________________________

1. Compare using Else, If (two separate lines of code) versus ElseIf versus Case.
When does it make sense to use each?

2. When working with the For loop, the typical construct is For X = 1 to 4321. What is the
construct when you have a finite number of objects, but you dont know how many?

3. Is it legal to write a Do Loop that has no condition statements, neither at the beginning,
nor the end? If so, how do you exit such a loop?

4. What are the consequences of working with our Loops in our current, single-threaded
implementation of VBA? How does Do Events fit into this picture?

5. If you wanted to test a value every 5 seconds, you could use a loop. Alternatively, how
could you use a block in the FIX database to trigger an event every 5 seconds? What
object(s) in iFIX could be used?

Copyright 1999, Intellution, Inc.

7-35

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

7.6. Summary Questions _________________________________

this page intentionally contains no data

Copyright 1999, Intellution, Inc.

7-36

*()DQXF

ZZZML\LWHFKFRP


Student Guide

8. Collections and Groups______________________________________

Chapter 8
Collections and Groups

Copyright 1999, Intellution, Inc.

8-1

*()DQXF

8.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Collections and Groups ____________________________________

Section Objectives
This section provides will discuss differences between collections and groups. The students will
isolate and manipulate properties of objects existing in a collection and a group. Also, user
defined collections will be discussed. This includes the following:

Grouped Objects

VBA Collections

The student will create logical expressions to affect the behavior of grouped objects.

Copyright 1999, Intellution, Inc.

8-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

8.1. Grouped Objects _________________________________________


A. Grouping objects is different than a defined collection of objects

The Group object holds information describing a number of objects used as a unit
-

Example: Two rectangles and two circles can be grouped to for a pump

Group objects together so that they function as a unit allowing for the
manipulation of all objects in the group as a unit instead of individually

Grouping objects in the iFIX WorkSpace adds objects to a new group type object
called FIX2DGroup
-

This new FIX2DGroup object has its own name, properties, methods and
events

Objects contained in either a grouped object or defined collection object can be


manipulated independently or as a entire entity
-

Example: When the grouped object position is changed in WorkSpace all


objects move as one entity

The individual objects could be repositioned by using VBA script

Copyright 1999, Intellution, Inc.

8-3

*()DQXF

8.1.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

ContainedObjects Property ______________________________

A. ContainedObjects Property

ContainedObjects is a property of every object in a picture


-

Example: The ContainedObjects Property of a DataLink shows the


Format object

ContainedObjects property of a group returns a collection


-

Consisting of the shapes that were collected to make this group

Includes any other object visible or not

B. ContainedObjects Property Help Topic

Syntax - Group.ContainedObjects
-

Object is any item in the Applies To list (see below)

Read only property

C. ContainedObjects Property Applied To List

Lists all the objects that can contain this property


Arc
Legend
Rectangle
Bitmap
Line
RoundRectangle
Chart
Linear
Scheduler
Chord
Lookup
Text
ControlContainer
Oval
TimeAxis
Datalink
Pen
Timer
DynamoSet
Picture
UserGlobals
Event
Pie
ValueAxis
Format
Polygon
Variable
Group
Polyline
All of these objects can have embedded objects associated with them

Copyright 1999, Intellution, Inc.

8-4

*()DQXF

8.1.1.

ZZZML\LWHFKFRP


Student Guide

ContainedObjects Property ______________________________

Figure 8-1: Example of Grouped Object

Private Sub grpTank1_Click()


Dim grpobj As Object
For Each grpobj In grpTank1. ContainedObjects
MsgBox grpobj.Name
Next grpobj
End Sub

Figure 8-2: Example using ContainedObject property to get list of objects

Copyright 1999, Intellution, Inc.

8-5

*()DQXF

8.1.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

ContainedSelections Property ___________________________

A. ContainedSelections Property

Collection of just the objects selected as a subset of the whole group

Syntax - Group.ContainedSelections
-

Object is any item in the Applies To list

Major use of this group property is at design time using custom tools

Figure 8-3: Object Browser showing ContainedSelections Property

Copyright 1999, Intellution, Inc.

8-6

*()DQXF

8.1.2.

ZZZML\LWHFKFRP


Student Guide

ContainedSelections Property ___________________________

Figure 8-4: Example of Grouped Object (showing selected objects)

Private Sub grpTank1_Click()


Dim grpobj As Object
For Each grpobj In grpTank1. ContainedSelections
MsgBox grpobj.Name
Next grpobj
End Sub

Figure 8-5: Example using ContainedSelections property to get list of objects

Copyright 1999, Intellution, Inc.

8-7

*()DQXF

8.1.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Grouped Object Properties ______________________________

A. Group Object has its own set of properties

Group Object contains user defined objects representing controls, elements, and
physical items

Normally have one property set by animation (color, size or text)

VBA scripts can be used to change others

B. Properties values by VBA code

Color, Fill - would set all object to same color

Position, Name - apply only to the group object

Copyright 1999, Intellution, Inc.

8-8

*()DQXF

8.1.3.

ZZZML\LWHFKFRP


Student Guide

Grouped Object Properties ______________________________

Figure 8-6: Group Properties

Copyright 1999, Intellution, Inc.

8-9

*()DQXF

8.1.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Group Events__________________________________________

A. Group Objects have the same events as objects

If a nested object has an event it supersedes the groups

Multiple nested objects can have the same event, since only one is selected

Figure 8-7: Group Events

Copyright 1999, Intellution, Inc.

8-10

*()DQXF

ZZZML\LWHFKFRP


Student Guide

8.2. Collections ______________________________________________


A. Collections are an important aspect of VBA

Many times similar objects are actually part of a group or collection of objects

Collection itself is defined as an object and has properties, methods and events
-

A collection can contain other collections

Individual objects in a collection are referred to as elements

A defined collection contains objects (elements) that can be referenced


individually by name or by position in the collection

The collection objects in WorkSpace are individual elements that happen to


belong to a collection

Common properties can be set to all elements by setting a common property

B. Collection Types

User Defined Collections


these are collections created using VBA

Pre-defined Collections
-

these are system collections

Copyright 1999, Intellution, Inc.

8-11

*()DQXF

8.2.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Pre-Defined Collections _________________________________

A. Examples

In Excel, the Workbooks collection is the set of all open Workbook objects

In Excel, the Worksheets collection is the set of all open Worksheet objects in a
workbook

In iFIX, the Documents collection is the set of all open:


-

Pictures

Schedules

Dynamo Sets

B. Referencing Collection Objects

Many application objects can not be referred to by simply using the object name
-

In general, the object needs to be referred to in a collection

Example:
-

when referring properties of the current picture, you use the following
syntax:

Application.ActiveDocument

current picture object

Application.ActiveDocument.Name

current picture name property

Application.ActiveDocument.Path

path to the picture location

Copyright 1999, Intellution, Inc.

8-12

*()DQXF

8.2.1.

ZZZML\LWHFKFRP


Student Guide

Pre-Defined Collections _________________________________

Figure 8-8: Object Hierarchy

Copyright 1999, Intellution, Inc.

8-13

*()DQXF

8.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

User Defined Collections ________________________________

A. Notes

A Collection object is an ordered set of items that can be referred to as a unit

The Collection object provides a convenient way to refer to a related group of


items as a single object
-

The items, or members, in a collection need only be related by the fact that
they exist in the collection

Members of a collection don't have to share the same data type

B. Creating a Collection

A collection can be created the same way other objects are created
-

For example:
Dim X As New Collection

C. Properties and Methods

The entire collection can be iterated using the For Each...Next statement

Once a collection is created, members can be added using the Add method and
removed using the Remove method

Specific members can be returned from the collection using the Item method

The number of objects in a collection can be determined by using the Count


property

Copyright 1999, Intellution, Inc.

8-14

*()DQXF

8.2.2.

ZZZML\LWHFKFRP


Student Guide

User Defined Collections ________________________________

Private Sub CommandButton2_Click()

declare a new collection


Dim mytruck As New Collection

add objects to the new collection


mytruck.Add Rect1
mytruck.Add Oval1
mytruck.Add Oval2
mytruck.Add RoundRect1

declare an object to represent any objects in the collection


Dim truckobj As Object

For Each truckobj In mytruck

check the name of each object and display the name in MsgBox

MsgBox truckobj.Name

change the color of each object in the collection to red


truckobj.ForegroundColor = vbRed

Next

End Sub

Figure 8-9: Collection Example

Copyright 1999, Intellution, Inc.

8-15

*()DQXF

8.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

User Defined Collections ________________________________

C. Add Method

Adds a member to a Collection object

Syntax
object.Add item, key, before, after
-

object Required

item Required

key Optional

name o f the object to be added to the collection


A string that specifies a key string that can be used, instead of a
positional index, to access a member of the collection

before Optional

An expression that specifies a relative position in the collection

The member to be added is placed in the collection before the


member identified by the before argument

If numeric, before must be a number from 1 to the value of the


collection's Count property

If a string expression, before must correspond to the key specified


when the member being referred to was added to the collection

after Optional

An expression that specifies a relative position in the collection

The member to be added is placed in the collection after the


member identified by the after argument

Additional Notes
-

Whether the before or after argument is a string expression or numeric


expression, it must refer to an existing member of the collection, or an
error occurs

An error also occurs if a specified key duplicates the key for an existing
member of the collection

Copyright 1999, Intellution, Inc.

8-16

*()DQXF

8.2.2.

ZZZML\LWHFKFRP


Student Guide

User Defined Collections ________________________________

D. Remove Method

Removes a member from a Collection object

Syntax
object.Remove index
-

object Required

index Required

An expression that specifies the position of a member of the


collection

If the value provided as index doesnt match an existing member of the collection,
an error occurs

E. Count Property

Returns a Read-only Long containing the number of objects in a collection

Example:
-

This example uses the Collection object's Count property to specify how
many iterations are required to remove all the elements of the collection

When collections are numerically indexed, the base is 1 by default

Since collections are reindexed automatically when a removal is made, the


code removes the first member on each iteration

Dim Num, MyClasses


For Num = 1 To MyClasse s.Count
MyClasses.Remove 1

' Remove name from the collection


' Default collection numeric indexes

Next

' begin at 1.

Figure 8-10: Collection Count and Remove Example

Copyright 1999, Intellution, Inc.

8-17

*()DQXF

8.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

User Defined Collections ________________________________

D. Item Method

Returns a specific member of a Collection object either by position or by key

Syntax
object.Item(index)

object Required

index Required

An expression that specifies the position of a member of the


collection

If a numeric expression, index must be a number from 1 to the


value of the collection's Count property

If a string expression, index must correspond to the key argument


specified when the member referred to was added to the collection

The Item method is the default method for a collection


-

Therefore, the following lines of code are equivalent:


Print MyCollection(1)

Print MyCollection.Item(1)

Copyright 1999, Intellution, Inc.

8-18

*()DQXF

8.2.3.

ZZZML\LWHFKFRP


Student Guide

For Each Next Loop ____________________________________

A. For Each Next Loop is used with a collection of objects

Does not use loop counter

VBA loops through individual elements (objects) in the collection

Performs operation that is in the loop for that element

Private Sub Tank1_Click()


Dim grpobj As Object

For Each grpobj In Tank1.ContainedObjects

MsgBox grpobj.Name
Next grpobj

End Sub

Private Sub CommandButton2_Click()

Dim mytruck As New Collection


Dim truckobj As Object

mytruck.Add Rect1
mytruck.Add Oval1
mytruck.Add Oval2
mytruck.Add RoundRect1

check the name of each object and displa y the name in MsgBox
For Each truckobj In mytruck
MsgBox truckobj.Name
End Sub

Figure 8-11: Example of ForEach loop to get name of each object

Copyright 1999, Intellution, Inc.

8-19

*()DQXF

8.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

___________________________________________ Lab Exercise 8

Group Objects and Collections


Lab Exercise 8

Copyright 1999, Intellution, Inc.

8-20

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 8


Learning Objectives:
Upon successful completion of this lab exercise, you will be comfortable working with
groups of objects.
As you progress through this lab, you will:

Use your skills to work with object properties.

Use a loop to go through each object in the picture

Use decision statements to evaluate the objects name and set the layer

When you are finished with this lab, turn to page 8-33 and answer the Summary Questions.

Resources:
The iFIX On-line Help and E-Books
The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

You will work with an existing picture called CIP Overview that has many objects. Your
code will loop through all the objects, check the name property and set the layer based on the
name property. You will copy and modify the form you created in an earlier exercise to
select which layers you want to view during run-time.

Copyright 1999, Intellution, Inc.

8-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 8


A. Develop the script that allows you to loop through all the objects
In this lab you will work with a completed picture that has many objects. All these
objects have been carefully named using the naming convention discussed in earlier
exercises.
1. Open the picture called CIPOver in Run mode.
The following picture appears:

This picture is a CIP (Clean in Place) Overview that displays many different pieces of
information:
2. Go to the Visual Basic Editor where you will write the code that will loop through
all the objects in the picture.

Copyright 1999, Intellution, Inc.

8-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 8


B. Add new modules and procedures

1. Insert a new module into the project


2. Rename it from Module1 to ChangeLayers.
3. Add the following code into the general section of the ChangeLayers module:
Option Explicit
Public MyObj As Object

' Reference to the current


' object selected in the picture

Public ObjTotal As Long

'Total count of objects in my picture

4. Add a new procedure into the ChangeLayers module:

Public Sub ChangeLayerAssignments()

'Loop through all the top-level objects of the picture


For Each MyObj In CIPOVER.ContainedObjects
ObjTotal = ObjTotal + 1

'Count the objects

'Show each object's informatio n in the immediate window


Debug.Print Format(ObjTotal, "000") & " = " & MyObj.Name
Next
'When finished, show the total count in the StatusBar
'at the lower left-hand side of the WorkSpace
Application.StatusBar = ObjTotal & " objects counted"
End Sub

This procedure will be used to loop through each object in the picture using a For
Each loop.
5. Open the Immediate Window to view the results of the For Each loop.

Copyright 1999, Intellution, Inc.

8-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 8


B. Add new modules and procedures (continued)

6. Run the code by placing the cursor on ChangeLayerAssignments and pressing <F5>
The screen should resemble the following:

This code works, but it only counts the top level objects in the picture. If we have a
group object, like Group1 that is made up of rect1, oval1, and line1, this procedure
will count Group1, but it will miss the objects contained in the Group.
7. Modify the code to include the following statement just before the Next statement:
If MyObj.ClassName = "Group" Then Call DrillObj(MyObj , 1)

Copyright 1999, Intellution, Inc.

8-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 8


B. Add new modules and procedures (continued)

8. The following code can be used to drill down into group objects. Enter this new
sub procedure into the same module:
'This sub procedure drills down into a gr oup object and shows
'all the objects that make up the group object.
Private Sub DrillObj(ObjArg As Object, DrillLevelArg As Long)
'This constant allows us to indent our output based on
'how deep we are inside a grouped object.
Const IndentStr As String = "********************"
Dim GrpObj As Object

'The current group object selected

'Loop through all the top-level objects in the group


For Each GrpObj In ObjArg.ContainedObjects

ObjTotal = ObjTotal + 1

With GrpObj

'Count the objects in the gro up

'Show each object's information in the immediate window

Debug.Print (Left$(IndentStr, DrillLevelArg) & _


" = " & .Name & "; Class = " & .ClassName)

End With

'If the group object contains a group object then


'drill into it - this makes our DrillObj sub procedure
'a recursive sub procdure.
If GrpObj.ClassName = "Group" Then
Call DrillObj(GrpObj, (DrillLevelArg + 1))
End If

Next
End Sub

Copyright 1999, Intellution, Inc.

8-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 8


B. Add new modules and procedures (continued)

9. With the new DrillObj sub procedure in place, run the code again by placing your
cursor on ChangeLayerAssignments and pressing <F5>.

Now the script works all objects were displayed in the immediate window.

Copyright 1999, Intellution, Inc.

8-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 8


C. Develop the script that allows you to evaluate the objects name and set the layer
This portion of the lab uses string functions to parse the name of the object and set the
objects layer accordingly.
Now that you are able to loop through all the objects, you need to write the code that
will test the name of the object.
Recall that you can assign an object to any one of 30 layers while youre in the
WorkSpace. Each layer is represented as a bit. If youre working with layer 8, bit #7
is set (we start counting with bit #0). If you do the binary math, 27 = 128. So its no
surprise to us that when we look at the objects Layer property, the value is 128.
Likewise, if an object is in the 3rd layer, bit #2 is set, which means the layer value is
set to 22 = 4.
1. The following is a table of object name prefixes, suffixes, and categories that
correlate our object to the target layer.
Layer
Value

Bit

Layer

Name fragment

First four characters are Tank, ie the name would be Tank*

Pmp* for pumps or Screw* for screw conveyors

Pipe* or Hdr* or CipHd* for pipes and headers

Vlv* for valves

16

Mix* or Mstem* for mixer and mixer stem/shaft graphics

32

Tmp* AND NOT ClassName = Datalink for temp. related objects

64

Lvl* AND NOT ClassName = Datalink for level objects

128

skip (used for the packager in Production Overview picture)

256

skip (used for the palletizer in Production Overview)

10

512

Lbl* for text labels

10

11

1024

skip (used for special command buttons)

11

12

2048

Tmp* AND ClassName = Datalink for Temperature datalinks

12

13

4096

Lvl* AND ClassName = Datalink for Level datalinks

13

14

8192

Tmr* AND ClassName = Datalink for Timer-related datalinks

Copyright 1999, Intellution, Inc.

8-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 8


C. Develop the script to evaluate the objects name and set the layer (continued)

For example, if you want to set all headers to the third layer, you can write a script
similar to the following:
If Left(MyObj.Name, 4) = "Pipe" Or _
Left(MyObj.Name, 3) = "Hdr" Or _
Left(MyObj.Name, 5) = "CipHd" Then
'Increment "Pipe and Header" counter
TotlPipeInt = TotlPipeInt + 1
'set the object's layer to 4, which is the third layer
MyObj.Layer = 4

End if

2. Now, it is your job to write the code to take all the objects in the four layers of the
picture and assign them to the appropriate layer. Start with the Tanks first.

Hints:

(a)

The code will be part of the ChangeLayerAssignments procedure.

(b)

You will need to declare an integer variable to track the number of tank
objects (for example: TotlTankInt)

(c)

You will need to use the Layer Value (from the table above) in the program
to set the objects layer.

3. Test the code by running it from the VBE, and then checking the Layer property of
the tanks in the CIPOVER picture or use the Set Layer tool to see the results.

Copyright 1999, Intellution, Inc.

8-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 8


D. Advanced functions.
Here are a few somewhat advanced exercises to try. Make sure the first part of the
application is working before trying these.
1. Export the frmPickLayer from the ProdOver picture.
2. Import that form into the CIPOver picture.
3. Modify the form and picture modules to have the form display the visible layers.

Copyright 1999, Intellution, Inc.

8-29

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

CHALLENGE LAB ________________________________ Lab Exercise 8


If you are finished with the exercise and other students are working, feel free to try these
challenge exercises.
A. Advanced functions.
You can make your code run faster by minimizing the number of times you reference
properties of an object; the reason is because VB has to re-reference the properties every
time the line of code is executed. By setting a variable equal to the property and using
the variable, we increase the speed of the program.
1. Instead of referencing each property of the objects many times in a procedure, you
can use the following code example and use a variable instead.

With MyObj
ObjNameStr = .Name

'copy the name property to a String

ObjLayerLng = .Layer

'copy the layer property to a Long

ObjClassStr = .ClassName

ObjDescStr = .Description

End With

Copyright 1999, Intellution, Inc.

8-30

'copy the classname to a String

'copy the description to a String

*()DQXF

ZZZML\LWHFKFRP


Student Guide

CHALLENGE LAB ________________________________ Lab Exercise 8

2. You can make your code run faster by minimizing the number of times you call
functions. For example, each time you test an objects name, you call the Left()
function to determine the objects name (tank, pipe, pmp, vlv, etc.).
Instead of calling the function many times in a procedure, you can use the following
code example and use a variable instead.
ObjNameLen = Len(ObjNameStr)
If ObjNameLen > 7 Then

'Make sure our name is long enough

ObjN5cPrefixStr = Left(ObjNameStr, 5)

'Grab first 5 chars

ObjN4cPrefixStr = Left(ObjNameStr, 4)

'Grab first 4 chars

ObjN3cPrefixStr = Left(ObjNameStr, 3)

'Grab first 3 chars

ObjN3cSuffixStr = Right(ObjNameStr, 3)

'Grab last 3 chars

ObjN3cCatgryStr = Mid(ObjNameStr, (Len(ObjNameStr) - 5), 3)

End If

Copyright 1999, Intellution, Inc.

8-31

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

CHALLENGE LAB ________________________________ Lab Exercise 8

3. Now, the ChangeLayerAssignments procedure should resemble the following:


For all objects in the picture:
Increase ObjTotal
Set ObjNameStr, ObjLayerLng, ObjClassStr, and ObjDescStr
Determine the number of characters in the object name
Read the first 3, 4, and 5 characters of the object name
Read the last 3 characters of the object name
If the object is a Tank, set the layer to 1
If the object is a Group, drill down

Move on to the next object

4. Try the code again with the new changes and see if it works.

Note: The layers for Tanks are already set to Layer 1, so you will need to manually
change a few tanks to a different layer before running the procedure.

End of Lab Exercise

Copyright 1999, Intellution, Inc.

8-32

*()DQXF

ZZZML\LWHFKFRP


Student Guide

8.4. Summary Questions ______________________________________

1. VBAs generic Collection object has only one property. What is it?

2. When working with arrays, if you want to extract the value of one of the elements in the
array, you specify which element you desire by the index. What are the two ways in
which you can access the individual objects in a collection object? Which method is
more reliable?

3. If you want to change the value of an element in an array, you simply use an assignment
statement such as SportsCarCostArray(7) = $60,000, assuming Sportscar is an array. If
you want to substitute one object with another object in a collection, will a statement like
SportsCarCollection(7) = Ferrari?

4. When working with collections, if you want to insert objects into the collection in a
specific place by using statement such as SportsCarCollection.Add Porche, after
Delorian. How would you insert a value into an array?

5. In VBA we can store a set (a group) of items two ways. One way is with an array, the
other way is with a collection. When does it make more sense to use an array and when
does it make more sense to use a collection?

Copyright 1999, Intellution, Inc.

8-33

*()DQXF

8.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Summary Questions _____________________________________

this page intentionally contains no data

Copyright 1999, Intellution, Inc.

8-34

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9. Embedded Objects__________________________________________

Chapter 9
Embedded Objects

Copyright 1999, Intellution, Inc.

9-1

*()DQXF

9.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Embedded Objects ________________________________________

Section Objectives
This section provides an introduction objects that can be embedded into the WorkSpace.
Specifically, this section explores the following:

Timer Objects

Event Objects

This section also looks at WorkSpace variable objects.

Copyright 1999, Intellution, Inc.

9-2

*()DQXF

9.

ZZZML\LWHFKFRP


Student Guide

Embedded Objects ________________________________________


A. Events

Basically two types of events are going to occur


-

Physical actions such as a mouse click or key press

Things that happen under software control such a timer being done or an
event trigger based on a PDB value

The event will kick off a procedure (event handler)

B. Events can come from many sources

Object Events

Embedded Object Events

Screen Events

Grouped Object Events

Key Events

Mouse Events

Form Control Events

Window Object Events

VBA script Events

Activated Event

De-Activated Event

Copyright 1999, Intellution, Inc.

9-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

9.1. WorkSpace Variable Objects _______________________________


A. Data variable objects can be used in logical operations

Variable objects are another type of object that can be added to the iFIX project

These variables exist in the FIXUSER.FXG or in a Picture

these are NOT declared in VBA

think of these variable like any other WorkSpace object (rectangle, oval,
etc.)

The variable objects can be defined with different data types


-

Boolean

Byte

Short

Long

Float

Double

String

B. Data Variable definition

FIX Variable Class

Defined to be available to the selected picture only (local)

Defined to be available to all pictures and scripts (global)

Acts as a handle to access data from the databases, pictures, and external sources

C. Data variable can then be monitored by other objects such as Event Objects

Create the variable object


-

Could be a variable that represents a on/off switch

Create an Event object to monitor the variable object


-

Monitor the variable event true or false

Copyright 1999, Intellution, Inc.

9-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9.1. WorkSpace Variable Objects _______________________________

Figure 9-1: WorkSpace Variable Object

Copyright 1999, Intellution, Inc.

9-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

9.1. WorkSpace Variable Objects _______________________________


D. Local WorkSpace Variables

Select from ToolBar and select Local

Variable name is added to project tree as part of the picture

E. Global WorkSpace Variables

Select from ToolBar and select Global

Variable name is added to project tree as part of the Global User

Figure 9-2: Global and Local Variables

Copyright 1999, Intellution, Inc.

9-6

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9.1. WorkSpace Variable Objects _______________________________


F. WorkSpace Variables in VBA

WorkSpace Variables have three events:


-

OnChange, OnFalse, OnTrue

These events are valid for both Local and Global variables

Figure 9-3: Global and Local Variables

Copyright 1999, Intellution, Inc.

9-7

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

9.2. Timer Object_____________________________________________


A. Timer Object

Creates time based event objects

Name needs to be unique

Local to the picture; only active when picture is active or loaded

Use scheduler for a global event

Note - Interval is in milliseconds, needs a multiplier of 1000 for each second

Class - FixTimer

Use property window of VBA code for more features

Provides for One show mode

B. Adding a Timer Object to a Picture

Select from the ToolBar

Complete Timer Object form (see Figure 9-4)

Timer name added to project tree

C. Adding an Timer Object to a Schedule

Double click an empty line in a schedule

Complete Timer Object form (see Figure 9-5)

Timer name added to the schedule spreadsheet

Copyright 1999, Intellution, Inc.

9-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9.2. Timer Object_____________________________________________

Figure 9-4: Adding a Timer Object to a Picture

Figure 9-5: Adding a Timer Object to a Schedule


Copyright 1999, Intellution, Inc.

9-9

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

9.2. Timer Object_____________________________________________


D. Timer Object in VBA code

Timer Objects has one event:


-

OnTimeOut

Occurs when the time parameters in the Timer Object are true

This event is valid for both picture and schedule Timer Object

Copyright 1999, Intellution, Inc.

9-10

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9.2. Timer Object_____________________________________________

Figure 9-6: Timer Object Code Example

Copyright 1999, Intellution, Inc.

9-11

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

9.3. Event Object_____________________________________________


A. Event Object

Provides a link to the container

Sources are data from the databases, pictures, and external sources

Events are data change, when true, when false, etc.

The container keeps track of data state and performs the event call

Event Objects can exist as part of a picture or as part of a schedule

Class - FixEvent

Use property window of VBA code for more features

Provides for WhileTrue, WhileFalse, OnTrue, OnFalse, and DataChange

B. Adding an Event Object to a Picture

Select from the ToolBar

Complete Event Object form (see Figure 9-7)

Event name added to project tree

C. Adding an Event Object to a Schedule

Double click an empty line in a schedule

Complete Event Entry form (see Figure 9-8)

Event name added to the schedule spreadsheet

Copyright 1999, Intellution, Inc.

9-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9.3. Event Object_____________________________________________

Figure 9-7: Picture Based Event Object

Figure 9-8: Schedule Based Event Object

Copyright 1999, Intellution, Inc.

9-13

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

9.3. Event Object_____________________________________________


D. Event Object in VBA code

Event Objects have three events:


-

DataChange

OnTrue

Occurs while the expression is true at a rate determined by the


objects interval

WhileFalse

Occurs the first time the expression becomes false

WhileTrue

Occurs the first time the expression becomes true

OnFalse

Occurs each time the expression value changes outside of the


deadband range

Occurs while the expression is false at a rate determined by the


objects interval

These events are valid for both picture and schedule events

Copyright 1999, Intellution, Inc.

9-14

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9.3. Event Object_____________________________________________

Figure 9-9: Event Object Code Examples

Copyright 1999, Intellution, Inc.

9-15

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

9.4. Scheduler _______________________________________________


A. Notes

Supports Timer and Event Objects

Events in a schedule can be performed independent of a picture

B. Schedule Object

A schedule is an object that contains timer and event objects


-

This is analogous to a picture being an object and contains other objects

Schedule Events
-

Activated, Close, Deactivated, Initialize

C. Background schedules vs. Foreground schedules

In general, schedules are designed to be run in the background


-

Foreground schedules are for testing and debugging

Events and scripts are asynchronous to the picture code if the schedule is running
as a background task

Copyright 1999, Intellution, Inc.

9-16

*()DQXF

ZZZML\LWHFKFRP


Student Guide

9.4. Scheduler _______________________________________________

Figure 9-10: Scheduler Code Example

Copyright 1999, Intellution, Inc.

9-17

*()DQXF

9.5.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

___________________________________________ Lab Exercise 9

Embedded Objects
Lab Exercise 9

Copyright 1999, Intellution, Inc.

9-18

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 9


Learning Objectives:
Upon successful completion of this lab exercise, you will be working with some Event
Objects and adding to some forms created in an earlier exercise.
As you progress through this lab, you will:

See how Event Objects can be used

When you are finished with this lab, turn to page 9-24 and answer the Summary Questions.

Resources:
The iFIX On-line Help and E-Books
The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information

You will work with an existing picture that displays equipment maintenance information.
When a piece of equipment goes into maintenance mode, a dialog box will appear prompting
for some maintenance information. You will need to create code so that when the form
appears, the equipment in question appears as the default on the form.

Copyright 1999, Intellution, Inc.

9-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 9


A. Open an existing picture and add Event Objects.
1. Open the MaintOverview picture in the WorkSpace. This is a picture you worked on
in a previous exercise.
The screen should resemble the following:

Copyright 1999, Intellution, Inc.

9-20

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 9

2. Add a new Event Object to the picture. Use the following dialog box as an example:

3. Click the Edit Script button and enter the following:

Private Sub RclPmpMaintEvt_OnTrue()

With frmMaintLog
.optReclaim.SetFocus

.optReclaim = True
.optPump.SetFocus

.optPump = True

End With

CmdRclMaintNow.ForeColor = VBRed

End Sub

This procedure is executed when the object (RclPmpMaintEvt) becomes true. This
refers to when the pump enters into maintenance mode. When this happens, the
command button text color turns red notifying the user to click the button to opening
the log maintenance form. Once opened the form will automatically contain
information based on a maintenance event for the reclaim tank
The form, which is one used in an earlier exercise, looks like the following:

Copyright 1999, Intellution, Inc.

9-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_______________________________________________ Lab Exercise 9


B. Observe the working code
1. Exit the VBE and return to the MaintOverview picture in the workspace.
2. Switch to Run Mode.
3. Type a one (1) into the Status link of the reclaim tank. This forces it into
maintenance mode. The follow dialog box appears:

4. Notice the following, and recall the code from the previous page:
a. In the Tank section, the Reclaim tank radio button is enabled

.optReclaim = True
.optReclaim = True

b. In the Equipment section, the Pump is radio button is enabled and it is the
currently selected object
.optPump = True
.optPump.SetFocus

c. the Send button is grayed out (because the rest of the dialog box is not filled in)
5. Fill out the rest of the dialog box and click Send.
6. Note that the button Text should return to normal black color once the user has sent
the information. Write the code that will accomplish this task.
7. A new dialog box appears with information about the selections you made.
8. Click OK to return to the picture.

Copyright 1999, Intellution, Inc.

9-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

_______________________________________________ Lab Exercise 9


C. Create additional code for other events.
Now you will be creating five new events to handle maintenance events similar to the one
from the previous page.
Using the Reclaim Tank example on the previous pages as a model, create additional
procedures for Tank1, Tank2, Tank3, Mix Tank, and the Reactor Tank. The
Tagname naming convention is as follows:
TK1 - Tank1
TK2 - Tank2
TK3 - Tank3
MIX - Mix Tank
REA - Reactor tank
RCL - Reclaim tank (this is the one from the previous page)

1. You will first need to add Event Objects into the picture. Each object is looking for
the equipment to go into maintenance mode. Again, use the Reclaim Tank as a
model.

2. The next thing you need to do is edit the script for each event object. When the
event goes true, the maintenance form will open. You need to write the code for this.
Use the code for the Reclaim Tank as a model.

3. Finally, test the scripts. There are data links in the picture to force the equipment
into maintenance mode. Each time this happens, the form should open prompting
you to enter in the maintenance information.

End of Lab Exercise

Copyright 1999, Intellution, Inc.

9-23

*()DQXF

9.6.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Summary Questions _____________________________________

1. Explain the term: Embedded Objects?

2. Explain how a Timer Object works.

3. When doing a Find and Replace in the exercise, why was it important to select the
Include Scripts check box?

4. Explain the difference between the following lines of code:


LogMaintFrm.optPump.SetFocus
LogMaintFrm.optPump = True

5. What was the purpose of the Event Objects that were used in the exercise?

Copyright 1999, Intellution, Inc.

9-24

*()DQXF

10.

ZZZML\LWHFKFRP


Student Guide

iFIX Automation __________________________________________

Chapter 10
iFIX Automation

Copyright (c) 1999, Intellution, Inc.

10-1

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

10. iFIX Automation ___________________________________________


Section Objectives
This section provides a look into the powerful iFIX Automation Interfaces. This includes
detailed references to VBA functions and information, all the iFIX objects and their properties,
methods and events. Includes an explanation of the subroutines used to manipulate process
database blocks. The section will include the following topics:

iFIX Automation

iFIX Objects

iFIX Subroutines

EDA Functions

Copyright (c) 1999, Intellution, Inc.

10-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

10.1. iFIX Automation Reference_________________________________


A. iFIX Automation References

Includes references to all the iFIX objects and their corresponding properties,
methods and events plus pre-built subroutines and database functions

Includes references to VBA functionality such as available constants, functions,


data types, keywords, methods and much more.

Includes conceptual information on using VBA including creating variables,


looping code, passing arguments and much more.

Figure 10-1: iFIX Automation Reference

Copyright (c) 1999, Intellution, Inc.

10-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

10.2. iFIX Objects _____________________________________________


A. Notes

A VBA object is anything in the application that can be referenced and


manipulated

An object represents an element of an application, such as an iFIX application


object, picture object, rectangle or text object

B. iFIX has nearly 60 objects

Common iFIX objects are:


-

Rectangle, Oval, Text, Bitmaps, Pictures

Figure 10-2 contains the iFIX objects that are available within VBA

C. Additional Notes

Each iFIX object type has its own properties, methods, and events
-

Example: a rectangle object has nearly 60 properties, over 40 methods and


8 events

This is why the iFIX Automation Reference help is important to identify the
available functionality for each object

Copyright (c) 1999, Intellution, Inc.

10-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

10.2. iFIX Objects _____________________________________________

Alarm Summary

Application

Arc

Bitmap

Chart

Chord

Color Button

ControlContainer

DataItem

DataItems

DataLink

DataServer

DataServers

Document

Documents

DynamoSet

Event

ExpressionEditor

FindReplace

FixDataSystem

FixFloatPoint

Format

Group

Group (DataSystem)

Groups

Legend

Line
Lines

Linear

Lookup

Oval

Picture

Pen

Pie

Polygon

Polyline

Procedures

Rectangle

RoundRectangle

Scheduler

ScriptLine

ScriptProcedure

ScriptSource

Sources

System

Text

TimeAxis

Timer

UserGlobals

ValueAxis

Variable

Window
Figure 10-2: iFIX Objects

Copyright (c) 1999, Intellution, Inc.

10-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

10.3. iFIX Subroutines _________________________________________


A. iFIX includes a variety of pre built subroutines and functions

Over forty subroutines and functions can be used in VBA scripting

B. Subroutines can be used in the following ways:

Subroutines to allow working with iFIX alarms

Subroutines to allow such actions as reading and writing to the process database

Subroutines to manipulate process database block modes

Subroutines to allow picture navigation

Subroutines to get information about the iFIX environment

Subroutines to handle script errors

And more
-

Figure 10-3 contains the iFIX Subroutines that are available

Copyright (c) 1999, Intellution, Inc.

10-6

*()DQXF

ZZZML\LWHFKFRP


Student Guide

10.3. iFIX Subroutines _________________________________________

AcknowledgeAllAlarms

LogIn

AcknowledgeAnAlarm

OffScan

CloseDigitalPoint

OnScan

ClosePicture

OpenDigitalPoint

DisableAlarm

OpenPicture

EnableAlarm

PictureAlias

FetchLimits

PrintReport

FindDataSource

QuickAdd

FindLocalObject

RampValue

GetAllConnections

ReadValue

GetDecimalSeparator

RegCloseKey

GetFormDynamoColor

RegOpenKeyEx

GetFormNumeric

ReplacePicture

GetFormPushbutton
GetFormRamp

SetAuto

SetManual

GetFormSlider

GetLocaleInfoA

ShellExecute

ToggleDigitalPoint

GetUserDefaultLCID

ToggleManual

HandleError

ToggleScan

IsUserFxg

WriteValue

LocateObject
Figure 10-3: iFIX Subroutines

Copyright (c) 1999, Intellution, Inc.

10-7

*()DQXF

10.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Accessing the Process Database __________________________

A. Accessing the iFIX database

Subroutines will allow such actions as reading and writing to the process database
blocks, working with block alarms and manipulating the mode of database blocks

Note that when referring to a specific node, tag, field combination the VBA
subroutines syntax can be formatted in multiple ways

Example writing to a database block named AI1:


-

WriteValue 45, "AI1"

WriteValue 45, "Scada10d.Ai1.f_cv"

WriteValue 45, "Fix32.Scada10d.Ai1.f_cv"

WriteValue (variableName), "fix32.Scada10d.Ai1.f_cv"

B. Subroutines that manipulate block values in the process database

CloseDigitalPoint closes, or sends a value of 1, to the specified digital block


CloseDigitalPoint "DO1"

FetchLimits returns the High and Low EGUs of the specified data source
-

Call FetchLimits ("FIX32.NODE1.AI1.F_CV", sngHi, sngLo, intRet)

OpenDigitalPoint opens, or sends a value of 0, to the specified digital block


-

RampValue ramps a block by a pre determined value or percentage of EGU


-

lValue = ReadValue("AI1")

ToggleDigitalPoint toggles the current state of the digital block


-

RampValue "25", True, "AO1"

ReadValue reads the value of the specified block storing the result in a variable
-

OpenDigitalPoint "DO1"

ToggleDigitalPoint "DO1"

WriteValue sets the value of the current value of the specified database block
-

WriteValue 1, "DO1"

Copyright (c) 1999, Intellution, Inc.

10-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

10.4. Accessing the Process Database ___________________________


C. Subroutines that affect block alarms in a process database

DisableAlarm disables alarm limit checking for the specified block


-

DisableAlarm "AI1"

EnableAlarm enables alarm limit checking for the specified block


-

EnableAlarm "AI1"

D. Subroutines that affect block modes in a process database

OffScan places the specified block off scan


-

OnScan places the specified block on scan


-

OnScan "AI1"

SetAuto sets the specified block to automatic mode


-

OffScan "AI1"

SetAuto "AI1"

SetManual sets the specified block to manual mode


-

SetManual "AI1"

ToggleManual toggles the mode status between manual and automatic


-

ToggleManual "AI1"

ToggleScan toggles the scan status of the specified block


-

ToggleScan "AI1"

E. Subroutine that adds a process database block

QuickAdd launches the Quick Add dialog box for adding a data block
-

iStatus = QuickAdd("NewBlock1")

Copyright (c) 1999, Intellution, Inc.

10-9

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

10.4.1. FindDataSource Subroutine _____________________________


A. Notes

Returns a tag name from the specified object's animation objects.

Used for retrieving the process database tag name used in the animation operation

There is Help in writing general purpose code

B. Example of using MsgBox and FindDataSource to display a data source in full

FIX32.Node.Tag.Field

Event code body (see Figure 10-4)

Dsplevel is the name of the embedded filled object

FindObject returns an object pointer to that object

FindDataSource returns the tag information for the object animation

Figure 10-5 displays the results of the script

Private Sub Tank_DblClick ()

Dim sDatasource as String,

Dim Tankobj as Object

Set Tankobj = Tank.FindObject(dpslevel)


sDataSource = FindDataSource(Tankobj, VerticalFillPercentage)
MsgBox Tankobj.Name & => & sDataSource

End Sub

Figure 10-4: Example Code

Figure 10-5: Tag Information

Copyright (c) 1999, Intellution, Inc.

10-10

*()DQXF

ZZZML\LWHFKFRP


Student Guide

10.4.1. FindDataSource Subroutine _____________________________

Figure 10-6: FindDataSource Function Help Topic

Copyright (c) 1999, Intellution, Inc.

10-11

*()DQXF

10.5.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Shell Function __________________________________________

A. Notes

Runs an executable program and returns a Variant (Double) representing the


program's task ID if successful, otherwise it returns zero

Syntax
Shell(pathname[,windowstyle])
-

pathname Required

Variant (String)

Name of the program to execute and any required arguments or


command-line switches; may include directory or folder and drive

windowstyle Optional

Variant (Integer) corresponding to the style of the window in


which the program is to be run

If windowstyle is omitted, the program is started minimized with


focus

B. Additional Notes

If the Shell function successfully executes the named file, it returns the task ID of
the started program
-

The task ID is a unique number that identifies the running program

If the Shell function can't start the named program, an error occurs

The Shell function runs other programs asynchronously


-

This means that a program started with Shell might not finish executing
before the statements following the Shell function are executed

Copyright (c) 1999, Intellution, Inc.

10-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

10.5. Shell Function ___________________________________________

Constant

Value

Description

vbHide

Window is hidden and focus is passed to


the hidden window.

vbNormalFocus

Window has focus and is restored to its


original size and position.

vbMinimizedFocus

Window is displayed as an icon with focus.

vbMaximizedFocus

Window is maximized with focus.

vbNormalNoFocus

Window is restored to its most recent size


and position. The currently active window
remains active.

vbMinimizedNoFocus

Window is displayed as an icon. The


currently active window remains active.

Figure 10-7: Window Style Options for the Shell Function

Copyright (c) 1999, Intellution, Inc.

10-13

*()DQXF

10.6.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Database Functions _____________________________________

A. The following list contains the iFIX Database Functions that are available

The functions allow access and manipulation of the process database using the
Easy Data Access layer of the iFIX architecture

EDA (Easy Data Access)

eda_add_block
-

eda_delete_block
-

Saves the current active database to a file

eda_type_to_index

Retrieves the type index for the specified string containing a block type

FixGetMyName
-

Loads the specified PDB to a file into the specified node

eda_save_database
-

Retrieves the PDB file name from the database

eda_reload_database
-

Deletes the specified database block from the database

eda_get_pdb_name
-

Add a new block of the specified type on the specified node

Get the node name of this node whether or not the FIX is running

NlsGetText
Translates an error number returned as a string.

Copyright (c) 1999, Intellution, Inc.

10-14

*()DQXF

ZZZML\LWHFKFRP


Student Guide

10.6. Database Functions ______________________________________

Figure 10-8: eda_add_block Function

Copyright (c) 1999, Intellution, Inc.

10-15

*()DQXF

10.7.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_________________________________________ Lab Exercise 10

Accessing the Process Database


Lab Exercise 10

Copyright (c) 1999, Intellution, Inc.

10-16

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 10


Learning Objectives:
Upon successful completion of this lab exercise, you will know how to read the data source
from a selected object, and strip off the field of that data source. You will also learn to how
to append your own fields and write data to some other fields. Also you will use the pre built
subroutines to perform other database block functions.
As you progress through this lab, you will:

Use ToggleScan and ToggleMode to change the status of a block

Use DisableAlarm and EnableAlarm to change block alarm status

Use ReadValue to get data out of the Process Database

Read/Write the Alarm Extension fields

Use Shell function to load the Alarm History application

Use QuickAdd function to add new database block

When you are finished with this lab, turn to page 10-26 and answer the Summary Questions.

Resources:

The iFIX On-line Help and E-Books


The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information
You will work with an existing picture and form. The form displays status information on
any object in a picture that has the selectable property set to true. The form has five tabs.
The tab names are Status, Control, Alarms, Chain, and Tools. Clicking on any of the tabs
(except Tools) calls a subroutine specific to that tab.
You will be working with the Control, Alarms, and Tools tabs adding additional code to the
form. There will be no need to add any additional controls to the form. All the form
development except the new code to add has been done.
Basically the form is called up, the user selects a Data Link object then clicks on the Status
tab of the form. Information about the database block is filled in the form.

Copyright (c) 1999, Intellution, Inc.

10-17

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 10


A. Develop the code to trim the data source to a base level
The Process Database data source is Server.Node.Tag.Field. The basic part of the
datasource that will stay the same is the Server.Node.Tag. The Field is what supplies the
different information about the tag. To start we need to capture the source and trim off
the Field then add the specific Fields back on the source when we want specific data.
1. Open the picture called Level_Track in the configure mode of the WorkSpace.
The screen should resemble the following:

Copyright (c) 1999, Intellution, Inc.

10-18

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 10


A. Develop the code to trim the data source to a base level (continued)

2. Open the VBE and double click on the form frmTagStatus


The form should resemble the following:

Copyright (c) 1999, Intellution, Inc.

10-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 10


B. Create the code for accessing the data source and trimming the Field
First we need to understand how the form works.
1. View the code for the form. Notice that there are a number of variables defined to
store the data.
2. Look for the procedure MultipageTagStatus_Click.

The line tagsource = FindDataSource(iObject) is how the complete


Server.Node.Tag.Field is brought into the variable tagsource.
The line immediately after calls the subroutine TagStatus. This is where we will
write our trim code.

Copyright (c) 1999, Intellution, Inc.

10-20

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 10


B. Create the code for accessing the data source and trimming the Field (continued)

3. Go to the subroutine named TagStatus. Add the following four lines of code needed
to trim off the field

Public Sub TagStatus()


On Error GoTo myErrHandler

tagTrim = InStr(tagsource, ".")


tagTrim = InStr((tagTrim + 1), tagsource, ".")

tagTrim = InStr((tagTrim + 1), tagsource, ".")


tagsource = Left$(tagsource, tagTrim)

tagName = readvalue(tagsource & "A_TAG")

To do this we look for a specific character, the period. The InStr function searches
the variable tagsource for the first period starting from the left. The characters are
counted and stored in the variable tagTrim. We then use the InStr function to go the
number of characters in TagTrim + 1 then to the next period. This repeats again until
we are at the last period before the Field. Since we now know the number of
characters to get just the Server.Node.Tag we then use the Left$ function to get the
correct characters from tagsource.
Now anytime TagStatus is called the tagsource will be trimmed. This means any time
you want to update the source, call TagStatus.

Copyright (c) 1999, Intellution, Inc.

10-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 10


C. Test the new code in WorkSpace Run mode
Selecting various links in the picture then clicking on the Status tab should provide tag
information.
1. Return to the WorkSpace and switch to run mode.
2. Select one of the Analog Input data links, and click the Tag Status button.
The screen should resemble the following:

Remember to click the Status tab to refresh the form!


3. Select other data links on the screen.
If you select a link to an Analog Output tag, you will get a message stating that this
block has no scan status. Also, the Control and Alarms tabs are disabled.

Copyright (c) 1999, Intellution, Inc.

10-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 10


D. Create the code for controlling block status and mode

1. The Status tab is now complete. Clicking on the Status tab calls the subroutine
TagStatus.
TagStatus reads in a variety of fields using the ReadValue subroutine with the
tagsource variable. One of the fields TagStatus reads in is the block name. The
statement looks like this tagName = readvalue(tagsource & "A_TAG")
2. Since we already have the block name in the variable called tagName we can build
the toggle subroutines using tagName variable as the source to toggle.
3. Again, open form in the VBE. Click on the Control tab. Select one of the
pushbuttons and Edit Script writing the following code appropriately. Note that
TagControl subroutine is called. This refreshes the data since it will have changed.

Private Sub CmdToggleScan_Click()


togglescan tagName

TagControl

End Sub

Private Sub CmdToggleMode_Click()


togglemanual tagName
TagControl
End Sub

The subroutines (ToggleManual, ToggleScan) are part of iFIX Automation Interfaces


4. Test the code in WorkSpace Run mode.

Copyright (c) 1999, Intellution, Inc.

10-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 10


E. Create code on your own to work with alarming
New code will be added to enable or disable alarms, read data into the Alarm Extension
text boxes and write new data to the Alarm Extension of the Process Database block.
1. Write code to populate the Alarm Extension text boxes with data. Clicking on the
Alarms tab calls a subroutine called TagAlarms. The variables to store the Alarm
Extension data are already defined but the code to populate them has not.
2. You decide how to write the code based on the existing code.
Hint: the fields for accessing the Alarm Extensions are A_AlmExt1 and A_AlmExt2.
3. Next, write code that writes any data the user has typed into the Alarm Extension text
boxes to the Process Database block.

Hint: Update Alarm Extensions button should capture the data in the text boxes and
send it to the proper fields using the WriteValue sub routine.

Hint: The subroutines (ReadValue,WriteValue,EnableAlarm,DisableAlarm) are part


of iFIX Automation Interfaces

Copyright (c) 1999, Intellution, Inc.

10-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 10


F. Create code for the Tools tab
Additional code will be added to load the Alarm History application and adding a new
block to the Process Database.
1. With form in the VBE, select the Tools tab.
2. Add code to the pushbutton Alarm History. The code will use the Shell function to
load the Alarm History program (ALMHIS.EXE). Alarm History should have focus
when it is loaded. Use the iFIX Automation Interface help for usage of the Shell
function.
3. Now add code to the Add New Block pushbutton. Use the QuickAdd subroutine to
add a block.

Hint: QuickAdd requires a block name. Since it cannot be hard coded use the
InputBox as a method of supplying a name.

Hint: Create a variable called NewBlockName and populate this variable with user
input from the InputBox function. Use the iFIX Automation Interface help for usage.

End of Lab Exercise

Copyright (c) 1999, Intellution, Inc.

10-25

*()DQXF

10.8.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Summary Questions _____________________________________

1. Whats the advantage of using ReadValue and WriteValue as opposed to reading and
writing the values directly?

2. What are the advantages to using FindObject and finddatasource?

3. How could the FetchLimits Function be used? Give an example.

4. What is the purpose of the Alarm Extension fields? How can you use them with VBA?

5. Explain the purpose of the Shell function.

Copyright (c) 1999, Intellution, Inc.

10-26

*()DQXF

11.

ZZZML\LWHFKFRP


Student Guide

Error Handlers ___________________________________________

Chapter 11
Error Handlers

Copyright 1999, Intellution, Inc.

11-1

*()DQXF

11.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Error Handlers ___________________________________________

Section Objectives
This section provides information on dealing with error handlers. This includes the following:

Understanding when to use error handers

How to use error handers

Error Handler code examples

This chapter also contains a list of all the VBA error codes.

Copyright 1999, Intellution, Inc.

11-2

*()DQXF

11.1.

ZZZML\LWHFKFRP


Student Guide

Introduction to Error Handling ____________________________

A. Error handling should be a part of good programming technique

VBA programming must allow for potential errors


-

Supplying invalid argument

Supplying invalid function

Attempting to run tasks that are non existent

Accessing an invalid file path

Why in the world would anybody do that

Error handling should include:


-

Trapping the error

Either fixing the error automatically or supply means to fix it

Supply a meaningful message to the user when appropriate

Copyright 1999, Intellution, Inc.

11-3

*()DQXF

11.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Introduction to Error Handling _______________________

B. What is an error handler?

Error Handler is a group of statements that process the error


-

Sets the error trap

Handles the error

Exits the error handler

Resumes program execution

C. Where does an error handler exist?

Error handler code could exist in each procedure

Error handler code could be a global error handler that is called

Error handling can also make use of the Err Object

Copyright 1999, Intellution, Inc.

11-4

*()DQXF

11.1.

ZZZML\LWHFKFRP


Student Guide

Introduction to Error Handling _______________________

D. What happens if an error handler is not used?

VBA searches for any active error handlers if none are found VBA handles it

Allowing VBA to handle errors sometimes is ok but often can cause issues
-

Code could get stuck in a loop

Nothing happens

Invalid results etc.

Any error messages that VBA creates may not provide good information

Figure 11-1: VBA Error Example

Copyright 1999, Intellution, Inc.

11-5

*()DQXF

11.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Handling Basic Errors ___________________________________

A. There are several ways to dealing with errors in code

One way is to use the Error Handling tools within VBA


-

This method finds any error that occurs during run time

This chapter focuses on using these tools

Another way is to simply use logic to check for error conditions within the code
-

This method only finds the errors that are specifically checked for during
execution

B. Example of a procedure that uses If Then logic in place of an error handler

See Figure 11-2

The If Then statement determines if an error has occurred

Pops up a MsgBox to the user with a message

Only provides error handling for errors that meet specific criteria

Copyright 1999, Intellution, Inc.

11-6

*()DQXF

11.2.

ZZZML\LWHFKFRP


Student Guide

Handling Basic Errors ______________________________

Private Sub WebTech_Click()


Dim lVar As Long
Dim Result
lVar = GetFocus()

' This shell function accesses the internet, and opens


' directly to the Intellution Technical Support Website
Result = ShellExecute(lVar, "Open",_
"http:\\www.intellution.com/services/",_
vbNullString, vbNullString, 5)

' ShellExecute is a Windows A PI call included in


' the iFIX Automations.

' It returns various values value less than 32 is failure

' Error check - If the local node is not connected


' to the internet, display an error message

If Result < 32 Then

MsgBox "You need to be connected to a server" & Chr(13) & _


"and have an internet browser to " & Chr(13) & _
"view the Intellution web site."

End If

End Sub

Figure 11-2: If Then Example

Copyright 1999, Intellution, Inc.

11-7

*()DQXF

11.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Using an Error Handler___________________________________

A. Dealing with the error

Decide what information the user needs about the error or resolving the error

Decide how you want to present information the user

Present a message using MsgBox

Provide additional information using the Err Object

Important Note:
-

Do NOT use a MsgBox in a script running in a background schedule

This will stop the script and hang up the Scheduler thread

B. Setting the error trap in a procedure

Use On Error GoTo statement to point to the error handler code

Decide when you want to trap errors

Check for error condition anytime during the running of the procedure

Check for error condition after every statement in the procedure

C. Using the Err Object

VBA traps more than two hundred errors

Information about the VBA errors can be retrieved from the Err object

The three Err Object properties used the most are as follows:

Err.Description returns the error description

Err.Number returns the error number

Err.Source returns the name of the project in which the error occurred

Err object has a few methods that may be used as well


-

Err.Clear resets the all the Err objects properties

Err.Clear is invoked automatically when certain statements are run

Err.Raise invokes a runtime error on purpose

Copyright 1999, Intellution, Inc.

Err.Raise is used to test the error handler

11-8

*()DQXF

11.3.

ZZZML\LWHFKFRP


Student Guide

Using an Error Handler___________________________________

Private Sub CommandButton2_Click()


Dim x As Integer,

y As Integer,

z As Integer,

msg As String

On Error GoTo MyHandler


x = 5
y = 0
z = x / y

Exit Sub

MyHandler:
' Display the error message

msg = "An error occurred!" & Chr(13) & Chr(13) & _


"Error number:

" & Err.Number & Chr(13) & _

"Error message: " & Err.Description

MsgBox msg, vbOKOnly + vbCritical

End Sub

Figure 11-3: Err Object Example

Figure 11-4: Message with Err Object Information

Copyright 1999, Intellution, Inc.

11-9

*()DQXF

11.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Using an Error Handler___________________________________

D. Exiting the error handler and resuming program execution

Decide on a method to resume program execution


-

Use Resume statement to return to line of code which caused the error

Use Resume Next statement to go to the next statement after the one
which caused the error

Use Resume <Label> statement to resume at a specific location

Use On Error Resume Next to go by error and continue (not


recommended)

DivByZeroHandler:

' Display the error message

msg = "An error occurred!" & Chr(13) & Chr(13) & _


"Error number:

" & Err.Number & Chr(13) & _

"Error message: " & Err.Description

MsgBox msg, vbOKOnly + vbCritical

Select Case Err.Number

' Check the error number

Case 11

' Division by zero

Resume GetDivisorOnly

Case 6

' Overflow

Resume GetDividendAndDivisor
Case 13

' Type mismatch

If Not IsNumeric(dividend) Then


Resume GetDividendAndDivisor
Else
Resume GetDivisorOnly
End If
Case Else

' Anything else, just quit

Exit Sub
End Select

Figure 11-5: Resuming Program Execution Example

Copyright 1999, Intellution, Inc.

11-10

*()DQXF

11.3.

ZZZML\LWHFKFRP


Student Guide

Using an Error Handler___________________________________

Private Static Sub Rect2_Click()


'procedure adds values and displays in MsgBox until exit

Static newtotal As Integer


Dim entry
On Error GoTo InputErrHandler

UserInput:
entry = InputBox("Enter Value to be added")
If entry = "" Then

MsgBox "No Value Entered or Invalid Data T ype"


Exit Sub
Else

'try to convert to Integer


entry = CInt(entry)

newtotal = (newtotal + (entry)) 'add new value to existing

MsgBox "The New Value is " & (newtotal)

End If

GoTo UserInput 'return to Input box

InputErrHandler:
Resume Next 'if error go to next statement after error

End Sub

Figure 11-6: Resume Next Statement Example

Copyright 1999, Intellution, Inc.

11-11

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

11.3.1. Procedure Based Error Handler __________________________


A. Example of a procedure that uses a procedure level defined error handler

The name of the error handler is MyErrHandler

Pops up a MsgBox to the user with a message


-

recall that MsgBox or other user interface code should NOT be used in an
Error Handler for a script running in a background schedule

Error handler uses the Err Object to provide more information

MsgBox includes additional information displaying properties of the Err Object

Err.Number adds error number in the MsgBox

Err.description adds an error description

Use Select Case structure to examine the Err.number


-

The code can react differently depending on the error number

Other properties of the Err Object include:


-

Err.Source returns the name of the project the error occurred

Copyright 1999, Intellution, Inc.

11-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

11.3.1. Procedure Based Error Handler __________________________

Private Sub CommandButton4_Click()


Dim strPath As String
On Error GoTo MyErrHandler
strPath = System.BasePath
' This shell function will run the executable file
' Almhis.exe

Shell strPath & "\Almhxc cis.exe", 1


Exit Sub

MyErrHandler:

MsgBox "Unable to Start Application

" & _

Chr(13) & Chr(13) & _

"Error number:

" & Err.Number & Chr(13) & _

"Error message: " & Err.Description

Resume Next
End Sub

Figure 11-7: Procedure Level Defined Error Handler

Copyright 1999, Intellution, Inc.

11-13

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

11.3.2. Global Based Error Handler______________________________


A. Example of a procedure that calls a global error handler

On Error GoTo statement is placed et the top of the procedure


-

ErrorHandler is the label that the code will jump to when an error occurs
-

Note: VBA cannot go to a label outside the procedure

The error handling code would be placed after the label ErrorHandler:
-

This protects all the statements in the procedure

Or, as in the example uses the name of a global error handler

Note Exit Sub is before the error handler


-

Ensures the error handler is bypassed if no errors occur

Copyright 1999, Intellution, Inc.

11-14

*()DQXF

ZZZML\LWHFKFRP


Student Guide

11.3.2. Global Based Error Handler______________________________

Private Sub DataBaseManager_Click()


Dim strPath As String
On Error GoTo ErrorHandler
strPath = System.BasePath

' This shell function will run the executable file


' DatabaseManager.exe
Shell strPath & "\DatabaseManager.exe", 1

Exit Sub

ErrorHandler:

HandleError

End Sub

Figure 11-8: Global Level Defined Error Handler

Copyright 1999, Intellution, Inc.

11-15

*()DQXF

11.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA Error Codes ________________________________________

A. Error Codes

Trappable errors can occur while an application is running

Some trappable errors can also occur during development or compile time

Test and respond to trappable errors using the On Error statement and the Err
object

See page 11-17 for a list of VBA error codes


-

Unused error numbers in the range 1 1000 are reserved for future use

Copyright 1999, Intellution, Inc.

11-16

*()DQXF

11.4.

ZZZML\LWHFKFRP


Student Guide

VBA Error Codes ________________________________________

Code
3
5
6
7
9
10
11
13
14
16
17
18
20
28
35
47
48
49
51
52
53
54
55
57
58
59
61
62
63
67
68

Message
Return without GoSub
Invalid procedure call
Overflow
Out of memory
Subscript out of range
This array is fixed or temporarily locked
Division by zero
Type mismatch
Out of string space
Expression too complex
Can't perform requested operation
User interrupt occurred
Resume without error
Out of stack space
Sub, Function, or Property not defined
Too many DLL application clients
Error in loading DLL
Bad DLL calling convention
Internal error
Bad file name or number
File not found
Bad file mode
File already open
Device I/O error
File already exists
Bad record length
Disk full
Input past end of file
Bad record number
Too many files
Device unavailable

Figure 11-9: VBA Error Codes

Copyright 1999, Intellution, Inc.

11-17

*()DQXF

11.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA Error Codes ________________________________________

Code
70
71
74
75
76
91
92
93
94
97
298
320
321
322
325
327
328
335
336
337
338
360
361
363
364
365
368
371
380
381

Message
Permission denied
Disk not ready
Can't rename with different drive
Path/File access error
Path not found
Object variable or With block variable not set
For loop not initialized
Invalid pattern string
Invalid use of Null
Can't call Friend procedure on an object that is not an instance of the
defining class
System DLL could not be loaded
Can't use character device names in specified file names
Invalid file format
Cant create necessary temporary file
Invalid format in resource file
Data value named not found
Illegal parameter; can't write arrays
Could not access system registry
ActiveX component not correctly registered
ActiveX component not found
ActiveX component did not run correctly
Object already loaded
Can't load or unload this object
ActiveX control specified not found
Object was unloaded
Unable to unload within this context
The specified file is out of date. This program requires a later version
The specified object can't be used as an owner form for Show
Invalid property value
Invalid property-array index

Figure 11-9: VBA Error Codes (continued)

Copyright 1999, Intellution, Inc.

11-18

*()DQXF

11.4.

ZZZML\LWHFKFRP


Student Guide

VBA Error Codes ________________________________________

Code
382
383
385
387
393
394
400
402
419
422
423
424
425
429
430
432
438
440
442
443
445
446
447
448
449
450
451
452
453
454

Message
Property Set can't be executed at run time
Property Set can't be used with a read-only property
Need property-array index
Property Set not permitted
Property Get can't be executed at run time
Property Get can't be executed on write-only property
Form already displayed; can't show modally
Code must close topmost modal form first
Permission to use object denied
Property not found
Property or method not found
Object required
Invalid object use
ActiveX component can't create object or return reference to this object
Class doesn't support Automation
File name or class name not found during Automation operation
Object doesn't support this property or method
Automation error
Connection to type or object library for remote process has been lost
Automation object doesn't have a default value
Object doesn't support this action
Object doesn't support named arguments
Object doesn't support current locale setting
Named argument not found
Argument not optional or invalid property assignment
Wrong number of arguments or invalid property assignment
Object not a collection
Invalid ordinal
Specified DLL function not found
Code resource not found

Figure 11-9: VBA Error Codes (continued)

Copyright 1999, Intellution, Inc.

11-19

*()DQXF

11.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA Error Codes ________________________________________

Code
455
457
458
459
460
461
480
481
482
483
484
485
486
520
521
735
744
746
31001
31004
31018
31027
31032
31036
31037

Message
Code resource lock error
This key is already associated with an element of this collection
Variable uses a type not supported in Visual Basic
This component doesn't support events
Invalid Clipboard format
Specified format doesn't match format of data
Can't create AutoRedraw image
Invalid picture
Printer error
Printer driver does not support specified property
Problem getting printer information from the system. Make sure the
printer is set up correctly
Invalid picture type
Can't print form image to this type of printer
Can't empty Clipboard
Can't open Clipboard
Can't save file to TEMP directory
Search text not found
Replacements too long
Out of memory
No object
Class is not set
Unable to activate object
Unable to create embedded object
Error saving to file
Error loading from file

Figure 11-9: VBA Error Codes (continued)

Copyright 1999, Intellution, Inc.

11-20

*()DQXF

12.

ZZZML\LWHFKFRP


Student Guide

Automation______________________________________________

Chapter 12
Automation

Copyright (c) 1999, Intellution, Inc.

12-1

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

12. Automation _______________________________________________


Section Objectives
This section provides an overview of Automation. The student will be able to create VBA
scripts that will access objects or functionality in another application. The section will include
the following topics:

Automation

References

Binding

Create Object Function

Get Object Function

Copyright (c) 1999, Intellution, Inc.

12-2

*()DQXF

12.1.

ZZZML\LWHFKFRP


Student Guide

Introduction to Automation _______________________________

A. Automation is basically one application making its services available to another

Excel could make its calculator available to Word

An OPC server could make its Items available to iFIX

Word could allow iFIX VBA script to start Word and append a document

SQL Server could allow another application to build databases and tables

An application makes its services(objects) available through a library reference

An instance of the application being referenced is loaded in memory

B. Two things need to happen in order for Automation to be successful

The VBA project needing to connect to another application must have a reference
to that applications object library
-

This enables the ability to create VBA scripts and have helpful
functionality available like Intellisense during development

An instance of the application you want to work with must be loaded into memory
-

This allows the script to work in runtime and during testing in


development mode

Copyright (c) 1999, Intellution, Inc.

12-3

*()DQXF

12.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Adding References ______________________________________

A. Notes

Before working with another applications objects you must set up a reference to
that applications object library
-

This could be a reference to a .DLL, .EXE, .TLB, .OCX and more

The developer must make sure the proper library is installed

Once a reference is established the objects for that application are available

B. Adding References

New references are added in the VBE


-

Highlight a project in the VBE that needs to access another application

From the Tools menu, select References

see Figure 12-1

Activate the other applications appropriate library in reference list

list will contain object libraries and automation servers

checked items in the list are listed by priority

unchecked items in the list are listed alphabetically

C. Additional Notes

Selected references are available to browse in the Object Browser

The available references are based on the application installation and NT registry
-

references are stored in the NT Registry

Copyright (c) 1999, Intellution, Inc.

MyComputer\HKEY_CLASSES_ROOT\TypeLib\

12-4

*()DQXF

12.2.

ZZZML\LWHFKFRP


Student Guide

Adding References ______________________________________

Figure 12-1: Object Library Reference List Example

Copyright (c) 1999, Intellution, Inc.

12-5

*()DQXF

12.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Making the Connection___________________________________

A. Reference notes

Once the proper library reference is made in a VBA project, the objects for that
reference are available to be used in VBA script

Not all applications have library references to support Automation


-

Examples: Paint, Wordpad, and Wordart

These examples can contain objects but the objects can not be manipulated
by other applications (Automation controllers)

They do not have an object library to reference

B. Automation notes

Based on a one way connection using a Client/Server relationship

Included as part of Microsoft COM technology

The client is considered the Automation controller

manipulates the Automation servers objects

instructs the Automation server to do something

Client must set up a reference to the servers object library

The server is considered the Automation server


-

must expose native objects via an Object Library

responds to the clients instructions

The concept of Binding is used to connect the Automation controller and the
Automation server
-

an instance of the application will be in memory at this time

This binding process can take place the first time an object is accessed during
VBA script development or during runtime of the script

Copyright (c) 1999, Intellution, Inc.

12-6

*()DQXF

12.3.

ZZZML\LWHFKFRP


Student Guide

Making the Connection___________________________________

C. Server only applications have no VBA development environment to access external


objects

These applications do have their own object library available for clients to access

Examples:
-

Outlook

Internet Explorer

Explorer

ActiveX objects

D. Some applications that allow Automation can be both a Client and Server

These applications do have a VBA development environment to access external


objects

These applications also have their own object library reference for clients to
access

Examples:
-

iFIX

Word

Excel

PowerPoint

Access

Copyright (c) 1999, Intellution, Inc.

12-7

*()DQXF

12.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Creating an Instance of the Application _____________________

A. Binding connects the Automation controller and the Automation server

Normally binding will be accomplished in the VBA code using both the Dim and
Set statements

An object variable is created with the Dim statement


-

binding associates the object variable to the actual Automation object in


the server

The Set statement will load the instance of the application being referenced into
memory

Binding uses the concepts of late or early binding


-

Late binding means it occurs at runtime

All Automation servers support late binding

No automatic error checking during design phase

Early binding occurs at design time

Occurs after script runs the Dim and Set statements

VBE checks for syntax errors

Intellisense is available

Code will run faster because object resolution is already done

Note: Some older applications do not support early binding

It is possible to bind using the Dim statement without the Set but this has other
consequences such as non efficient memory usage

B. There are multiple ways to use the Dim and Set statements

Using the New keyword with the Dim or Set statement

Using the CreateObject function instead of the New keyword

Using the GetObject function instead of the New keyword

Copyright (c) 1999, Intellution, Inc.

12-8

*()DQXF

12.4.

ZZZML\LWHFKFRP


Student Guide

Creating an Instance of the Application _____________________

Dim newobj As New Word.Application

Figure 12-2: Dim Statement with New Keyword Example

Dim wordApp As Word.Application


Set WordApp

= CreateObject(Word.Application)

Figure 12-3: CreateObject Example

Dim wordDoc As Word.Document


Set wordDoc = GetObject(C:\Test1.doc, Word.Document)

Figure 12-4: GetObject Example

Copyright (c) 1999, Intellution, Inc.

12-9

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

12.4.1. Dim Statement using New Keyword _______________________


A. Notes

New is used in the Dim statement to create a new instance of the object
-

The new instance of the application will be loaded into memory

The instance does not have to be visible to the user

Example (see Figure 12-5)


-

VarName is the name of the object variable

Application.ObjectType specifies the Automation object class


Application name is as it appears in the Object Browser

ObjectType is the object class type

The new instance of the object is not created until the variable is referred to in a
line of code
-

Using New keyword forces early binding


-

In Figure 12-5, varname is not actually created until the second line of
code
Can be considered wasteful because it creates it before you use it

Some Automation servers do not support New keyword

CreateObject function is an alternative to using the New keyword

Dim varname As New Application.ObjectType


varname.Visible = True

Figure 12-5: Using the New Keyword

Copyright (c) 1999, Intellution, Inc.

12-10

*()DQXF

12.4.2.

ZZZML\LWHFKFRP


Student Guide

Set Statement _________________________________________

A. The Set statement also lets VBA know you want to work with the Automation object

The Set statement creates a new instance as soon as the Set statement is run

Set can also use the keyword New to create a new instance of the object

Example (see Figure 12-6)


-

VarName is the name of the object variable

Application.ObjectType specifies the Automation object class

Application name is as it appears in the Object Browser

ObjectType is the object class type

Set varName = New Application.ObjectType

Figure 12-6: Using the Set Statement

Copyright (c) 1999, Intellution, Inc.

12-11

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

12.4.3. CreateObject Function __________________________________


A. CreateObject is a function that explicitly creates a new instance of an Automation object

CreateObject is usually used within a Set statement

Depending how the new object variable is declared determines if early or late
binding is used
-

VBA will use early binding if a class argument is included

Providing a class type helps VBA to resolve ambiguous object


names and since the class type is specified VBA does not have to
resolve the objects application

VBA will use late binding if the declaration of the variable is as Object

The declaration can include a class argument to specify a class type

Dim wordApp As Object

Set wordApp = CreateObject(Word.Application)

Figure 12-7: Create Object Example

Copyright (c) 1999, Intellution, Inc.

12-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

12.4.4. GetObject Function_____________________________________


A. GetObject is a function that can be used if the object already exists or is already open

Prevents a second instance of the application from loading

GetObject(pathname, class)
-

Pathname can be drive, folder and filename or a file containing the object
you want to work with.

Class specifies the Automation Server application and the type of object to
work with

Application.ObjectType

Providing a class type helps VBA to resolve ambiguous object


names and since the class type is specified VBA does not have to
resolve the objects application

Dim wordDoc As Word.Document


Set wordDoc = GetObject(C:\Dynamics\MyNotes.doc, Word.Document)

Figure 12-8: GetObject Function Example

Copyright (c) 1999, Intellution, Inc.

12-13

*()DQXF

12.5.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Example 1 ____________________________________________

A. E-mail (Outlook) example

iFIX can be used to generate e-mail messages, for example:


-

When an alarm condition occurs

At the end of the shift, day, week, month, etc.

Use the following steps for sending a message using Microsoft Outlook:
-

Use the Scheduler to run a custom script

In the VBE, make sure that in the Tools menu, References item,
"Microsoft Outlook 8.0 Object Library" is checked off

Enter the script in Figure 12-9

The NewMessage.Body can be virtually anything, for example:


-

An alarm description with current time and date

A report with descriptions and values which are built before the
NewMessage.Body statement is executed

This will place the message in the "Outbox" until the next time the messages are
sent
-

This can be done be setting up Outlook to check for messages every so


often or by adding code to trigger the send messages command

Copyright (c) 1999, Intellution, Inc.

12-14

*()DQXF

12.5.

ZZZML\LWHFKFRP


Student Guide

Example 1______________________________________________

Private Sub CreateNewOutlookMailMessage()

Dim ol As Object
Dim NewMessage As Object

Set ol = New

Outlook.Application

Set NewMessage = ol.CreateItem(olMailItem)

' You can send the message to a person in your


' personal address book or just use the email address

NewMessage.To = "John Doe; training@intellution.com"


NewMessage.Subject = "Using iFIX to send E-mail"

NewMessage.Body = Message goes here!"

NewMessage.Send

End Sub

Figure 12-9: E-mail script example

Copyright (c) 1999, Intellution, Inc.

12-15

*()DQXF

12.6.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Example 2______________________________________________

A. Word example

iFIX can use Word as a reporting tool

In this example, the following occurs:


-

The Word object is created

A document is opened in the Word object

in this case, the document is called MyNotes.doc

Text from a text box on a form is added to the document

The document is saved and closed

Notice that at each step, the WorkSpace status bar displays status information

Copyright (c) 1999, Intellution, Inc.

12-16

*()DQXF

12.6.

ZZZML\LWHFKFRP


Student Guide

Example 2______________________________________________

Private Sub CommandButton1_Click()


Dim Wordapp As Word.Application
'create the Word Application Object
Set Wordapp = CreateObject("Word.Application")
With Wordapp
'open an existing document
Application.StatusBar = "Opening Word Document..."
.Documents.Open ("C:\dynamics\MyNotes.doc")
'add text from form text box to document

.ActiveDocument.Paragraphs.Add.Range.InsertAfter_
UserForm1.TextBox1.Value

'save the document


Application.StatusBar = "Saving Word Document..."

.ActiveDocument.saveas "C:\dynamics\MyNotes.doc"

'shut down the application


Application.StatusBar = "Shutting Down Word..."
.quit

End With
Set Wordapp = Nothing
Application.StatusBar = ""
End If
End Sub

Figure 12-10: Writing to Word Example

Copyright (c) 1999, Intellution, Inc.

12-17

*()DQXF

12.7.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

_________________________________________ Lab Exercise 12

Automation
Lab Exercise 12

Copyright (c) 1999, Intellution, Inc.

12-18

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 12


Learning Objectives:
Upon successful completion of this lab exercise, you will be comfortable working with
Automation connecting to other applications and working with that applications objects,
properties, methods and events. In this exercise Microsoft Word will be the application to
connect to. Information from the maintenance form message will be transferred to a Word
document.
As you progress through this lab, you will:

Write code enabling a connection to Word

Write code that accounts for any open instances of Word

Write code incorporating the use of an error handler

Write code to capture data from an existing source and append it to a document

Use the Object Browser in the VBE to search for advanced features like bold font
and paragraph formatting

Write code that accounts for the document existing or not

When you are finished with this lab, turn to page 12-31 and answer the Summary Questions.

Resources:

The iFIX On-line Help and E-Books


The iFIX Automation On-line Help
Microsoft Visual Basic On-line Help

Lab Information
The first part of the lab will create the basic functionality of the Automation connection.
The second part of the lab will add advanced features.

Copyright (c) 1999, Intellution, Inc.

12-19

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 12


A. Open an existing picture.
Open a picture that displays equipment maintenance information.
1. Open the MaintOverview picture in the WorkSpace in configure mode
The screen should resemble the following:

2. Switch to Run mode to make sure the functionality of this picture is working.
Particularly the buttons that bring up the Maintenance log form.
3. You can force the equipment into Maintenance mode by clicking the Maint Now
button. This brings up the form frmMaintLog. You will be adding code to this form.
The new code will transfer the information currently viewed in the MsgBox when the
Send button is selected to a Word document.

Copyright (c) 1999, Intellution, Inc.

12-20

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 12


B. Insert new code.
Create the basic functionality to accomplish Automation.
1. Switch to the VBE
2. Open the form frmMaintLog in the code window
The form should resemble the following:

3. Right Mouse Click on the Send button and select View Code

Scrolling through the code you will notice that the code calls a subroutine called
WriteLog. The WriteLog subroutine is where the MsgBox is invoked presenting the
user with the information captured from the form.
What we want to do is call another procedure that you will design that gets called
after MsgBox and appends the Word document.
The name of the new procedure will be AppendWordDoc. Once the code is
complete add the statement AppendWordDoc as the last line in WriteLog.
The coding is going to be done in steps reflecting the goals described at the start of
the lab.

Copyright (c) 1999, Intellution, Inc.

12-21

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 12


C. Insert a new procedure.
Now that you know where the new code needs to reside and what to name it we can build
the code.
1. Insert a new procedure called AppendWordDoc. This can be a part of your form or
inserted into a module.
2. Next enter the code using the Dim statement that will create a variable to represent
the Word application
3. Next enter the code that will check for an existing instance of Word in memory. The
GetObject function will be used along with an error handler to accomplish this.
If Word is already loaded we will open the document and work with it. If Word is
not loaded in memory we will load it using the Set statement which exists in the error
handler.
The code will look as follows:
Public Sub AppendWordDoc()

Dim WordApp as Word.Application


On Error GoTo OpenWord

Set Wordapp = GetObject(, "Word.Application")

(more code to go here)

OpenWord:
Set Wordapp = CreateObject("Word.Application")
Resume Next
End Sub

This code declares the variable WordApp, then attempts to set the variable using
the GetObject function. If there is no application to get, an error occurs causing the
error handler OpenWord to be invoked. The error handler loads Word into memory
using the Set statement then Resumes Next which will be the next line of code after
the GetObject statement. You will write that code next.

Copyright (c) 1999, Intellution, Inc.

12-22

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 12


D. Adding more code
Now that there is a mechanism to load Word or use the existing instance you can add
code to append a document.
1. For now the code will be written assuming the document does exists. Remember start
simple then build in more complicated tasks.
2. Add code using the methods in the example to Open the document and Add a
paragraph of information that currently is in the string " Msg3LineStr
The code will look as follows:
Public Sub AppendWordDoc()
Dim WordApp as Word.Application

On Error GoTo OpenWord

Set Wordapp = GetObject(, "Word.Application")

With Wordapp

.Documents.Open ("C:\dynamics\APP\MaintLog.doc")

.ActiveDocument.Paragraphs.Add.Range.InsertAfter Msg3LineStr

(more code to go here)

OpenWord:
Set Wordapp = CreateObject("Word.Application")
Resume Next
End Sub

The new code opens the document and appends to the document.

Copyright (c) 1999, Intellution, Inc.

12-23

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 12


E. Add code to save the document and quit the application
Now that the document has been appended, the document must be saved. Then the
application can be closed and removed from memory.
1. After the document is saved the application will be removed from memory. Quitting
the application using the Quit method will remove it from memory. Also the variable
is set to Nothing. This will clear the memory used for the variable.
2. Add code using the methods in the example to save the document and quit the
application.
The new code will save the document and close the application. At this point this
should be a working procedure.
Use the code on the next page as an example

3. Make sure the picture is open in Run mode, and test the new code.

4. If it is not working properly, look at the following hints:

a. During development you may have loaded instances of Word into memory and
not have unloaded them. Use task manager to check and remove if needed.

b. Did you add the line of code to the WriteLog procedure to call the
AppendWordDoc procedure?
c. Did you add Word to the list of References in VBA?

Copyright (c) 1999, Intellution, Inc.

12-24

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 12


E. Add code to save the document and quit the application (continued)

Public Sub AppendWordDoc()


Dim WordApp as Word.Application
On Error GoTo OpenWord
Set Wordapp = GetObject(, "Word.Application")
With Wordapp
.Documents.Open ("C:\dynamics\APP\MaintLog.doc")
.ActiveDocument.Paragraphs.Add.Range.InsertAfter Msg3LineStr

.ActiveDocument.saveas "C:\dynamics\APP\MaintLog.doc"

.quit
End With

Set Wordapp = Nothing

Exit Sub

OpenWord:

Set Wordapp = CreateObject("Word.Application")


Resume Next
End Sub

Copyright (c) 1999, Intellution, Inc.

12-25

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 12


F. Add code to format the data and paragraphs
Now that we have code to open Word, append the document, save it and quit the
application, the Word document will look similar to the example below. Now code can
be added to add features to format the data and separate the paragraphs.
1. The format of the document MaintLog.doc currently looks as follows:
Chuck reports that Reclaim Pump
is being { Repaired, }
Chuck reports that Reclaim Pump
is being { Repaired, }
Mark reports that Reclaim Pump
is being { Calibrated, }
Operator reports that Tank3 Value
is being { Repaired, }
Operator reports that Bulk Value
is being { Replaced, }

The document is hard to read and not easy to distinguish between messages. The new
feature you add will change this.

2. Now you will add code to Bold the text and separate any new Paragraphs

The Object Browser will be used to isolate the methods or properties that can be used
to Bold and format paragraphs.

Copyright (c) 1999, Intellution, Inc.

12-26

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 12


G. Using the Object Browser in the VBE
The Object Browser is a mechanism to help find the methods, properties and events that
are available to an application. It does not necessarily point to the exact answer. There
are many ways to perform bolding and adding paragraphs for instance. You will need to
experiment a little. Lets start with the bold feature.
1. After opening the Object Browser, select Word from the available reference list.
2. Search on the word bold and you should have a search result similar to below.

3. This list is somewhat short and it will be left up to you to write the code.
Hint: A new line can be added to invoke each new feature like bolding. The new
statement starts just like the one that appends the document. There is more than one
way to accomplish this. For instance the entire document could be bolded or each
individual paragraph as it is inserted.
4. You need to determine if the selections in the list are properties or methods. You also
need to determine how to use them. If it is a property, what is the property that would
be set? If it is a method how is it invoked?

Copyright (c) 1999, Intellution, Inc.

12-27

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

______________________________________________ Lab Exercise 12


G. Using the Object Browser in the VBE (continued)

5. After coming up with the new code the document will look as follows:

Chuck reports that Reclaim Pump


is being { Repaired, }
Chuck reports that Reclaim Pump
is being { Repaired, }
Mark reports that Reclaim Pump
is being { Calibrated, }

Operator reports that Tank3 Value


is being { Repaired, }
Operator reports that Bulk Value
is being { Replaced, }

Two new lines were added to perform bolding and inserting new paragraphs. The
bolding is done with a property that has a True or False value. The inserting of a new
paragraph is done with a method. Your result could be different.

Copyright (c) 1999, Intellution, Inc.

12-28

*()DQXF

ZZZML\LWHFKFRP


Student Guide

______________________________________________ Lab Exercise 12


G. Using the Object Browser in the VBE (continued)

The code may look as follows:

Public Sub AppendWordDoc()


Dim WordApp as Word.Application
On Error GoTo OpenWord
Set Wordapp = GetObject(, "Word.Application")
With Wordapp

.Documents.Open ("C:\dynamics\APP\MaintLog.doc")
.ActiveDocument.Range.Font.Bold = True

.ActiveDocument.Paragraphs.Add.Range.InsertParagraph

.ActiveDocument.Paragraphs.Add.Range.InsertAfter Msg3LineStr

.ActiveDocument.saveas "C:\dynamics\APP\MaintLog.doc"

.quit

End With

Set Wordapp = Nothing


Exit Sub

OpenWord:
Set Wordapp = CreateObject("Word.Application")
Resume Next
End Sub

The bold property is set to True. The Range usage bolds the complete document.
The InsertParagraph method inserts a new paragraph each time the code is run.

Copyright (c) 1999, Intellution, Inc.

12-29

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

CHALLENGE LAB _______________________________ Lab Exercise 12


If you are finished with the exercise and other students are working, feel free to try these
challenge exercises.
A. Add more code.
Here are a few somewhat advanced exercises to try. Make sure the first part of the
application is working before trying these.
1. More code could be added to check for the existence of the document.
2. Also if the Word application is already open we would not want to shut it down when
we are done with it by using the Quit method.

End of Lab Exercise

Copyright (c) 1999, Intellution, Inc.

12-30

*()DQXF

12.8.

ZZZML\LWHFKFRP


Student Guide

Summary Questions _____________________________________

1. When incorporating automation, why is a reference to the applications object library


needed to develop code successfully?

2. Explain what the Dim statement does differently then the Set statement?

3. What would be the disadvantage of using the following statement?


Dim WordApp as New Word.Application
What would be an advantage?

4. When is an application used in automation removed from memory? What is the method
that removes the application from memory?

5. Explain what happens when the object variable is set to Nothing.

Copyright (c) 1999, Intellution, Inc.

12-31

*()DQXF

12.8.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Summary Questions _____________________________________

this page intentionally contains no data

Copyright (c) 1999, Intellution, Inc.

12-32

*()DQXF

13.

ZZZML\LWHFKFRP


Student Guide

ActiveX, Linking and Embedding ___________________________

Chapter 13
ActiveX, Linking and Embedding

Copyright (c) 1999, Intellution, Inc.

13-1

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

13. ActiveX, Linking and Embedding_____________________________


Section Objectives
This section provides an overview of ActiveX concepts and components. The student will
manipulate ActiveX objects. The section will include the following topics:

ActiveX Basic Principles

ActiveX Controls

iFIX ActiveX Controls

VBA and ActiveX

Copyright (c) 1999, Intellution, Inc.

13-2

*()DQXF

13.1.

ZZZML\LWHFKFRP


Student Guide

ActiveX ________________________________________________

A. OLE architecture is a complicated technology providing many topics of discussion


including the following:

ActiveX Controls

Component Object Model (COM)

OLE Automation

Compound Documents

B. ActiveX

A set of programming technologies created by Microsoft

Allows software components created in different languages to interact with one


another locally or in a networked environment

Evolved from the OLE development standard (OLE for the internet)

Is based on the Component Object Model (COM) programming model

C. ActiveX Document

A file that can be edited through any ActiveX compliant application

ActiveX documents created with iFIX include:


-

iFIX Picture

Event Schedule

D. ActiveX Control

An object that can be manipulated by the user to perform an action i.e. a control

ActiveX controls can be used from within any ActiveX compliant application

Copyright (c) 1999, Intellution, Inc.

13-3

*()DQXF

13.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

ActiveX Basic Principles _________________________________

A. Notes

Can be created in any programming language

Allows for reusable components in application design

ActiveX controls allows for routines to be used without knowing how the
container application works

Provides functionally not envisioned by the container applications vender

Provides a special or unique function best done by the object author

VBA can access ActiveX objects as any other object in the container

The container vendor may provide some ActiveX controls as part their own
application

ActiveX controls can come from other sources like the Web and can be used for
free or require a purchase and possibly a license to use them

Typically ActiveX controls include a .OCX file along with .DLLs and help files

Copyright (c) 1999, Intellution, Inc.

13-4

*()DQXF

13.2.

ZZZML\LWHFKFRP


Student Guide

ActiveX Basic Principles _________________________________

New ActiveX term

Old OLE term

ActiveX code component

OLE server, OLE Automation server

ActiveX component
(umbrella term for ActiveX
document, ActiveX control, and
ActiveX code component)

OLE Automation server, OLE


Component, OLE control, custom
control, OLE server

ActiveX control

OLE control, custom control

ActiveX document

No corresponding OLE term

ActiveX scripting

No corresponding OLE term

Automation

OLE Automation
Figure 13-1: ActiveX and OLE Terms

Figure 13-2: ActiveX Calendar Control

Copyright (c) 1999, Intellution, Inc.

13-5

*()DQXF

13.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

iFIX ActiveX Controls ____________________________________

A. Notes

iFIX uses ActiveX controls as tools to help in building a project and as user
interface objects

The Expression Editor and the Alarm Summary object are examples of built in
controls that can be used in your project

The Alarm Summary object and the Expression Editor have exposed properties
displayed in a custom property dialog and the properties window
-

Because they are ActiveX controls you could drop them in another
container like Word and the controls will function normally

ActiveX controls work within iFIX in a secure environment

If the ActiveX control crashes it will not bring down iFIX

Copyright (c) 1999, Intellution, Inc.

13-6

*()DQXF

13.3.

ZZZML\LWHFKFRP


Student Guide

iFIX ActiveX Controls ____________________________________

Figure 13-3: iFIX Controls Example

Copyright (c) 1999, Intellution, Inc.

13-7

*()DQXF

13.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA and ActiveX Controls ________________________________

A. ActiveX controls

ActiveX controls have their own methods, properties and events and are available
immediately as the control is added

Most ActiveX controls have their own exposed property set

ActiveX controls include a custom property dialog and the ability to use the
property window as well
-

Some containers can only show the custom property dialog and do not
include the ability to use property window

The custom property dialog can be accessed from the property window by
selecting the filed Custom and the dialog will appear

VBA can be used to manipulate the ActiveX controls properties, methods and
events

ActiveX controls can have their own object reference library that will be
referenced if Automation is used to work with the object

Figure 13-4: Property Dialog Box

Copyright (c) 1999, Intellution, Inc.

13-8

*()DQXF

13.4.

ZZZML\LWHFKFRP


Student Guide

VBA and ActiveX Controls ________________________________

Copyright (c) 1999, Intellution, Inc.

Figure 13-5: Property Window

13-9

*()DQXF

13.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA and ActiveX Controls ________________________________

B. Using ActiveX controls

Most of the time after installing ActiveX controls, the methods, properties and
events have to be browsed to determine how to use them

Example:

Suppose a gauge control is installed

The control may allow for the attachment of a source like a iFIX database
tag or only have a value property to be set

Also be aware that installing an ActiveX control does not necessarily mean it is
available for use
-

There may be a license issue

A message will appear if a license is required

Installing an ActiveX control into iFIX in most case will be successful but there is
not a total guarantee

Whoever wrote the code may not have done the best job in coding

iFIX tries to protect against this by securing the ActiveX control in a


secure wrapper

this prevents a bad control from affecting other objects in the


picture

Copyright (c) 1999, Intellution, Inc.

13-10

*()DQXF

13.4.

ZZZML\LWHFKFRP


Student Guide

VBA and ActiveX Controls ________________________________

Figure 13-6: Calendar ActiveX Control and Chart Object

Private Sub Calendar1_Click()


Dim sTime As String

Dim sStartTime As String


'Set sTime=to the current Time of the Chart
sTime = Trim(Right(Chart1.StartTime, 9))
'Set sStartTime to the selected Date from Calendar
sStartTime = Calendar1.Value
'Add the previous Time to the Date
sStartTime = sStartTime & " " & sTime
'Set the Start Time to the new Date + previous time
Chart1.StartTime = sStartTime
End Sub

Figure 13-7: Using Calendar ActiveX Control to Set the Chart Object

Copyright (c) 1999, Intellution, Inc.

13-11

*()DQXF

13.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

VBA and ActiveX Controls ________________________________

C. VBE also makes use of ActiveX controls

VBE forms toolbox contains ActiveX controls such as the listbox and the
combobox

The forms toolbox can be customized to add additional controls


-

Only ActiveX controls that will be used within forms should be added

To add new controls:


-

Right Mouse Click on the Controls tab title in toolbox

Select New Page

Rename the new page and add page tips

Add any controls that exist in a form already by dragging them from the
form onto the new page

Add new controls by selecting the new page, then RMC and select
additional controls, then select from available list

Copyright (c) 1999, Intellution, Inc.

13-12

*()DQXF

13.4.

ZZZML\LWHFKFRP


Student Guide

VBA and ActiveX Controls ________________________________

Figure 13-8: VBE Form ActiveX Controls

Figure 13-9: Adding Additional ActiveX Controls to VBE Forms

Copyright (c) 1999, Intellution, Inc.

13-13

*()DQXF

13.5.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Installing ActiveX Controls _______________________________

A. Installing ActiveX controls can be done a number of ways

From an executable file

Self installable off the Web or other source

Using the Install Shield program

Manually installing the files and registering the control

Note the NT Registry needs to be updated anytime an ActiveX controls is added


to the host application
-

Normally this is done automatically when control is installed

The ActiveX control information is in the NT registry


MyComputer\HKEY_CLASSES_ROOT\Amovie.ActiveMovieControl

B. Installing ActiveX controls into iFIX WorkSpace

Controls are installed from WorkSpace configure mode

From the menu Insert select Insert OLE objects

Select from list or select Add Control

Note that some controls on the list may require a license

Copyright (c) 1999, Intellution, Inc.

13-14

*()DQXF

13.5.

ZZZML\LWHFKFRP


Student Guide

Installing ActiveX Controls _______________________________

Figure 13-10: Installing into WorkSpace

Figure 13-11: NT Registry

Copyright (c) 1999, Intellution, Inc.

13-15

*()DQXF

13.6.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

OLE ___________________________________________________

A. OLE provides the ability to do behind the scenes data exchange and manipulation of
other programs

OLE

OLE is a true method of integration in solving programming issues

OLE is a Microsoft technology standard

Object Linking and Embedding

offers the ability to expose the object model used in other applications

manipulating those objects is called OLE Automation and is similar to


manipulating objects in a client application

offers ability to work with objects that are supported by other applications

Inserting Excel chart or spreadsheet into iFIX Workspace

OLE objects are now called ActiveX objects

B. OLE concepts include Objects, Servers, and Clients

Objects are data, text, graphics, sounds, spreadsheets, almost anything plus
functions used to create, access and use the data

Server application is the application used to create and edit an object

Client application is the application that is used to store, link or embed object

i.e. the container application

C. Compound Documents are part of the OLE technology

Compound documents are documents that contain there own data plus an object
or objects created by other applications
-

Excel chart or spreadsheet in the iFIX Workspace

Word documents with sound or movie object

Note that the compound document can have completely different


data formats than the Clients native formats

The Client application does not have to know anything about the
data format.

The client only needs to know the name of the server that created
the data and how to display it

This information is supplied by the server app

Either linking or embedding can be used in creating a compound document

Copyright (c) 1999, Intellution, Inc.

13-16

*()DQXF

13.6.

ZZZML\LWHFKFRP


Student Guide

OLE ___________________________________________________

D. Object Linking

Linking is one method to insert an object into a file from a client application

Linking consists of the compound document and the source document

Compound document has link pointer to source file

Source file resides in a separate file and can be edited by the server or client

If source file is moved to another file location the link is broken

Linking allows client application to check the source for changes


-

The link updates the object automatically

If the client application is running and the compound document is


open

If the compound document is not open it updates when opened

Updating automatically can be disabled

Editing the compound document in the client is as easy as double clicking on the
object and the server loads the source file

E. Object Embedding

Embedding solves the issue of having a compound document and a separate


linked source document

Embedding inserts the object and the data along with registry information and
metafile information so everything is there to display and work with the object

Metafile contains GDI instructions on how to display the data

Registry key is used to invoke the server application

Embedding allows the creation of server objects in the client


-

Clicking on an embedded Excel object in iFIX Workspace brings up the


tools needed to create or edit the object

Note some applications are server only and cannot create objects

Copyright (c) 1999, Intellution, Inc.

13-17

*()DQXF

13.7.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Linking vs. Embedding___________________________________

A. Notes on Object Linking

Linking helps to keep the size of the compound document small

Linking works well if the source document does not move


-

Link can be reestablished by correcting path information to source

Linking allows for one file to maintain if changes are needed

Linking allows as many clients to have pointers to the source as needed

Linking allows the user to swap to different source file

B. Notes on Object Embedding

Embedding will be used if compound documents need to be emailed as one entity

Embedding means a separate source file is not needed

Embedding is self contained in the compound document and can be easily


distributed
-

The recipient client must have the server application installed to view the
compound document

Embedding compound documents uses more disk space

Copyright (c) 1999, Intellution, Inc.

13-18

*()DQXF

13.8.

ZZZML\LWHFKFRP


Student Guide

Summary Questions _____________________________________

1. iFIX provides you with a Chart Object, an Alarm Summary Object, a Variable Object, a
Timer Object and an Event Object. Which of these Objects are ActiveX controls?

2. What do OLE, COM, and DCOM stand for? Are all three basically the same
technology?

3. What are ActiveX controls?

4. Clearly all ActiveX controls are objects. They are pre-packaged pieces of functionality,
which expose their properties, methods, and events to our component architecture in the
form of OLE automation interfaces. So if all ActiveX controls are objects, are all the
objects we use in the iFIX WorkSpace ActiveX controls?

5. What is the total distance between the earth and the sun? What planet almost lost its
status as a planet if the definition rules were followed?

Copyright (c) 1999, Intellution, Inc.

13-19

*()DQXF

13.8.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Summary Questions _____________________________________

this page intentionally contains no data

Copyright (c) 1999, Intellution, Inc.

13-20

*()DQXF

14.

ZZZML\LWHFKFRP


Student Guide

Accessing Relational Databases ____________________________

Chapter 14
Accessing Relational Databases

Copyright (c) 1999, Intellution, Inc.

14-1

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

14. Accessing Relational Databases _____________________________


Section Objectives
This section provides an overview of various ways to access SQL databases. The section will
include the following topics:

Data Access Objects (DAO)

Remote Access Objects (RDO)

ActiveX Data Objects (ADO)

Copyright (c) 1999, Intellution, Inc.

14-2

*()DQXF

14.1.

ZZZML\LWHFKFRP


Student Guide

Overview_______________________________________________

A. Database Access in VBA

Microsoft provides developers with three database access models:


-

the Data Access Object model (DAO)

the Remote Data Object model (RDO)

the ActiveX Data Object model (ADO)

B. Data Access Object (DAO)

Originally, Microsoft developed the DAO model


-

this was originally designed to connect to Microsoft Access

Microsoft later extended DAO to use ODBCDirect


-

this allowed DAO to connect to other databases

such as Oracle and SQL Server

DAO is widely-used and is familiar to many Visual Basic programmers

Drawbacks to DAO
-

it lacks many of the high-end features of the other methods

DAO also relies on the Jet Database Engine

such as events

this is not the fastest way to get data from a database such as
Oracle

DAO is only licensed for development on machines that have either


Visual Basic (32-bit versions) or Microsoft Access 97 installed

Copyright (c) 1999, Intellution, Inc.

since VBA is not compiled code, VBA scripts written using DAO
will not run on machines without one of these programs installed

14-3

*()DQXF

14.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Overview_______________________________________________

C. Remote Data Object (RDO)

After DAO, Microsoft developed the RDO model

RDO has a similar object model to DAO, but adds features such as asynchronous
processing and events

RDO is designed to communicate well with back-end relational databases


-

such as SQL Server and Oracle

RDO introduced asynchronous database access to VB programmers and exposes


several events in its objects for asynchronous programming

RDO is faster than DAO, but adds complexity

Drawbacks:
-

RDO has the same limitations as DAO in terms of distributing code

It is only available with Visual Basic Enterprise Edition

it requires a copy of Visual Basic Enterprise Edition be installed on


all iFIX nodes that need to run RDO VBA code

Copyright (c) 1999, Intellution, Inc.

14-4

*()DQXF

14.1.

ZZZML\LWHFKFRP


Student Guide

Overview_______________________________________________

D. ActiveX Data Object (ADO)

Most recently, Microsoft developed the ADO model

ADO is built on OLE DB and is part of Microsoft's Universal Data Access


strategy

Microsoft designed ADO in an effort to combine the best features of DAO and
RDO
-

Microsoft has publicly stated that ADO will eventually replace these older
methods

ADO can access more types of data than DAO or RDO

ADO can use ODBC (Open DataBase Connectivity) to access data

The ADO architecture is built on OLE DB Providers

OLE DB Providers can be written for any data, from a legacy mainframe
database to an .INI file

ADO flattens the complex RDO (or DAO) object model and provides the
same, or more, functionality with fewer, more powerful objects

ADO is built into Visual Basic 6.0, but is also currently available as a separate
download from Microsoft's website

It is legal to install and use ADO on all iFIX nodes without purchasing
extra software

Intellution recommends that ADO is used for all iFIX VBA scripts that deal with
database access

Copyright (c) 1999, Intellution, Inc.

14-5

*()DQXF

14.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Data Access Objects (DAO) _______________________________

A. Overview

DAO is an object-based data access interface that provides access to SQL data
sources through VBA

Using DAO, you can:


-

Retrieve, add, change, or delete data in a database

Create a new database or change the design of an existing database

Implement security to protect data

B. Microsoft DAO object library

To use DAO within iFIX, a reference to the Microsoft DAO object library must
be set

To set the reference to the Microsoft DAO object library:


1

2 From the Tools menu, select References


3

Open the Visual Basic Editor (VBE)

Select the Microsoft DAO Object 3.5 Library check box

Note:

Microsoft DAO 3.5 no longer supports some of the objects, properties, and
methods that were supported in earlier versions of Microsoft DAO

If necessary, set a reference to the Microsoft DAO 2.5/3.0 Compatibility


Library, the Microsoft DAO 2.5/3.5 Compatibility Library, or the
Microsoft DAO 3.0 Object Library from the VBE

C. Viewing DAO Objects

Once you have set a reference to the Microsoft DAO object library, you can view
the DAO objects in the Object Browser
-

this is done by selecting DAO in the Project/Library box

DAO supports two technologies for accessing SQL data sources:


-

Microsoft Joint Engine Technology (Jet)

ODBCDirect

The DAO technology used depends on the type of operation needed to be


performed
-

see Figure 14-1 for an illustration of how DAO uses Jet and ODBCDirect
to access a SQL data source

Copyright (c) 1999, Intellution, Inc.

14-6

*()DQXF

14.2.

ZZZML\LWHFKFRP


Student Guide

Data Access Objects (DAO) _______________________________

Figure 14-1: Accessing SQL Data Sources with DAO Jet versus DAO ODBCDirect

Copyright (c) 1999, Intellution, Inc.

14-7

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

14.2.1. Joint Engine Technology (Jet) ___________________________


A. Notes

Jet was designed primarily to access native Jet/Access (.MDB) databases and
selected ISAM databases
-

ISAM database include dBase, Paradox, FoxPro, and Btrieve

B. The following is a list of exclusive Jet capabilities not offered by ODBCDirect.

Linking remote tables for form and control binding


-

Heterogeneous data access


-

allows you to join data stored in different back ends

Programmatic DDL
-

allows forms or controls to be bound to data in an ODBC data source

provides table definitions and the ability to create or modify tables using
Data Definition Language (DDL)

Support for Find and Seek methods


-

permits the use of the Find and Seek methods

C. Jet Disadvantages

Although Jet is capable of accessing ODBC data sources, this functionality is


limited and, compared to ODBCDirect, has two major disadvantages
-

Jet loads the Microsoft Jet database engine even when it is not a Jet
database being accessed

Since calls must be passed through the Jet database engine before reaching
the ODBC API, Jet is slower than ODBCDirect

Copyright (c) 1999, Intellution, Inc.

14-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

14.2.2. ODBCDirect ___________________________________________


A. Notes

ODBCDirect provides more direct access to ODBC data sources by way of


bypassing the Jet engine

ODBCDirect is a thin DAO wrapper around the RDO interface


-

this means it routes DAO objects, methods, and properties to equivalent


RDO functions

B. The following is a list of ODBCDirect advantages not provides by Jet.

Direct data access


-

Reduced resource requirements


-

eliminates the resources required by Jet to load the Jet database engine

Asynchronous queries
-

allows direct access to ODBC data resources

optimizes performance by allowing alternative functions to perform while


an operation completes

Local batch processing

caches Recordset changes locally and submits the changes to the server in
a single batch

Copyright (c) 1999, Intellution, Inc.

14-9

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

14.2.3. Example Using DAO ____________________________________


A. Example

The following example queries a relational database using DAO and displays the
database information in a picture

Private Sub cmdQueryDowntimeRDB_Cl ick()


'Create the WorkSpace application.
Dim wrkSpace As Workspace
Set wrkSpace = CreateWorkspace("", "admin", "", dbUseJet)
'Open the database.
Dim db As Database
Set db = wrkSpace.OpenDatabase(System.PicturePath & "\downtime.mdb")

'Create a recordset.
Dim rs As Recordset
Set rs = db.OpenRecordset("Packaging", dbOpenDynaset)

'Move to the beginning of the table.


If rs.EOF = True Then
MsgBox "The Database does not have any records"
Exit Sub
End If
rs.MoveLast
Rows = rs.RecordCount + 1
rs.MoveFirst

'Set up display information.


DownTimeGrid.Rows = Rows
DownTimeGrid.Cols = 5
DownTimeGrid.Row = 0
DownTimeGrid.Col = 0
DownTimeGrid.Text = "Time In"
DownTimeGrid.Col = 1
DownTimeGrid.Text = "Date In"
DownTimeGrid.ColWidth(1) = 2000

Figure 14-2: Sample Code using DAO

Copyright (c) 1999, Intellution, Inc.

14-10

*()DQXF

ZZZML\LWHFKFRP


Student Guide

14.2.3. Example Using DAO ____________________________________

DownTimeGrid.Col = 2
DownTimeGrid.Text = "Data Source"
DownTimeGrid.ColWidth(2) = 4500
DownTimeGrid.Col = 3
DownTimeGrid.Text = "Description"
DownTimeGrid.ColWidth(3) = 5500
DownTimeGrid.Col = 4
DownTimeGrid.Text = "Period"
'Loop through the data and display it.
Dim r As Integer
Dim c As Integer
r = 1
While rs.EOF <> True
DownTimeGrid.Row = r
For c = 0 To 4
DownTimeGrid.Col = c
If rs.Fields(c + 1) <> "" Then
DownTimeGrid.Text = rs.Fields(c + 1)
End If
If c = 0 Then
'This formats the time from ACCESS.
DownTimeGrid.Text = Format(rs.Fields (c + 1), "h:mm:ss AM/PM")
End If
If c = 1 Then
'This formats the date from ACCESS.
DownTimeGrid.Text = Format(rs.Fields (c + 1), " dddd, mmmm, yyyy")
End If
Next c
r = r + 1
rs.MoveNext
Wend
Set rs = Nothing
Set db = Nothing
Set wrkSpace = Nothing
End Sub

Figure 14-2: Sample Code using DAO (continued)

Copyright (c) 1999, Intellution, Inc.

14-11

*()DQXF

14.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

ActiveX Data Objects (ADO)_______________________________

A. Using ActiveX Data Objects (ADO)

ADO is a free download from Microsoft's web site


-

there is no need to buy another product to use ADO

DAO requires Office97

RDO requires Visual Basic Enterprise Edition

Currently, Microsoft is encouraging VBA developers to use ADO over the


other types of data access

The key elements covered in this section include:


-

Creating ADO objects

Populating a MSFlexGrid from a Select statement

Adding a record to the database

Updating a record in the database

Deleting a record from the database

B. Creating ADO Objects

The first step is to reference the ActiveX Data Objects Library in a picture's
project

Do this by selecting the References command from the VBE Tools menu and then
selecting the ADO type library

The object variables are declared at the Module level, which means that
they are available in all of the other routines in this example

If the records dont need to be manipulated, then they can be declared at


the Procedure level

See Figure 14-3 for an example

Copyright (c) 1999, Intellution, Inc.

14-12

*()DQXF

14.3.

ZZZML\LWHFKFRP


Student Guide

ActiveX Data Objects (ADO)_______________________________

'General Declarations
'This stores the link to the database.
Dim conODBC As ADODB.Connection
'This stores the results of the query.
Dim adoRS As ADODB.Recordset

Private Sub InitADO()


Dim strQuery As String
On Error GoTo ErrorHandler
'SQL query that ADO will run.
strQuery = "SELECT Recipe_ID, Recipe_Name, Batch_Size, " + _
"Milk_Quan , Choc_Quan, Mix_Time, _
Milk_Type FROM ACCEPT_TEST ORDER BY Recipe_Name ASC"

'Create ADO Connection Object.


Set conODBC = New ADODB.Connection

'Connect to the database. Connect string can be DSN-less.


'This varies by database type.
conODBC.Open "driver= _
{SQL server};server=thunder;uid=sa;pwd=;database=master"
'Create ADO Recordset Object.
Set adoRS = New ADODB.Recordset
'Run query, and allow read/write access.
adoRS.Open strQuery, conODBC, adOpenDynamic, _
adLockPessimistic, adCmdText
Exit Sub
ErrorHandler:
HandleError

End Sub

Figure 14-3: Sample Code Creating ADO Objects

Copyright (c) 1999, Intellution, Inc.

14-13

*()DQXF

14.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

ActiveX Data Objects (ADO)_______________________________

C. Populating a MSFlexgrid or Similar Spreadsheet OCX with ADO

To get the data out of the recordset for display, a spreadsheet or grid is handy

Figure 14-4 shows how to copy the data into the grid

Private Sub InitGrid()


'This routine adds column titles to grid
'and sets column widths.
MSFlexGrid1.Clear
MSFlexGrid1.TextArray(faIndex(0, 0)) = "Recipe ID"
MSFlexGrid1.TextArray(faIndex(0, 1)) = "Recipe Name"

MSFlexGrid1.TextArray(faIndex(0, 2)) = "Batch Size"

MSFlexGrid1.TextArray(faIndex(0, 3)) = "Milk Amount"

MSFlexGrid1.TextArray(faIndex(0, 4)) = "Chocolate Amount"


MSFlexGrid1.TextArray(faIndex(0, 5)) = "Mix Time"

MSFlexGrid1.ColWidth(0) = 1150
MSFlexGrid1.ColWidth(1) = 4000
MSFlexGrid1.ColWidth(2) = 1250
MSFlexGrid1.ColWidth(3) = 1450
MSFlexGrid1.ColWidth(4) = 2050
MSFlexGrid1.ColWidth(5) = 1150

RecipeID.Value = ""
RecipeName.Value = ""
BatchSize.Value = ""
MilkQuan.Value = ""
ChocQuan.Value = ""
MixTime.Value = ""
End Sub

Figure 14-4: Sample Code Populating a MSFlexgrid

Copyright (c) 1999, Intellution, Inc.

14-14

*()DQXF

14.3.

ZZZML\LWHFKFRP


Student Guide

ActiveX Data Objects (ADO)_______________________________

Private Sub
Dim iRow
Dim iCol
On Error

LoadRecipes()
As Integer
As Integer
GoTo ErrorHandler

'Set MSFlexGrid column sizes and titles.


InitGrid
iRow = 0
'Read though the entire record to populate the grid.
While adoRS.EOF <> True
iRow = iRow + 1
MSFlexGrid1.Row = iRow
For iCol = 0 To 5
MSFlexGrid1.Col = iCol
MSFlexGrid1.Text = adoRS(iCol)

'After setting the row a nd column of the grid,


'insert data into the cell.

Next iCol

'Move to the next record returned from the query.


adoRS.MoveNext

Wend
'The row number will show the number of records returned.
RecipeCount.Value = Str(iRow)
Exit Sub
ErrorHandler:
HandleError
End Sub

Figure 14-4: Sample Code Populating a MSFlexgrid (continued)

Copyright (c) 1999, Intellution, Inc.

14-15

*()DQXF

14.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

ActiveX Data Objects (ADO)_______________________________

D. Adding a Record to the Database Through ADO

If the recordset is not opened as read-only, records can be added to the database
through ADO

See Figure 14-5

Private Sub AddRecipe()


Dim lIndex As Long
On Error GoTo ErrorHandler
If RecipeName.Value = "" Then
MsgBox "Please Enter Recipe Parameters First", _
vbExclamation, "Recipe Control"

Exit Sub
End If
adoRS.AddNew 'Adds a new record to the recordset.

'Populate the record with data.


adoRS!Batch_Size = CLng(BatchSize.Value)
adoRS!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
adoRS.Update 'Commits the new record to the database.
adoRS.Requery 'Refreshes the recordset.
LoadRecipes 'Populates the grid.
Exit Sub

ErrorHandler:
'Handle the error returned if any columns need
'to be unique (such as recipe name) but weren't.
If Err.Number = -2147217887 Then
MsgBox "Recipe Names Must be Unique", _
vbExclamation, "RecipeControl"
Exit Sub
End If
HandleError
End Sub

Figure 14-5: Sample Code Adding a Record to the Database

Copyright (c) 1999, Intellution, Inc.

14-16

*()DQXF

14.3.

ZZZML\LWHFKFRP


Student Guide

ActiveX Data Objects (ADO)_______________________________

E. Updating a Record in the Database Through ADO

If the recordset is not read-only, values in a record can be changed and written to
with ADO

See Figure 14-6

Private Sub UpdateRecipe()


On Error GoTo ErrorHandler
'Check for primary key setting before update.
If RecipeID.Value = "" Then
MsgBox "Please Select a Recipe First", _
vbExclamation, "Recipe Control"
Exit Sub
End If
adoRS.Requery 'Refresh the recordset.
While adoRS!Recipe_ID <> CLng(RecipeID.Value)
'Move to the selected record to be updated.
adoRS.MoveNext
Wend

'Set any changed values.


adoRS!Batch_Size = CLng(BatchSize.Value)
adoRS!Milk_Quan = CLng(MilkQuan.Value)
adoRS!Choc_Quan = CLng(ChocQuan.Value)
adoRS!Mix_Time = CLng(MixTime.Value)
adoRS.Update 'Commits the updated record to the database.
adoRS.Requery 'Refreshes the recordset.
LoadRecipes 'Populates the grid.
Exit Sub
ErrorHandler:
HandleError

End Sub

Figure 14-6: Sample Code Updating a Record in the Database

Copyright (c) 1999, Intellution, Inc.

14-17

*()DQXF

14.3.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

ActiveX Data Objects (ADO)_______________________________

F. Deleting a Record from the Database Through ADO

If the recordset is not read-only, records in the database can be deleted with ADO

See Figure 14-7

Private Sub DeleteRecipe()


On Error GoTo ErrorHandler
'Check for primary key setting before delete.
If RecipeID.Value = "" Then
MsgBox "Please Select a Recipe First", _
vbExclamation, "Recipe Control"
Exit Sub
End If
adoRS.Requery 'Refresh the recordset.
While adoRS!Recipe_ID <> CLng(RecipeID.Value)
'Move to the selected record to be upda ted.
adoRS.MoveNext
Wend
adoRS.Delete 'Delete current record in recordset.
adoRS.Update 'Commit deleted record to database.
adoRS.Requery 'Refresh recordset.
LoadRecipes 'Populate grid.
Exit Sub

ErrorHandler:
HandleError
End Sub

Figure 14-7: Sample Code Deleting a Record in the Database

Copyright (c) 1999, Intellution, Inc.

14-18

*()DQXF

ZZZML\LWHFKFRP

Intellut on



354 Course Appraisal Sheet

Name (optional): ________________________

Date: _______________________________

Instructor: ______________________________

Class Location: _______________________

Please indicate your level of interest in these aspects of using VBA with iFIX:
Low
High
Why?
Using Forms
    
______________________________________
Collections and Groups
    
______________________________________
Accessing the PDB
    
______________________________________
Error Handling
    
______________________________________
Debugging
    
______________________________________
Of all course topics, which were of the most value? _____________________________________
Which were of the least value? _____________________________________________________

Comments: ____________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Totally
Unfamiliar

Please rate your competence with VBA before class.

Completely
Competent

    

How would you now rate your competence with VBA?

    

Please comment on your instructors:


Ability to answer course-related questions
Ability to make material easy to understand
Style and attitude - did they contribute to your learning

Poor

OK

Superior

    
    
    

Comments: ____________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
Poor

Please rate the quality of class facilities (room, PCs, etc.)

OK

Superior

    

Give Details: ___________________________________________________________________


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

*()DQXF

ZZZML\LWHFKFRP



Additional Comments:

*()DQXF

ZZZML\LWHFKFRP


Student Guide

A. Glossary _________________________________________________

Appendix A
Glossary

Copyright (c) 1999, Intellution, Inc.

A-1

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

A. Glossary _________________________________________________

ActiveX - Microsoft's brand name for the technologies that enable interoperability using the
Component Object Model (COM).
ActiveX Component - Physical file (for example, .exe, .dll, .ocx) that contains classes, which
are definitions of objects.
ActiveX Control - An object that you place on a form to enable or enhance a user's
interaction with an application. These controls have an .ocx file name extension
ActiveX Document - An application that can be viewed in another.
Alarm Destination - An enabled service on a node where alarms are routed. Alarm
destinations include Alarm Printers, the Alarm File Service, the Alarm Summary
Service, and the Alarm Network Service.
Alarm Priority - The relative severity of an alarm. You can assign a priority of Low,
Medium, or High to alarms.

Alarm Queue - Reserved memory that holds incoming alarm messages until an alarm service
can process them. The size of the queue determines how many alarms can be stored.
If the queue overflows, the oldest unprocessed alarms are discarded.

Alarming - The process by which blocks receive process data, compare the data against predefined alarm limits, and react to those process values that exceed these limits.

Alarms Path - Stores alarm data files and security log files. By default, the alarms path is set
to C:\DYNAMICS\ALM.

Application Feature - An account privilege that allows an operator access to specific


application functions. For example, the WorkSpace Runtime application feature
enables an operator to access the WorkSpace run-time environment.
Application Message - Message generated by operator actions or iFIX applications that
include operator messages and recipe messages.
Application Path - Stores data and configuration files for iFIX applications. By default, the
application path is set to C:\DYNAMICS\APP.

Copyright (c) 1999, Intellution, Inc.

A-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

A. Glossary _________________________________________________

Application User - An operator you want automatically logged into iFIX. Once logged in,
operators have access to the privileges assigned to the specified user account.
Automatic Mode - A database tag mode in which the tag is scanned by the Scan, Alarm, and
Control (SAC) program. In this mode, the tag accepts data only from the poll table or
other tags.
Base Path - Stores all iFIX executable files. By default, this path is set to C:\DYNAMICS.
Block - Individual unit of instructions capable of receiving, checking, manipulating, and
outputting process values. A block can also compare a process value against an alarm
limit and perform calculations based on a specific process value.
Block Field - A location in a block that holds process data. Blocks have many fields such as
their current value, name, scan time, EGU range, alarm limits, alarm areas, and
security areas.

Block Type - Blocks are organized into types based upon similar function. Blocks capable of
performing batch functions are of the batch type; blocks capable of performing
statistical calculations are of the statistical type, and so forth. The types of blocks
available to your system is dependent upon the options you purchased with iFIX.

Chain - Two or more blocks connected to each other. Your goal in creating a database is to
chain blocks in a sequence so that each block performs a specific task and then passes
its information on to one or more appropriate blocks.

Collection Group - A set of tagnames for a selected node that identifies the database blocks
that contain process data required for trending. You can define up to 64 collection
groups with 80 different tags in each collection group. The Historical Assign program
stores collection groups in the historical data path in the following format:
HTRGRP##.DAT, where ## represents the number of the group (01-64).

Copyright (c) 1999, Intellution, Inc.

A-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

A. Glossary _________________________________________________

Color Threshold - Either a color and value combination (Color by Value) or a color and
alarm state combination (Color by Alarm or Color by Latched Alarm). For a value
threshold, you specify the upper limit of the range of values that correspond to a color.
When the value of the target database field is less than or equal to the threshold, but
greater than all lower thresholds, the foreground, edge, or background color of the
object changes to the defined color. For an alarm threshold, you specify the color that
correspond to an alarm state. When the target database tag is in an alarm state, the
object changes to the defined color.
COM - Component Object Model
Cross-Hair Cursor - The cross-hair cursor creates rectangles, ovals, lines, polygons, and
polylines.
Data Collection Rate - Defines how often the Historical Collect program accumulates values
for the tagnames selected in a collection group.

Data Source - A reference to a source of information, such as iFIX tagnames and historical
files, or other OPC-compliant data servers. Additionally, a data source may consist of
iFIX objects (such as shapes, charts, and variables) or 3rd party OLE controls.

Database Path - Stores process database files, Database Builder configuration files, and I/O
driver configuration files. By default, this path is set to C:\DYNAMICS\PDB.

DCOM - Distributed Component Object Model


Deadband Limit - A convenient and powerful way to compress data. It determines by how
much the current collection value must deviate from the last recorded value for the
system to record the value in the historical data file. For example, if the deadband
limit is set to 0.5 (the default) and the first recorded value is 50, the next value
recorded by Historical Collect must be greater than or equal to 50.5 or less than or
equal to 49.5. During times when process values are changing by insignificant
amounts, a deadband limit can improve system performance and decrease the amount
of disk space used by historical data files.

Copyright (c) 1999, Intellution, Inc.

A-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

A. Glossary _________________________________________________

Dynamo - A reusable graphic, stored in a set, that contains object properties. When you
paste a Dynamo into a picture, you are prompted to enter the appropriate property
values for the current picture. In addition to the standard iFIX Dynamos, you can
convert custom-built objects, links, and application scripts, such as pumps, valves, and
charts into Dynamos.
Easy Database Access (EDA) - A library of subroutines that provides easy access to iFIX
data. EDA handles the details of memory management, error detection and recovery,
networking, and so forth.
EGU Range - The maximum and minimum process values the process hardware can measure.
Events - Actions that an object recognizes, such as when a user clicks the mouse on the
object or changes its size If a script is associated with an event, the script executes
when the event triggers or occurs. Events can occur as a result of user action,
program code, or other occurrences in iFIX

Executable - The name of the file that runs a iFIX or a third party application. For example,
RECIPE.EXE or EXCEL.EXE.
The executable file name must include path
information. A string variable can replace this parameter.

Exception-Based Processing - Instructions that tell the Scan, Alarm, and Control (SAC)
program to process blocks by exception rather than a scheduled time interval. The
Analog Input, Analog Alarm, Digital Input, and Digital Alarm blocks can use this
processing method:

Expression - Constants, data sources, or a combination of constants and data sources


connected with one or more operators. Using the Expression Builder, you can create
specific expressions that access data from unique sources. This gives you more
flexibility when assigning dynamic object properties.
Fast Path - Reserved for future use.
C:\DYNAMICS\FAST.

By default, the fast path is set to

Font - A text design. The characters in a text object all have a common design.

Copyright (c) 1999, Intellution, Inc.

A-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

A. Glossary _________________________________________________

Grid - The grid is a tool for helping you lay out and align objects in a picture. When you
enable the grid, evenly spaced dots appear on your screen. These dots represent the
intersection of invisible guidelines.
Group Account - A group account defines the application features and security areas for
multiple users. By creating group accounts, you define the account privileges most
commonly needed for two or more people.
Group Membership - Group membership defines the group account(s) that a user is assigned
to in a user account. Once assigned to a group account, a user may have access to all
the application features and security areas defined for the group.
Grouped Objects - A set of objects that has been joined together with the Group command.
Once you group objects into one single object, you can manipulate the group like any
other object. You can move, cut, paste, copy, stretch, and assign animations to a
group, using the same methods used for individual objects.

Handles - Small squares located on the corners and sides of an object that you have selected
with the mouse. Handles allow you to resize an object horizontally, vertically, or both
ways at the same time by dragging the appropriate handle. An object with solid
handles has animations. An object with hollow handles does not have dynamic
properties.

Historical Data Path - Stores historical data files from which the Historical Collect
application creates a unique subdirectory in this directory for each node data is being
collected, and names the subdirectory according to the name of the node. By default,
the historical data path is set to C:\DYNAMICS\HTRDATA.
Historical Path - Stores the configuration files of Historical Assign and Historical Collect.
By default, the historical path is set to C:\DYNAMICS\HTR
I-Beam Cursor - Marks the start of a new text object or places the insertion cursor within an
existing text object.

Copyright (c) 1999, Intellution, Inc.

A-6

*()DQXF

ZZZML\LWHFKFRP


Student Guide

A. Glossary _________________________________________________

Language Path - Stores the language files used to create dialog boxes and help files. If you
choose to implement a native language other than English, the new language and help
files replace the files found in this directory. By default, this path is set to
C:\DYNAMICS\NLS.
Line Style Marker - A line style marker, defined in the Line Style dialog box, displays on the
trend line and is used to distinguish between overlapping trend lines or when printing
in black and white. Historical data pens must either use a line style marker or show a
trend line, or both.
Links - Real-time connections to data points in the process database that are used to display
or process information.
Literal Pattern - A literal pattern generates a literal string of text for a block field. Literal
patterns can contain up to 255 characters and do not require quotation marks. For
example, you can enter alarms, elapsed time, and analog input from tank A as literal
patterns.

Local Node - The node at which you are physically located.

Local Path - Stores configuration files associated with the local computer, including the SCU
and Security application files. By default, this path is set to C:\Dynamics\LOCAL.

Logical Node Name - The name configured in a View node's and blind SCADA's SCU that
represents a primary and backup SCADA pair.

Manual Mode - A database tag mode in which operators can manually change the value of a
tag through links in the WorkSpace.
Master Recipe Path - Stores master recipe, master recipe error, and master recipe report
files for the Recipe application. By default, this path is set to C:\DYNAMICS\RCM.
Methods VBA Subroutines that effect the behavior of object
NetBEUI - Microsoft's implementation of NetBIOS.
NetBIOS - An API specification, not an implementation, of a network programming
interface.

Copyright (c) 1999, Intellution, Inc.

A-7

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

A. Glossary _________________________________________________

Network Path - A network path is made up of a protocol and LAN card or modem. For
example: NetBEUI over one LAN card, NetBEUI over a RAS "card", or TCP/IP
over one LAN card.
Objects - Comprised of data and procedures that are treated as a unit. Each object has its
own properties, methods, and events that can be used to write scripts
Off Scan Status - A tag with an off scan status is not processed by the Scan, Alarm, and
Control (SAC) program. When a tag is off scan, its associated database chain is also
off scan.
OLE - Object Linking and Embedding
On Scan Status - A tag with an on scan status is being processed by the Scan, Alarm, and
Control (SAC) program every scan cycle. When a tag is on scan, its associated
database chain is also on scan.

One Shot Processing - One shot processing instructs the Scan, Alarm, and Control (SAC)
program to process a block once. This processing method is similar to exceptionbased processing, except that the block will not trigger again unless SAC is restarted,
the database is reloaded, or the block is turned off scan and then turned back on scan.
Any block with a scan time can be configured for one shot processing.

Operator Message - A broadcast of information generated whenever an operator uses a


mouse, keyboard, or touch screen to input to a iFIX application.

Order of Solve - The order in which SAC scans database blocks.


Pen - A pen represents a floating point value or tag that is displayed in a chart link.
Picture Path - Stores picture files, Dynamo files, tag group files, macro files, block status
display files, and WorkSpace configuration files. By default, the picture path is set to
C:\DYNAMICS\PIC.
Polygon - A polygon is a closed plane figure bounded by three or more line segments.
Polyline - A polyline is a line with many segments.

Copyright (c) 1999, Intellution, Inc.

A-8

*()DQXF

ZZZML\LWHFKFRP


Student Guide

A. Glossary _________________________________________________

Primary Block - A block that receives data from an I/O driver or OPC server and includes a
scan time. Primary blocks are usually associated with one or more pieces of I/O
hardware and are always the first block in a chain.
Process Database - A data file that holds all the data from your process hardware. It is the
primary source of data for most iFIX applications.
Property - Characteristics of an object
Query - A request to Database Manager to display one or more blocks from the database.
Remote Node - Any node on the network that is not the local node.
Resolve - Resolving is a method to optimize the speed at which pictures open in the run-time
environment. Database information for each tag in a picture is saved as part of the file
on disk. When a picture is displayed in the run-time environment, and the database
information is not up to date, the WorkSpace has to query the database and resolve
the tag definitions; a time consuming process. Resolving in the configuration
environment eliminates the need for the WorkSpace to query the database. The end
result is that the picture opens faster in the run-time environment.

SCADA Server - A SCADA (Supervisory, Control, And Data Acquisition) node is a


computer that loads a process database in memory and collects process information
from one or more control devices. A SCADA server can return process information
to the control devices to automate and control a process. All SCADA servers run the
Scan, Alarm, and Control (SAC) program in order to process the database.

Scan, Alarm, and Control (SAC) - A program that retrieves process information from an
I/O driver or OPC server. Using the data it receives, SAC updates blocks in the
database and process alarms. SAC also returns corrective values from the database to
a control device.
Scan Time - A user-defined interval at which the Scan, Alarm, and Control (SAC) program
processes a block and any blocks chained to it.

Copyright (c) 1999, Intellution, Inc.

A-9

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

A. Glossary _________________________________________________

SCU File - The SCU file contains information that the iFIX Startup program needs to
configure your node. When you run Startup, it reads the SCU file and uses the
information to run several system tasks. iFIX only uses the SCU file during startup, so
most changes you make to the file while the system is running will not take effect until
you stop and restart iFIX.
Secondary Block - A block that receives input from an upstream block and performs a
specific function with the input. For example, a secondary block can perform a
calculation or store several successive inputs.
Security Area - A physical or functional division of your process that allows you to restrict
access to schedules, recipes, operator displays, and write-protect database blocks.
Security areas can be process hardware (such as pumps or ovens) or utilities (such as
fuel, water, or steam), or maintenance functions. You can define up to 254 security
areas, which are identified by number. Associated with each number is a name of up
to 20 alphanumeric characters. By default, iFIX names the first 16 security areas A
through P.

The Simulation (SIM) Driver - A matrix of addresses where values are written to and read
from. If one block writes to a specific address, other blocks can read the same value
from the same address. SIM points are saved in the process database itself but are
cleared when SAC is started or when you reload the database. Refer to the Building a
SCADA System manual for more information.

Tagname - The information needed to access database data. A tagname consists of a node
name, database block (tag) name, and field name in this format: NODE:TAG.FIELD
User Account - Provides individual access to group accounts, security areas, and application
features. Each user account is identified by a full name, login name, optional password
and optional timeout specification. The Security Configuration program lets you
specify a user account to automatically log in an operator or you can have each user
log in manually with the Security Login program.

Copyright (c) 1999, Intellution, Inc.

A-10

*()DQXF

ZZZML\LWHFKFRP


Student Guide

B. File I/O ___________________________________________________

Appendix B
File I/O

Copyright (c) 1999, Intellution, Inc.

B-1

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

B.1. Opening a File ___________________________________________


A. Notes

VBA does not treat files as objects


-

use statements and functions to carry out file related actions

object methods are not used to perform file I/O

Each file opened in VBA is assigned a file number


-

this number is used throughout the code to reference the file

the filename is only used in the OPEN statement

To work with the contents of a file, the file must first be opened
-

there are exceptions to this rule

this will be covered later in the course

The Open statement enables input/output to a file

B. Syntax of the Open statement

Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

See Figure B-1 for details on the parts of the Open Statement

C. Important Note:

In Binary, Input, and Random modes, a file can be opened using a different file
number without first closing the file

In Append and Output modes, a file must be closed before opening it with a
different file number

D. Additional Notes

You must open a file before any I/O operation can be performed on it

Open allocates a buffer for I/O to the file and determines the mode of access to
use with the buffer

If the file specified by pathname doesn't exist, it is created when a file is opened for
Append, Binary, Output, or Random modes

If the file is already opened by another process and the specified type of access is
not allowed, the Open operation fails and an error occurs

The Len clause is ignored if mode is Binary

Copyright (c) 1999, Intellution, Inc.

B-2

*()DQXF

B.1.

ZZZML\LWHFKFRP


Student Guide

Opening a File __________________________________________

Part

Description

pathname

Required. String expression that specifies a file name - may


include directory or folder, and drive.

mode

Required. Keyword specifying the file mode: Append, Binary,


Input, Output, or Random. If unspecified, the file is opened for
Random access.

access

Optional. Keyword specifying the operations permitted on the


open file: Read, Write, or Read Write.

lock

Optional. Keyword specifying the operations permitted on the


open file by other processes: Shared, Lock Read, Lock Write, and
Lock Read Write.

filenumber

Required. A valid file number in the range 1 to 511, inclusive.


Use the FreeFile function to obtain the next available file number.

reclength

Optional. Number less than or equal to 32,767 (bytes). For files


opened for random access, this value is the record length. For
sequential files, this value is the number of characters buffered.

Figure B-1: Parts of the Open Statement

Mode

Description

Append

Used to write data to the end of a text or CSV file.

Binary

Used to read or write to any byte position in a file, such as storing


or displaying a bitmap image.

Input

Used to read data from a text or CSV file.

Output

Used to write data to a text or CSV file.

Random

Used to read and write data to a file without closing it. Random
access files keep data in records, which makes it easy to locate
information quickly.
Figure B-2: File Access Mode Descriptions

Copyright (c) 1999, Intellution, Inc.

B-3

*()DQXF

B.1.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Opening a File __________________________________________

E. Using the FreeFile Statement

Use FreeFile to supply a file number that is not already in use

It Returns an Integer representing the next file number available for use by the
Open statement

Syntax
myVar = FreeFile[(rangenumber)]
-

The optional rangenumber argument is a Variant that specifies the range


from which the next free file number is to be returned

specify a 0 (default) to return a file number in the range 1 255,


inclusive

specify a 1 to return a file number in the range 256 511

Use the integer variable in place of an actual value in the Open Statement
-

see Figure B-3 for examples

F. Closing a file

Concludes input/output to a file opened using the Open statement

Syntax

Close [filenumberlist]

The optional filenumberlist argument can be one or more file numbers


using the following syntax, where filenumber is any valid file number:
[[#]filenumber] [, [#]filenumber] . . .

Additional Notes
-

If the filenumberlist is omitted, all active files opened by the Open


statement are closed

When files are closed that were opened for Output or Append, the final
buffer of output is written to the operating system buffer for that file

all buffer space associated with the closed file is released

Copyright (c) 1999, Intellution, Inc.

B-4

*()DQXF

B.1.

ZZZML\LWHFKFRP


Student Guide

Opening a File __________________________________________

Open "TESTFILE" For Input As #1


' Close before reopening in another mode.
Close #1

Const FileNum = 2
Open "TESTFILE" For Binary Access Write As FileNum
' Close before reopening in another mode.
Close FileNum

Type Record
ID As Integer
Name As String * 20
End Type

' Define user-defined type.

Dim MyRecord As Record


' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
' Close before reopening in another mode.
Close #1

' This example uses the FreeFile function to open five files for
' output within the loop, and some sample data is written to each.
Dim MyIndex, FileNumber
For MyIndex = 1 To 5
' Loop 5 times.
FileNumber = FreeFile
' Get unused file number.
Open "TEST" & MyIndex For Append As #FileNumber
Write #FileNumber, "This is a sample."
' Output text.
Close #FileNumber
' Close file.
Next MyIndex

Figure B-3: Open Statement Examples

Copyright (c) 1999, Intellution, Inc.

B-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

B.2. Reading and Writing Data__________________________________


A. Commands to Read and Write Data.

Read Commands:
-

Get, Input, Input #

Write Commands
-

Put, Write #, Print #

B. Notes

As discussed, the Open statement lets you create and access files directly

Open provides three types of file access:


-

Sequential access (Input, Output, and Append modes) is used for writing
text files, such as error logs and reports

Random access (Random mode) is used to read and write data to a file
without closing it

Random access files keep data in records, which makes it easy to


locate information quickly

Binary access (Binary mode) is used to read or write to any byte position in
a file, such as storing or displaying a bitmap image

Figure B-4 shows the statements typically used when writing data to and reading
data from files

Access Type

Writing Data

Reading Data

Sequential

Print #, Write #

Input, Input #

Random

Put

Get

Binary

Put

Input, Get

Figure B-4: Reading and Writing to Files

Copyright (c) 1999, Intellution, Inc.

B-6

*()DQXF

B.2.1.

ZZZML\LWHFKFRP


Student Guide

Put Statement _________________________________________

A. Put Statement

Writes data from a variable to a disk file

Data written with Put is usually read from a file with Get

Syntax
Put [#]filenumber, [recnumber], varname
-

filenumber Required

recnumber Optional

Variant (Long). Record number (Random mode files) or byte


number (Binary mode files) at which writing begins

varname Required

any valid file number

Name of variable containing data to be written to disk

If recnumber is omitted, the next record or byte after the last Get or Put statement
is written

delimiting commas must be included

Dim strAlarm As String


strAlarm = Now & " Alarm Time Stamp"
Open "c:\dynamics\file1.txt" For Random As #1
Put #1, 5, strAlarm
Close #1

Figure B-5: Put Statement Example

Copyright (c) 1999, Intellution, Inc.

B-7

*()DQXF

B.2.2.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Get Statement _________________________________________

B. Get Statement

Reads data from an open disk file into a variable

Data read with Get is usually written to a file with Put

Syntax
Get [#]filenumber, [recnumber], varname
-

filenumber Required

recnumber Optional

Variant (Long). Record number (Random mode files) or byte


number (Binary mode files) at which reading begins

varname Required

any valid file number

Valid variable name into which data is read

If recnumber is omitted, the next record or byte following the last Get or Put
statement is read

delimiting commas must be included

Dim strAlarm As String


Open "c:\dynamics\file1.txt" For Random As #1
Get #1, , strAlarm
Debug.Print strAlarm
Close #1

Figure B-6: Get Statement Example

Copyright (c) 1999, Intellution, Inc.

B-8

*()DQXF

B.2.3.

ZZZML\LWHFKFRP


Student Guide

Input Statement ________________________________________

A. Input Statement

Returns String containing characters from a file opened in Input or Binary mode

Data read with the Input function is usually written to a file with Print # or Put
-

Use this function only with files opened in Input or Binary mode

Unlike Input #, the Input function returns all of the characters it reads, including
commas, carriage returns, linefeeds, quotation marks, and leading spaces

Syntax
Input(number, [#]filenumber)
-

number Required

any valid numeric expression specifying the number of characters to


return

filenumber Required

any valid file number

' this example assumes that the file has a few lines of
' data. The Input function to read one character at a
' time from a file and print it to the Debug w indow
Dim MyChar
Open "c:\dynamics\file1.txt" For Input As #1
Do While Not EOF(1)
' Loop until end of file.
MyChar = Input(1, #1)
' Get one character.
Debug.Print MyChar
' Print to Debug window.
Loop
Close #1
' Close file.

Figure B-7: Input Statement Example

Copyright (c) 1999, Intellution, Inc.

B-9

*()DQXF

B.2.4.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Input # Statement ______________________________________

A. Input # Statement

Reads data from an open sequential file and assigns the data to variables.

Data read with Input # is usually written to a file with Write #


-

Use this statement only with files opened in Input or Binary mode

Syntax
Input #filenumber, varlist
-

filenumber Required

any valid file number

varlist Required

comma-delimited list of variables that are assigned values read from


the file - can't be an array or object variable

variables that describe an element of an array or user-defined type


may be used

' this example assumes that the file has a few lines of
' data containing a string in quotations and a number
' separated by a comma, for exa mple, ("Hello", 234)
Dim MyString, MyNumber
Open "c:\dynamics\file2.txt" For Input As #1
Do While Not EOF(1)
Input #1, MyString, MyNumber
Debug.Print MyString, MyNumber
Loop
Close #1

' Loop until end of file.

Figure B-8: Input # Statement Example

Copyright (c) 1999, Intellution, Inc.

B-10

*()DQXF

B.2.5.

ZZZML\LWHFKFRP


Student Guide

Write # Statement ______________________________________

A. Write # Statement

Writes data to a sequential file

Data written with Write # is usually read from a file with Input #

Unlike the Print # statement, the Write # statement inserts commas between items
and quotation marks around strings as they are written to the file
-

Write # inserts a newline character after it has written the final character in
outputlist to the file

that is, a carriage returnlinefeed (Chr(13) + Chr(10)) is added

Syntax
Write #filenumber, [outputlist]
-

filenumber Required

outputlist Optional

any valid file number

One or more comma-delimited numeric expressions or string


expressions to write to a file

' This example uses the Write # statement to write r aw data


' to a
sequential file.
Open " c:\dynamics\file3.txt " For Output As #1
Write #1, "Hello World", 234
' Write comma-delimited data.
Write #1,
' Write blank line.
Dim MyBool, MyDate, MyNull, MyError
MyBool = False : MyDate = #January 1 , 2000# : MyNull = Null
MyError = CVErr(32767)
Write #1, MyBool ; " is a Boolean value"
Write #1, MyDate ; " is a date"
Write #1, MyNull ; " is a null value"
Write #1, MyError ; " is an error value"
Close #1

Figure B-9: Write # Statement Example

Copyright (c) 1999, Intellution, Inc.

B-11

*()DQXF

B.2.6.

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

Print # Statement_______________________________________

A. Print # Statement

Writes display-formatted data to a sequential file

Data written with Print # is usually read from a file with Input # or Input

If the data from a file is to be read using the Input # statement, use the Write #
statement instead of the Print # statement to write the data to the file
-

using Write # ensures the integrity of each separate data field by properly
delimiting it, so it can be read back in using Input #

Syntax
Print #filenumber, [outputlist]
-

filenumber Required

any valid file number

outputlist Optional

Expression or list of expressions to print

' This example uses the Print # statement to write data to a file.
Open " c:\dynamics\file4.txt " For Outpu t As #1
Print #1, "Hello" ; " " ; "World"
' Separate strings with space.
Print #1, "Zone 1"; Tab ; "Zone 2"
' Print in two print zones.
Print #1,
' Print blank line to file.
Print #1, Spc(5) ; "5 leading spaces " ' Print five leading spaces.
Print #1, Tab(10) ; "Hello"
' Print word at column 10.
Dim MyBool, MyDate, MyNull, MyError
MyBool = False : MyDate = #January 1, 2000# : MyNull = Null
MyError = CVErr(32767)
Print #1, MyBool ; " is a Boolean value"
Print #1, MyDate ; " is a date"
Print #1, MyNull ; " is a null value"
Print #1, MyError ; " is an error value"
Close #1

Figure B-10: Print # Statement Example

Copyright (c) 1999, Intellution, Inc.

B-12

*()DQXF

ZZZML\LWHFKFRP


Student Guide

C. Additional Notes___________________________________________

Appendix C
Additional Notes

Copyright (c) 1999, Intellution, Inc.

C-1

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

C.1. iFIX Object Methods ______________________________________

AboutBox
AckAlarmPage
ActivateWorkspaceUI
AddEventHandler
AddLegendItem
AddObject
AddPoint
ApplyProperty
BringToFront
CanConstruct
ClearUndo
Commit
ConnectedPropertyCount
ConvertSecurityAreaNameToNumber
Copy
CreateFromDialog
CreateWithMouse
DeActivateWorkspaceUI
DelAlarm
DeleteImage
DeletePoint
DemandFire
DestroyObject
Disconnect
DoesPropertyHaveTargets
DumpProperties
EditPicture
ExchangePenPositions
FindInString
FindReplaceInObject
FitDocumentToWindow
FixCheckApplicationAccess
FixCheckSecurityEnabled
FixLogin
FontProperties

AckAlarm
AckAllAlarms
Add
AddImage
AddLevel
AddPen
Align
AutoScaleDisplayLimits
BuildObject
Clear
Close
Connect
Construct
ConvertSecurityAreaNumberToName
CopyAsBitmap
CreateFromProgID
Cut
DefaultView
DeleteAllAlarms
DeletePen
DeleteSelectedObjects
DeselectObject
DisableNonSelectionEvents
DisplaysControlPoints
DoMenuCommand
Duplicate
Enable
FindAndReplaceDialog
FindObject
FindReplaceInString
FitWindowToDocument
FixCheckAreaAccess
FixGetUserInfo
FixLogout
FullView

Figure C-11: iFIX Object Methods

Copyright (c) 1999, Intellution, Inc.

C-2

*()DQXF

ZZZML\LWHFKFRP


Student Guide

C.1. iFIX Object Methods ______________________________________

GetBoundRect
GetConnectionInformation
GetCurrentValue
GetDuration
GetEventHandlerIndex
GetInterval
GetObjectInfo
GetPointAt
GetProperty
GetPropertyTargets
GetSelectedNodeTag
GetSelectedUserDefFields
GetStatusFont
GetTimeCursorInfo
Group
InsertPoint
IsConnected
Item
ListMethods
LoadImage
LogicalToUserFormPoint
Modify
Move
ParseConnectionSource
PasteSpecial
PercentageToLogical
PixelToPercentage
Quit
Refresh
Remove
RemoveItem
RemoveLevel
ReplaceDocument
ResetChartData
ResetStats

GetColumnInfo
GetConnectionParameters
GetDeviceRect
GetErrorString
GetIndirectionInfo
GetLevel
GetPenDataArray
GetPriorityColor
GetPropertyAttributes
GetSelectedAlmExt
GetSelectedRow
GetStatusColor
GetTimeBeforeNow
GetWindowLocation
HiLoDisplay
IsColorSelectionVisible
IsEmpty
ListEvents
ListProperties
LogicalToPercentage
MakeSameSize
ModifyColumnLength
Open
Paste
Pause
PercentageToPixel
PrintOut
Read
RefreshChartData
RemoveAllLevels
RemoveLegendItem
RemoveObject
ReplaceInString
ResetObjectStats
ResetZoom

Figure C-11: iFIX Object Methods (continued)

Copyright (c) 1999, Intellution, Inc.

C-3

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

C.1. iFIX Object Methods ______________________________________

Resume
RunObject
SaveToHistoryList
ScrollForward
ScrollTimeForward
SelectAll
SendOperatorMessage
SetCurrentValue
SetDISPID
SetFocusToComboBox
SetInterval
SetPenDataArray
SetPriorityColor
SetScriptWindow
SetStatusColor
SetStringFormat
SetTimeBeforeNow
SetWindowLocation
ShowBrowseDialog
ShowColorSelection
ShowTaskWizard
SnapObjectsToGrid
StartEvent
StickToCursor
StopTimer
SwitchMode
UIDeActivate
UndoTransaction
UpdateBackgroundObject
UserFormPointToLogical
ValueTimeFromXY
XYFromValueTime
Zoom

Rotate
Save
ScrollBack
ScrollTimeBack
Select
SelectObject
SendToBack
SetDispatch
SetDuration
SetIndirectionInfo
SetNumericFormat
SetPointAt
SetProperty
SetSource
SetStatusFont
SetTabSelection
SetTimeCursorTime
ShowAnimations
ShowColorBox
ShowCustomPages
ShowVisualBasicEditor
SpaceEvenly
StartTimer
StopEvent
Stretch
UIActivate
Undo
UnGroup
UpdateConnectionParameters
ValidateSource
Write
XYHitTest

Figure C-11: iFIX Object Methods (continued)

Copyright (c) 1999, Intellution, Inc.

C-4

*()DQXF

ZZZML\LWHFKFRP


Student Guide

C.2. Mathematical Functions ___________________________________

Secant

Sec(X) = 1 / Cos(X)

Cosecant

Cosec(X) = 1 / Sin(X)

Cotangent

Cotan(X) = 1 / Tan(X)

Inverse Sine

Arcsin(X) = Atn(X / Sqr(-X * X + 1))

Inverse Cosine

Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)

Inverse Secant

Arcsec(X) = Atn(X / Sqr(X * X 1)) + Sgn((X) 1) * (2 * Atn(1))

Inverse Cosecant

Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) 1) * (2 *


Atn(1))

Inverse Cotangent

Arccotan(X) = Atn(X) + 2 * Atn(1)

Hyperbolic Sine

HSin(X) = (Exp(X) Exp(-X)) / 2

Hyperbolic Cosine

HCos(X) = (Exp(X) + Exp(-X)) / 2

Hyperbolic Tangent

HTan(X) = (Exp(X) Exp(-X)) / (Exp(X) + Exp(-X))

Hyperbolic Secant

HSec(X) = 2 / (Exp(X) + Exp(-X))

Hyperbolic Cosecant HCosec(X) = 2 / (Exp(X) Exp(-X))


Hyperbolic
Cotangent

HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) Exp(-X))

Inverse Hyperbolic
Sine

HArcsin(X) = Log(X + Sqr(X * X + 1))

Inverse Hyperbolic
Cosine

HArccos(X) = Log(X + Sqr(X * X 1))

Inverse Hyperbolic
Tangent

HArctan(X) = Log((1 + X) / (1 X)) / 2

Inverse Hyperbolic
Secant

HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)

Inverse Hyperbolic
Cosecant

HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) + 1) / X)

Inverse Hyperbolic
Cotangent

HArccotan(X) = Log((X + 1) / (X 1)) / 2

Logarithm to base N

LogN(X) = Log(X) / Log(N)

Figure C-12: Mathematical Function Equivalents

Copyright (c) 1999, Intellution, Inc.

C-5

*()DQXF

ZZZML\LWHFKFRP

Intellution
Dynamics iFIX

C. Additional Notes___________________________________________

this page intentionally left blank

Copyright (c) 1999, Intellution, Inc.

C-6

Potrebbero piacerti anche