IFIX-354
Transcript of IFIX-354
-
Intellut on
Educational Services
354 Student Guide
Using Visual Basic for Applications
with Intellution Dynamics iFIXVersion 2.1 - 7.99
Copyright 1999, Intellution, Inc.All Rights Reserved
-
Intellut on Student Information SheetName: _________________________________ Date: ____________________________
Title: __________________________________ Course: 354 v2.1-7.99
Phone Number: _________________________ Instructor: ________________________
Fax Number: ___________________________ Class Location: ___________________
E-mail: _______________________________________________________________________
Company Name and Address: _____________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
Hotel where you are staying: ______________________________________________________
1. Have you used any Intellution, Inc. products? Yes NoIf 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: ______ SI: ______ Rep: ______
Dealer: ______ OEM ______ A&E: ______
Inty Emp: ______ Other (explain): _________________
-
Student Guide
Copyright 1999, Intellution, Inc. i
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 thelicense with Intellution, Inc. The information in this manual is subject to change without noticeand should not be construed as a commitment by Intellution, Inc. Intellution, Inc. assumes noresponsibility 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 productnames are trademarks of Intellution, Inc. All other names are property of their respectiveholders.
Microsoft Visual Basic Technology. 1996, Microsoft Corporation. All Rights Reserved.
Printed in the United States of America.
T h e I n t e l l i g e n t S o l u t i o n One Edgewater Drive, Norwood, MA 02062
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. ii
Table of Contents _____________________________________________
Intellution Dynamics iFIX Training Student Guide
Days One and Two ................................................................................ x
Days Three and Four............................................................................. xi
Introduction........................................................................................... xii
1. Overview......................................................................................... 1-1
1.1. VBA Scripts........................................................................ 1-41.1.1. Understanding Objects .................................................. 1-61.1.2. Object Properties........................................................... 1-81.1.3. Object Methods............................................................. 1-101.1.4. Object Events ................................................................ 1-11
1.2. Container Objects................................................................ 1-121.2.1. iFIX Container .............................................................. 1-141.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-42.2.1. Project Explorer ............................................................ 2-62.2.2. Property Window .......................................................... 2-82.2.3. Immediate Window....................................................... 2-102.2.4. Code Window ............................................................... 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
-
Student Guide
Copyright 1999, Intellution, Inc. iii
Table of Contents _____________________________________________
3. Variables and Constants ................................................................ 3-1
3.1. Naming Rules....................................................................... 3-3
3.2. Variables .............................................................................. 3-43.2.1. Integers ......................................................................... 3-63.2.2. Floating Point................................................................ 3-73.2.3. String Data .................................................................... 3-83.2.4. Variant .......................................................................... 3-10
3.3. Declaring Variables .............................................................. 3-123.3.1. Variable Scope .............................................................. 3-163.3.2. Variable Lifetime .......................................................... 3-173.3.3. User Defined Data Types............................................... 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
4. Procedures and Functions ............................................................. 4-1
4.1. VBA References................................................................... 4-4
4.2. Procedures............................................................................ 4-64.2.1. Understanding Events.................................................... 4-104.2.2. Understanding Scope..................................................... 4-124.2.3. Procedure Arguments .................................................... 4-144.2.4. Expressions ................................................................... 4-18
4.3. Code Locations..................................................................... 4-224.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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. iv
Table of Contents _____________________________________________
5. VBA Debugging ............................................................................. 5-1
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-105.5.1. Stepping Through Procedures..................................... 5-125.5.2. Immediate Window .................................................... 5-145.5.3. Watch Window........................................................... 5-165.5.4. Quick Watch .............................................................. 5-185.5.5. Locals Window .......................................................... 5-205.5.6. VBE Calls Stack......................................................... 5-225.5.7. VBE Debug Floating Toolbar ..................................... 5-23
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. Introduction to Forms.................................................................... 6-1
6.1. Forms Overview................................................................... 6-3
6.2. Creating a Form.................................................................... 6-66.2.1. Form Controls ............................................................ 6-96.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
-
Student Guide
Copyright 1999, Intellution, Inc. v
Table of Contents _____________________________________________
7. Controlling VBA Code................................................................... 7-1
7.1. Decision Statements ............................................................ 7-37.1.1. If Then Else................................................................... 7-47.1.2. If Then ElseIf ................................................................ 7-87.1.3. Select Case.................................................................... 7-107.1.4. GoTo............................................................................. 7-12
7.2. Looping .............................................................................. 7-137.2.1. Do Loops ...................................................................... 7-147.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
8. Collections and Groups.................................................................. 8-1
8.1. Grouped Objects ................................................................. 8-38.1.1. ContainedObjects Property............................................ 8-48.1.2. ContainedSelections Property........................................ 8-68.1.3. Grouped Object Properties ............................................ 8-88.1.4. Group Events ................................................................ 8-10
8.2. Collections.......................................................................... 8-118.2.1. Pre-Defined Collections ................................................ 8-128.2.2. User Defined Collections............................................... 8-148.2.3. For Each Next Loop ...................................................... 8-19
8.3. Lab Exercise 8 .................................................................... 8-20
8.4. Summary Questions ............................................................ 8-33
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. vi
Table of Contents _____________________________________________
9. Embedded Objects ......................................................................... 9-1
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-810.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-811.3.1. Procedure Based Error Handler .................................. 11-1211.3.2. Global Based Error Handler........................................ 11-14
11.4. VBA Error Codes................................................................ 11-16
-
Student Guide
Copyright 1999, Intellution, Inc. vii
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-812.4.1. Dim Statement using New Keyword........................... 12-1012.4.2. Set Statement.............................................................. 12-1112.4.3. CreateObject Function................................................ 12-1212.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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. viii
Table of Contents _____________________________________________
14. Accessing Relational Databases ..................................................... 14-1
14.1. Overview ............................................................................ 14-3
14.2. Data Access Objects (DAO)................................................ 14-613.2.1. Joint Engine Technology (JET) .................................. 14-813.2.2. ODBCDirect .............................................................. 14-913.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-6B.2.1. Put Statement ............................................................. B-7B.2.2. Get Statement............................................................. B-8B.2.3. Input Statement .......................................................... B-9B.2.4. Input # Statement ....................................................... B-10B.2.5. Write # Statement....................................................... B-11B.2.6. Print # Statement ........................................................ B-12
C. Additional Notes .............................................................................. C-1
C.1. iFIX Object Methods .......................................................... C-2
C.2. Mathematical Functions ...................................................... C-5
-
Student Guide
Copyright 1999, Intellution, Inc. ix
Table of Contents _____________________________________________
this page intentionally left blank
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. x
Days One and Two ____________________________________________
Section 1 Section 5
Overview DebuggingIntroduction to VBA Understanding ErrorsiFIX and VBA Debugging ToolsContainer Objects Hints and TipsVBA Code and VBA HelpAutomation Interface Help
Section 6
Introduction to Forms
Section 2 Creating FormsVBA Environment Form Controls
Visual Basic Editor Launching FormsMessage Box and Input Box Form Events
Section 3 Section 7
Variables Controlling VBA CodeData Types Decision StatementsUser Defined Data Types If Then ElseArrays Case StatementConstants Loops
For Next LoopDo Loops
Section 4
Procedures and FunctionsProcedures Section 8Class Modules Collections and GroupsExpressions Grouped ObjectsFunctions Group EventsObject Browser User Defined Collections
-
Student Guide
Copyright 1999, Intellution, Inc. xi
Days Three and Four __________________________________________
Section 9 Section 12
Embedded Objects AutomationWorkSpace Variable Object Using AutomationTimer Object Adding ReferencesEvent Object Automation ExamplesScheduler
Section 13
Section 10 ActiveX, Linking, and Embedding
iFIX Automation ActiveXAccessing the Process Database iFIX ActiveX ControlsiFIX Subroutines VBA and ActiveX ControlsDatabase Functions Installing ActiveX Controls
OLE
Section 11
Error Handling Section 14Using Error Handlers Accessing a Relational DatabaseError Handle Examples Data Access Objects (DAO)VBA Error Codes ActiveX Data Objects (ADO)
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. xii
Introduction __________________________________________________
Course DescriptionThis course is designed for those who wish to acquire a basic knowledge of Visual Basic forApplications (VBA) within the iFIX container. This knowledge will allow the student togenerate VBA based solutions for their special system requirements. The student should befamiliar with the iFIX workspace and its features. The course begins with an introduction toVBA and why VBA is so important in todays applications. Lectures, coding example, andlabs are included in this course on the important aspects of VBA, as well as reference toVisual Basic syntax. This course will demonstrate to the student how to enhance runtimeoperation to solve special problems. Additionally, the material will present information onadding custom design tools (like ActiveX objects) and adding online maintenance tools suchas operation manuals, part descriptions, and P&ID views.
AudienceThis course is principally designed for system integrators, instrumentation engineers andprocess engineers who want to use the power of VBA to create unique solutions for theirapplications 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 DurationFour (4) days.
Continuing Education UnitsThis course is worth 3.2 CEU credits.
-
Student Guide
Copyright 1999, Intellution, Inc. 1-1
1. Overview __________________________________________________
Chapter 1
Overview
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-2
1. Overview _________________________________________________
Section Objectives
This section provides an introduction to the VBA and the iFIX object Hierarchy. The studentwill run through a VBA sample application and discuss how objects are used within VBA. Thisincludes 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.
-
Student Guide
Copyright 1999, Intellution, Inc. 1-3
1. Overview _________________________________________________
A. What is VBA?
VBA Microsoft Visual Basic for Applications
- an object-oriented and event-driven development environment thatsupports 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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-4
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 VBAscripts
VBA scripts will perform functions like calculations or other minor tasks but themain 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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-5
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 canbe 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 themouse on the object or changes its size
If a script is associated with an event, the script executes whenthe event triggers or occurs
Events can occur as a result of user action, program code, or otheroccurrences in iFIX
Examples: mouse click, value reaches a threshold
Figure 1-1: VBA Terminology
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-6
1.1.1. Understanding Objects _________________________________
A. Notes
A VBA object is anything in the application that can be referenced andmanipulated
An object represents an element of an application, such as a worksheet, a cell, achart, 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 basedon 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, dependingon what needs to be accomplished
-
Student Guide
Copyright 1999, Intellution, Inc. 1-7
1.1.1. 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 Linear
Lines Lookup
Oval Pen
Picture Pie
Polygon Polyline
Procedures Rectangle
RoundRectangle Scheduler
ScriptLine ScriptProcedure
ScriptSource Sources
System Text
TimeAxis Timer
UserGlobals ValueAxis
Variable Window
Figure 1-2: iFIX Objects
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-8
1.1.2. 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 itsbehavior, 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 anobject
- there is also a Property Window in the Visual Basic Editor to viewproperties of an object
Figure 1-3 shows some of the properties of a picture object using the PropertyWindow
C. Changing the property of an object
To set the value of a property, follow the reference to an object with a period, theproperty 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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-9
1.1.2. Object Properties ______________________________________
Figure 1-3: Properties Window Example
Private Sub Rect1_Click()
FermTank.BackgroundColor = vbBlue
End Sub
Figure 1-4: Property Scripting Example
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-10
1.1.3. 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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-11
1.1.4. 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 clickevent occurs
- the script in Figure 1-5 run a procedure when the picture initialize eventoccurs
Figure 1-7 lists the events available in iFIX
- note that not all events are available to all objects
Activated AfterKillFocus
AlarmAck Click
Close ColorChanged
DataChange DblClick
DeActivated 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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-12
1.2. Container Objects ________________________________________
A. Application Object
The object that is common to all applications and is at the top of the applicationmodel is the Application Object
The application object is the container for all other objects even other containerobjects 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 inWorkSpace
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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-13
1.2. Container Objects ________________________________________
Figure 1-8: iFIX Object Hierarchy
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-14
1.2.1. 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 otherobjects
-
Student Guide
Copyright 1999, Intellution, Inc. 1-15
1.2.1. iFIX Container__________________________________________
Windows NT
NIC
Text
Modem
Serial Port
Hard Drive
Mouse
KeyboardiFIX Container
Picture Object
LineObject
RectObject
TextObject
Object Event VBA Code
Container Support Code
Excel Container
Workbook Object
Sheet1 Object
Sheet2 Object
XYZ Container
Form Object
Figure 1-9: iFIX Container
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-16
1.2.2. 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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-17
1.2.2. 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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-18
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 createa 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, andreferences
The VBA code within a project is contained within a module
- Modules, and all other supporting VBA components, make up a VBAproject
- in the VBE clicking on the Project_untitled will bring the module intoview in the code window of the VBE
Within a module, code is divided into procedures
- 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 bediscussed in the next chapters:
- Variables
- Constants
- Functions
- User forms
- Looping
- Decisions
- Debugging
- Expressions
- Automation
- Error Handling
-
Student Guide
Copyright 1999, Intellution, Inc. 1-19
1.3. VBA Code _______________________________________________
Figure 1-10: Visual Basic Editor
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-20
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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-21
1.4. VBA Help _______________________________________________
Figure 1-11: VBA Help (Contents tab shown)
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-22
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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-23
1.5. iFIX Automation Interface Help _____________________________
Figure 1-13: iFIX Automation Help Alphabetical List
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-24
1.5. iFIX Automation Interface Help _____________________________
Figure 1-14: Automation Help Example (Rectangle Object)
Figure 1-15: Automation Help Example (Click Event)
-
Student Guide
Copyright 1999, Intellution, Inc. 1-25
1.5. iFIX Automation Interface Help _____________________________
Figure 1-16: Automation Help Example (ForegroundColor Property)
Figure 1-17: Automation Help Example (Rotate Method)
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-26
1.6. Key Terms ______________________________________________
VBA Terminology
Project Stores all VBA code and any added components: includesdocuments, 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. IntellutionWorkSpace 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 canbe 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 themouse on the object or changes its size
If a script is associated with an event, the script executes whenthe event triggers or occurs
Events can occur as a result of user action, program code, orother occurrences in iFIX
Examples: mouse click, value reaches a threshold
Figure 1-18: VBA Terminology
-
Student Guide
Copyright 1999, Intellution, Inc. 1-27
1.7. ___________________________________________Lab Exercise 1
Introduction to VBA
Lab Exercise 1
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-28
_______________________________________________Lab Exercise 1
Lab Information
Upon successful completion of this lab exercise, you will be familiar with many terms relatedto VBA in iFIX. You will also be familiar with locating and manipulating various features inthe 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-BooksThe 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 apoint 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 youthrough various dialog boxes and windows. You will discover how to open various windowsand 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 theRelease Notes. There is also Automation Interfaces Help and Database Manager Help. Allof these can be found in the Help & Information folder of the WorkSpace System Tree. Andof course, if you go to the help menu you can get WorkSpace Help and Picture Help. Whenyou are working with the Visual Basic Editor, you have access to Microsoft Visual BasicHelp and iFIX Automation Help.
-
Student Guide
Copyright 1999, Intellution, Inc. 1-29
_______________________________________________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 VBAapplications, 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, eachVBA implementation seems to vary. Why?
2. Can you use iFIX VBA to build a stand-alone application that can be complied downto an EXE, DLL, or OCX?
3. Since VBA is the same across all applications, you could take the VBA code and theUserForms you developed in iFIX VBA and drop them into Excel. Can you also takethe VBA code and UserForms you developed in iFIX VBA and drop them intoMicrosoft 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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-30
_______________________________________________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 oval
1 polyline 2 polygons
1 arc 1 pie1 chord 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
-
Student Guide
Copyright 1999, Intellution, Inc. 1-31
_______________________________________________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 uninterestingnames.
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 correspondingobject also is selected in the System Tree and in the Properties Window. You canalso select an object in the System Tree, or by using the drop-down menu in theProperties Window.
Regardless where you select the object (WorkSpace work area, System Tree, or
Properties Window) the corresponding information about the object is highlighted inthe other two locations.
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-32
_______________________________________________Lab Exercise 1
C. Edit the new picture
Now, we will go to the Properties window and make some changes so that you can seehow that affects your object in the work area.
1. Select one of the rectangles, Rect1 perhaps. Now, in the properties page, modify thefollowing 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 modifiedwith VBA code both at run-time (Run mode) and design-time (Configure mode).These same properties can have animations assigned to them.
-
Student Guide
Copyright 1999, Intellution, Inc. 1-33
_______________________________________________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 adescription, 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 Windowand 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 bethe Immediate Window and above it the Code Window. Above the Code Windowon the left-hand side is the VBE Object drop-down list. This is a list of objects thatare registered with the VBE. To the right of it is the Event drop-down list.
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-34
_______________________________________________Lab Exercise 1
D. Viewing the VBE Configuration
1. Go to the Project Explorer in the VBE, and highlight the Project_VBAObjectsproject.
2. Right click it and select Project_VBAObjects Properties from the menu. Youshould 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 youcan password protect your VBA code so other people can not access it. If someonewere looking at your picture in the WorkSpace and decided to look at your code bylaunching the Visual Basic Editor, they would get a prompt that forces them to type ina user and password.
5. Now, close the Project Properties dialog box by clicking the OK button.
-
Student Guide
Copyright 1999, Intellution, Inc. 1-35
_______________________________________________Lab Exercise 1
E. Additional VBE Functionality
1. Go to the Project Explorer and highlight the Project_VBAObjects project. Rightmouse 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 theProperties 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 seethe module you just inserted, Module1. You can change the name to something moremeaningful. Also, you can have many modules.
In general, modules contain functions and subroutines called by the picture eventcode or by other functions and subroutines.
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-36
_______________________________________________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 howmany 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 theProject 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:
-
Student Guide
Copyright 1999, Intellution, Inc. 1-37
_______________________________________________Lab Exercise 1
5. Put your cursor on the word Rotate10degrees and press the key. If you madeany typos, you may have gotten an error message after hitting . If not, you justran your code.
6. Use to go back to the WorkSpace to see what changed. You should seethat 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 theWorkSpace was not even in Run mode!
End of Lab Exercise
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 1-38
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 Dynamicsfamily 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 GRFfile)?
-
Student Guide
Copyright 1999, Intellution, Inc. 2-1
2. VBA Environment___________________________________________
Chapter 2
VBA Environment
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-2
2. VBA Environment _________________________________________
Section Objectives
This section provides an introduction to the VBA environment. The discussion will includeVBA projects. The student will also use the Visual Basic Editor to create VBA script. Thisincludes the following:
Visual Basic Editor
Working in the VBE
Creating Procedures
Creating Modules
MsgBox and InputBox
-
Student Guide
Copyright 1999, Intellution, Inc. 2-3
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 newproject 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 suchas Modules, Class modules, and User Forms
- Picture documents, Modules, User Forms, and Class modules and all othersupporting 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 PictureDocument, 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 orreturns a value
- To perform any VBA task a procedure must be written
- Every procedure has a name which must be unique within a module
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-4
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
- displays all the VBA projects currently opened in the WorkSpace
Properties Window
- displays the properties of the selected object
Code Window
- displays the code of the selected picture, module, or class module
Immediate Window
- used to test code functions without running an entire procedure
-
Student Guide
Copyright 1999, Intellution, Inc. 2-5
2.2. Visual Basic Editor _______________________________________
Project Explorer Code Window
Property Window Immediate Window
Figure 2-1: Visual Basic Editor (VBE)
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-6
2.2.1. 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 otherdocuments
Projects contain open application objects (such as a picture), modules (if you havecreated them), and user forms you have built
Saving a project
- Projects can be saved by highlighting the project and selecting SaveProject from the File menu
- Also, when the application is saved, such as saving a picture inWorkSpace, the project will be automatically saved
-
Student Guide
Copyright 1999, Intellution, Inc. 2-7
2.2.1. Project Explorer _______________________________________
Figure 2-2: VBE Project Explorer
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-8
2.2.2. 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
-
Student Guide
Copyright 1999, Intellution, Inc. 2-9
2.2.2. Property Window ______________________________________
Figure 2-3: VBE Property Window
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-10
2.2.3. 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 debugan 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
-
Student Guide
Copyright 1999, Intellution, Inc. 2-11
2.2.3. Immediate Window _____________________________________
Figure 2-4: VBE Immediate Window
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-12
2.2.4. 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 andperform 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 inthe 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 theWizard Bar
C. Procedures
A self contained block of code is called a procedure
Two types of procedures:
- Sub Procedure
- Function Procedure
-
Student Guide
Copyright 1999, Intellution, Inc. 2-13
2.2.4. Code Window _________________________________________
Figure 2-5: VBE Code Window
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-14
2.2.4. 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 selectedobject procedure
- At the bottom left of window, select Full Module View or ProcedureView
A Group of objects is also an object
Includes (General) which refers to any procedures that are not associated with aparticular 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
From the Edit menu, select Select All and then right click EnableScripts
-
Student Guide
Copyright 1999, Intellution, Inc. 2-15
2.2.4. Code Window _________________________________________
Figure 2-6: VBE Object List
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-16
2.2.4. 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:
Initialize event is available for an iFIX picture object but does notexist as an event for a rectangle object
-
Student Guide
Copyright 1999, Intellution, Inc. 2-17
2.2.4. Code Window _________________________________________
Figure 2-7: VBE Procedure (Event) List
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-18
2.2.4. 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 avalue
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
-
Student Guide
Copyright 1999, Intellution, Inc. 2-19
2.2.4. 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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-20
2.2.4. 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 otherprocedures 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 areimported
this may not be the desired result
to only add a particular procedure, open the *.BAS file in a texteditor 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
-
Student Guide
Copyright 1999, Intellution, Inc. 2-21
2.2.4. Code Window _________________________________________
Figure 2-10: Add Procedure Dialog Box
Figure 2-11: Import File Dialog Box
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-22
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, andreturns 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 commadelimiter
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 numberand type of buttons to display, the icon style to use, the identity ofthe 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 providecontext-sensitive Help for the dialog box
- context Optional
numeric expression that is the Help context number assigned to theappropriate Help topic by the Help author
-
Student Guide
Copyright 1999, Intellution, Inc. 2-23
2.3. Message Box ____________________________________________
Figure 2-12: VBA - Help MsgBox Topic
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-24
2.4. Input Box _______________________________________________
A. Notes
Displays a prompt in a dialog box, waits for the user to input text or click abutton, and returns a String containing the contents of the text box
If the user clicks OK or presses Enter, the InputBox function returns whatever isin 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 commadelimiter
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 responseif 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 leftedge 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 upperedge of the dialog box from the top of the screen
If ypos is omitted, the dialog box is vertically positionedapproximately one-third of the way down the screen
- helpfile same as MsgBox
- context same as MsgBox
-
Student Guide
Copyright 1999, Intellution, Inc. 2-25
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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-26
2.5. ___________________________________________Lab Exercise 2
Objects, Events, and VBA Code
Lab Exercise 2
-
Student Guide
Copyright 1999, Intellution, Inc. 2-27
_______________________________________________Lab Exercise 2
Learning Objectives:
Upon successful completion of this lab exercise, you will be more familiar with locating andmanipulating 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-BooksThe iFIX Automation On-line HelpMicrosoft Visual Basic On-line Help
Lab Information
During lecture you covered the VBA Editor and many of its settings and windows. This labwill give you some hands-on with the VBA Editor.
Note: Throughout the exercise, the following object naming conventions are used:
Prefix: What the object represents such as Pipe, Valve, Tank, PumpRoot: Properties of the object such as Color, Position, NumberSuffix: 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 LinDatalink Lnk, Command Button Cmd, Chord Crd, Arc Arc, Pie Pie
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-28
_______________________________________________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 correlatedto the objects and properties in the Properties dialog box both in the WorkSpace and inthe Visual Basic Editor. With this lab you will see how the Event code in the VisualBasic Editor correlates to the objects in the WorkSpace.
1. Create a new picture in the WorkSpace and draw a rectangle, line, oval, polygon, andpolyline.
The picture should resemble the following:
2. Save this picture with the following name:
IngredientTank
-
Student Guide
Copyright 1999, Intellution, Inc. 2-29
_______________________________________________Lab Exercise 2
3. Using the Property Window, modify the properties of the objects as follows:
Rect1: Name: Tank1Rct
Description: Ingredient Tank#1
EdgeWidth: 4
ForegroundColor: Blue (16711680)
Line1: Name: PipeTk1ToVlv1Lin
Description: Tank #1 Pipe to Transfer Valve
EdgeColor: Black (0)
EdgeWidth: 9
Oval1: Name: Vlv1XoutOvl
Description: Valve #1 background
EdgeWidth: 4
ForegroundColor: Light Gray (12632256)
Polygon1: Name: Vlv1XoutPgn
Description: Valve #1 rotary-valve
EdgeWidth: 4
ForegroundColor: Dark Gray (8421504)
PolyLine1: Name: PipeXoutPln
Description: Transfer Out Pipe
EdgeColor: Black (0)
EdgeWidth: 9
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-30
_______________________________________________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 menufollowed by Rotate.
You will see the center of rotation and rotation handles appear.
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 thepolygon.
Center ofRotation
-
Student Guide
Copyright 1999, Intellution, Inc. 2-31
_______________________________________________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 theevent drop-down menu, select MouseMove.
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-32
_______________________________________________Lab Exercise 2
3. You will now type the MouseMove event code as in the figure below. It is also goodprogramming practice to use comments, so you will be typing those in also, as yousee 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:
-
Student Guide
Copyright 1999, Intellution, Inc. 2-33
_______________________________________________Lab Exercise 2
4. Next, use 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 MouseMoveevent, so from the event drop-down menu, select MouseMove. You will now typethe MouseMove event code as in the figure below adding comments as you see fit.
' Mouse-move event for the Polygon that represents our' Transfer out Valve. Any time you move the mouse over the' polygon, the rotation angle value of the polygon is' increased. The valve is immediately flipped back to its' original position when it goes upside down.
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
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-34
_______________________________________________Lab Exercise 2
C. Viewing the picture in Run Mode
1. Use 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
-
Student Guide
Copyright 1999, Intellution, Inc. 2-35
2.6. Summary Questions ______________________________________
1. In the iFIX object hierarchy, what object serves as the container for all shape objects andActiveX controls?
2. As you work with iFIX, you will see that each picture has its own VBA programmingproject. 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 anentire code module.
4. Suppose you create an object in a picture and then task-switch to the VBE. The objectdoes not appear in the Object List. What can you do to get the object to appear in theObject List?
5. Explain IntelliSense. What is it and how can it be used?
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 2-36
2.6. Summary Questions ______________________________________
this page intentionally contains no data
-
Student Guide
Copyright 1999, Intellution, Inc. 3-1
3. Variables and Constants____________________________________
Chapter 3
Variables and Constants
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 3-2
3. Variables and Constants____________________________________
Section Objectives
This section provides an introduction to the concept of variables and constants in VBA. Thisincludes a look at variable data types, variable arrays, and constants. This includes thefollowing:
Variables
Variable Data Types
User Defined Data Types
Arrays
Constants
-
Student Guide
Copyright 1999, Intellution, Inc. 3-3
3.1. Naming Rules____________________________________________
A. Use the following rules when naming procedures, constants, variables, and arguments ina 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, andmethods 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 asfollows:
VBA.keyword
B. Notes
VBA is not case-sensitive, but it preserves the capitalization in the statementwhere 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 notbe declared
- However, a private variable named tank and a procedure-level variablenamed tank can be declared within the same module.
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 3-4
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
- Only statements in the same procedure can access variable
Module level
- 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
-
Student Guide
Copyright 1999, Intellution, Inc. 3-5
3.2. Variables________________________________________________
Figure 3-1: Data Type Help Screen
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 3-6
3.2.1. 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- 0 to 255, 8 bits/1 byte of memory
Integer (Short)
- -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
-
Student Guide
Copyright 1999, Intellution, Inc. 3-7
3.2.2. 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#
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 3-8
3.2.3. 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"
-
Student Guide
Copyright 1999, Intellution, Inc. 3-9
3.2.3. String Data _____________________________________________
Figure 3-2: Help - String Concatenation
Figure 3-3: Help - & Operator Example
-
Intellution Dynamics iFIX
Copyright 1999, Intellution, Inc. 3-10
3.2.4. 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
- Good practice would be to provide variables with a type
Variant is only variable type that can contain a Null
- 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 azero-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 hasoccurred in a procedure
- Unlike for other kinds of errors, normal application-level error handlingdoes not occur
- This allows the devel