Sie sind auf Seite 1von 49

smar - VBA TUTORIAL INSTALLATION AND OPERATION MANUAL

PROCESS VIEW
VBA TUTORIAL
FIRST IN FIELDBUS

JUN / 02
PROCESS VIEW
VBA TUTORIAL
VERSION 6.0

TM

FOUNDATION P V I E WT U T M E
smar
web: www.smar.com e-mail: smarinfo@smar.com

Specifications and information are subject to change without notice.

BRAZIL ARGENTINA CHINA FRANCE


Smar Equipamentos Ind. Ltda. Smar Argentina Smar China Corp. Smar France S. A. R. L.
Rua Dr. Antonio Furlan Jr., 1028 Soldado de La Independencia, 1259 3 Baishiqiao Road, Suite 30233 42, rue du Pavé des Gardes
Sertãozinho - SP 14170-480 (1429) Capital Federal – Argentina Beijing 100873, P.R.C. F-92370 Chaville
Tel.: +55 16 645-6455 Telefax: 00 (5411) 4776-1300 / 3131 Tel.: +86 10 6849-8643 Tel.: +33 1 41 15-0220
Fax: +55 16 645-6450 e-mail: smarinfo@smarperifericos.com Fax: +86-10-6894-0898 Fax: +33 1 41 15-0219
e-mail: smarinfo@smar.com e-mail: info@smar.com.cn e-mail: smar.adm@wanadoo.fr
GERMANY MEXICO SINGAPORE
Smar GmbH Smar México Smar Singapore Pte. Ltd.
Rheingaustrasse 9 Cerro de las Campanas #3 desp 119 315 Outram Road
55545 Bad Kreuznach Col. San Andrés Atenco #06-07, Tan Boon Liat Building
Germany Tlalnepantla Edo. Del Méx - C.P. 54040 Singapore 169074
Tel: + 49 671-794680 Tel.: +53 78 46 00 al 02 Tel.: +65 6324-0182
Fax: + 49 671-7946829 Fax: +53 78 46 03 Fax: +65 6324-0183
e-mail: infoservice@smar.de e-mail: ventas@smar.com e-mail: info@smar.com.sg

USA
Smar International Corporation Smar Laboratories Corporation Smar Research Corporation
6001 Stonington Street, Suite 100 10960 Millridge North, Suite 107 4250 Veterans Memorial Hwy.
Houston, TX 77040 Houston, TX 77070 Suite 156
Tel.: +1 713 849-2021 Tel.: +1 281 807-1501 Holbrook , NY 11741
Fax: +1 713 849-2022 Fax: +1 281 807-1506 Tel: +1-631-737-3111
e-mail: sales@smar.com e-mail: smarlabs@swbell.net Fax: +1-631-737-3892
e-mail: sales@smarresearch.com
© ICONICS, Inc., 2000
GraphWorX32, TrendWorX32, AlarmWorX32, ControlWorX32,
WebHMI, AlarmWorX6.0, ToolWorX, ToolBox, and OPC-To-The-
Core are trademarks of ICONICS, Inc.

IBM and PC are trademarks of International Business Machines Corp.


Microsoft, Windows 95, Windows 98, Windows CE, Windows NT, Windows
2000, Visual Basic, Visual Basic for Applications (VBA), and the Microsoft
Visual Basic logo, ActiveX are either registered trademarks or trademarks of
Microsoft Corporation in the United States and /or other countries.

All other trademarks are property of their respective companies.

Because of SMAR's continuing effort to improve its products, specifications in this


guide are subject to change without notice.
Index

Contents

Introduction - About this Guide ...................................................................... V


Introduction............................................................................................................................... V
Step One – A Display............................................................................................................... V

1. ProcessView Functionality........................................................................1-1
1.1 Introduction...................................................................................................................... 1-1
1.2 The Programming Environment ...................................................................................... 1-1
1.3 VBA Basics...................................................................................................................... 1-3
1.3.1 Procedures and Functions ...................................................................................... 1-3
1.3.2. Declaring variables ................................................................................................ 1-3
1.3.3. Assigning values .................................................................................................... 1-4
1.4 Displaying messages to the operator.............................................................................. 1-4
1.5 Reading the value of a variable....................................................................................... 1-5
1.6 Changing the value of a variable..................................................................................... 1-7
1.7 Using forms in VBA programs......................................................................................... 1-8
1.8 Defining user functions.................................................................................................. 1-11
1.9 Entering values with a touchscreen .............................................................................. 1-12

2. Accessing other Applications...................................................................2-1


2.1 Introduction...................................................................................................................... 2-1
2.2 Accessing another Application ........................................................................................ 2-2
2.3 Recipes based on Excel data.......................................................................................... 2-3
2.4 Recipes based on Access data....................................................................................... 2-7
2.5 Generating reports in Excel........................................................................................... 2-13
2.6 Sending email................................................................................................................ 2-17

3. Accessing OPC Data via OLE Automation ..............................................3-1


3.1 Introduction...................................................................................................................... 3-1
3.2 Connecting Excel to an OPC Server............................................................................... 3-1

III
Process View VBA Tutorial

Notes:

IV
Introduction

About this Guide


1.1 Introduction
Welcome to the ProcessView VBA Tutorial. This tutorial explains how to use Visual Basic for
Applications as it is implemented in ProcessView (GraphWorX32). Using step by step examples this
tutorial will show the almost unlimited possibilities of Visual Basic for Applications for new and
experienced users alike.
The tutorial covers the following topics:
• Displaying Messages
• Designing (interactive) forms
• Using user defined functions and procedures
• Accessing other applications using OLE Automation
• Making reports with Excel
• Choosing profiles/recipes from an Access database or Excel workbook.
• Sending emails using Outlook
• Reading from and writing to OPC Variables and Local Variables in GraphWorX32
• Accessing an OPC Server using OLE Automation
• Using additional Visual Basic components in VBA forms.

The different topics are divided into three sections:


• ProcessView Functionality
The first section covers the programming environment and the ProcessView functionality that can be
used for operations in GraphWorX32, TrendWorX32, AlarmWorX32 or the objects inside one of these
applications.
• Accessing Other Applications
The second section covers methods of accessing other applications using OLE Automation. Examples
include reporting with Excel, making recipes in Access and sending email.
• Accessing OPC Data via OLE Automation
The third and last section explains how to connect to the Automation DLL of an OPC Server from a
VB(A) engine. Many products might have VBA functionality, but only very few besides the SMAR
products actually include easy to use OPC capabilities. Therefore an example is included that makes it
possible to access OPC data from Excel using the Automation DLL of the OPC Server.

1.2 Step One – A Display


A sample display (base.gdf) has been created and should be used to execute the examples in this
tutorial. This display shows a part of a plant that is used to harden metal. To harden metal, the metal is
first heated in the furnaces 1 and 2, after that it is cooled down using a fluid. When material leaves the
cool down section it will be heated again to re-crystallize the material for an optimal result.
The bottom 65% of the display contains a visualization of the actual process, in the top 35% of the
screen the parameters of the different sections can be filled in using data entry fields.

V
Process View VBA Tutorial

Figure 1. - Sample display file: base.gdf

VI
Section 1
ProcessView Functionality
1.1 Introduction
This section covers the ProcessView functions, including GraphWorX32, TrendWorX32 and
AlarmWorX32 functions.
The different functions of an application can easily be accessed from within the application itself. For
example in GraphWorX32 starting at the ThisDisplay object any GraphWorX32 method or property can
be accessed. From this object either direct access to a property is provided, or if the property belongs
to an underlying object, methods are provided access to the underlying objects.

Figure 1.1. Structure of access to methods, properties or objects

We will first explain the programming environment and some VBA basics, before actually starting to
program.
Once familiar with the programming environment the programming can start. In this section the
following topics will be covered:
• Display messages to the operator
• Entering data
• Creating simple forms
• Defining and using user created functions
• Reading from and writing to OPC Variables and Local GraphWorX32 Variables

1.2 The Programming Environment


The Visual Basic for Applications programming environment is a so-called integrated development
environment. It is build up out of different parts as shown below.

1.1
ProcessView - VBA Tutorial

Figure 1.2. Visual Basic for Applications programming environment

The following parts are present clockwise starting at the upper left.
• The project window (View  Project Explorer): In the project window the different parts of the
projects are shown. Usually the following three folders are present: GWX32 Objects, containing all
GraphWorX32 objects, in this case the ThisDisplay object; Forms, which contains all defined forms
and Modules that contains all defined code modules. There is also a fourth folder possible that will
contain the class modules, but it is not that common.
• The form window: In the form window it is possible to change the look of a form using the toolbox
shown next to it. This toolbox contains by default about 15 component that can be used to create
forms, but it is also possible to add more components. VB 5.0 components as well as any ActiveX
control can be used in addition to VBA components.
• The code window: In the code window, the actual coding takes places and the different functions
and procedures are displayed. Different functions and or procedures can be selected from the two
pull down boxes found at the top of the code window.
• The Watches window (View  Watch Window): In the watches-window, a watch can be added.
The window is only used during debugging; it can contain variables, which show the current value
while running the code.
• The last window is the property window (View  Properties Window): This window shows the
properties of a module or function when the code window is active. It can also show the properties
of an object on a form or of the form itself, if the form window is active.

Besides the previously mentioned window there are also some additional windows that are quite
useful:
• The Object Browser (View  Object Browser): In the object browser all methods and properties
belonging to a particular library can be viewed.
• The References Windows (Tools  References): In the references-window, the currently used
references can be viewed. Additionally, it is possible to add references to the VBA project. Adding
additional references increases the functionality of the VBA project.

1.2
ProcessView - Functionality

1.3 VBA Basics


This section will only give a short introduction to some of the many possibilities and options that Visual
Basic for Applications offers. Only the most basic topics like procedures and functions, declaring
variables and assigning values will be covered.

1.3.1. Procedures and Functions


A program can be built out of one or more parts. Such a program part can either be a function or a
procedure. Both can take zero or more parameters but only the function is able to return a value.
The basic definitions for a procedure is:
Sub MyProc()

End Sub
And for a function:
Function MyFunc() As Integer

MyFunc=

End Function
In the above definitions no parameters are given to either the procedure or the function, but the
function returns an integer value. The return value is assigned to the function at the end.
When parameters have to be given to a function or procedure they will have to be placed between the
( and ). For example:
Sub MyProc2(Var1 As Integer, Var2 As Integer)

End Sub
These variables can be used as if they were local variables inside the procedure or function.
Starting a procedure from another procedure or function can be achieved with the Call statement:

Call MyProc

Starting a function from another procedure or function can be achieved by entering the following code:

Dim Result As Integer

Result=MyFunc()

The return value of the function called will be assigned to the variable Result, of course any variable
could be used as long as it is the same type as the return value of the function.

1.3.2. Declaring variables


In the previous section the name variable was already mentioned. A variable is an object in which a
value can be stored. In almost any VBA program developed variables will be used. A variable can
either be defined inside a procedure or function using the Dim statement or outside the procedures
and functions using the Dim or Public statements. If a variable is defined within a procedure or
function with the Dim statement it can be used within that procedure or function. If a variable is defined
with a Dim statement outside the function or procedure all functions and procedures in the module can
use the variable. If the variable is defined with Public all functions and procedures in all the modules
can use the variable.

1.3
ProcessView - VBA Tutorial

The principle of defining variables:

[Dim|Public] name As type


Name: the name of the character using the following format: [a-zA-Z][a-zA-Z0-9_]*
Type: the type of the variable, such as: integer, double, variant, string and so on.
Examples:
Dim Var_1 As Integer
Public Var2 As Variant
Dim ExcelObj As Excel.Application

1.3.3. Assigning values


Depending on the type of variable a value will either be assigned directly using the = character
otherwise the set name = object format must be used. The first format is used for normal values such
as integers, doubles and variants, while the second format is used for objects. Examples:
Var_1 = 15
Var_2 = 89.4345
Set ExcelObj = CreateObject(“Excel.Application”)

1.4 Displaying messages to the operator


The example covers the following topics:
• Creating a simple VBA program attached to a button.
• Displaying messages using the MsgBox function

The example:
A help button has to be implemented in the Heating section of the display to provide advice to the
operator if needed. When pressed this button will show the operator information in the Heating section.
With the sample display, base.gdf open, use the following steps to create the help button and the VBA
code behind it:

1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-button
from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "HeatingHelp" as the Script Name and press the OK button
5. Press the Edit Button to open the VBA Editor
6. Type in the following lines of the code in the module GwxHeatingHelp_Main:

Sub HeatingHelp(o As GwxPick)


MsgBox "The temperatures of furnaces 1 & 2 can be changed here"
End Sub

The MsgBox function uses, the string that will be displayed in the dialog box on execution of the
script, as a parameter.
7. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
8. Use the property page to change the text on the button to "Help"

The result of adding this button is shown below. When pressing the button located on the left a
message box is displayed in the middle of the screen.

1.4
ProcessView - Functionality

Figure 1.3. Displaying a message to the operator

1.5 Reading the value of a variable


The example covers the following topics:
• Creating a VBA program attached to a button.
• Displaying messages using the MsgBox function.
• Accessing an OPC variable or ProcessView local variable to read its value.

The example:
To be able to change the values of OPC tags and ProcessView local variables, data will have to be
exchanged between the VBA program and the variables (OPC or ProcessView Internal). Due to the
object oriented structure of ProcessView is very easy to read data into the VBA program where it can
then be used as desired.
Use the following steps to create a button and the code behind it to read and display the value of a
ProcessView variable.
1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "ReadingValue" as the Script Name and press the OK button
5. Press the Edit Button to open the VBA Editor
6. Type in the following lines of the code in the module GwxReadingValue_Main:

Sub ReadingValue(o As GwxPick)


Dim MyPoint As GwxPoint
Set MyPoint = _
ThisDisplay.GetPointObjectFromName("~~setenablecooling~~")
MsgBox MyPoint.Value
Set MyPoint = Nothing
End Sub

1.5
ProcessView - VBA Tutorial

7. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
8. Use the property page to change the text on the button to "Read Value"

How the VBA program works:


The Dim command makes it possible to define variables. In this case it is used to define a variable
called MyPoint of the (object) type GwxPoint.
After that the variable MyPoint gets an object assigned to it coming from the display. It is searched for
using the GetPointObjectFromName method that is part of the ThisDisplay object, the name of the
variable is taken from the parameter. If the point object (in this case ~~setenablecoolling~~) is found
the MyPoint object variable can be used to read and modify the parameters of the object in the screen.
In this case the Value property is read and displayed using the MsgBox function already described
before.
The figure below shows where the ~~setenablecooling~~ object and the MyPoint object variable are
located and the link between them.

Figure 1.4.The relationship between an object and an object variable

The result of adding this button is shown below. When pressing the ‘Read Value’ button a message
box is displayed in the middle of the screen displaying the current value of the variable
~~setenablecooling~~, in this case 1 because cooling is enabled (Enable Cooling = Yes):

Figure 1.5. The result of reading a variable

1.6
ProcessView - Functionality

1.6 Changing the value of a variable


The example covers the following topics:
• Creating a VBA program attached to a button.
• Entering text using the InputBox function.
• Converting text to values using the Val function
• Accessing an OPC variable or ProcessView local variable to write a value.

The example:
Besides being able to read the value of a point it is also necessary to be able to change the value of
point. Writing to a variable is very much like reading from a variable, the only difference is that instead
of assigning the value property to a local variable, you will assign a local variable, result of a formula or
constant value to the value property.

Use the following steps to create a button and the code behind it, which will allow the operator to type
in a value and write the value to a ProcessView local variable.
1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "WriteValue" as the Script Name and press the OK button
5. Press the Edit Button to open the VBA Editor
6. Type in the following lines of the code in the module GwxWriteValue_Main:

Sub WriteValue(o As GwxPick)


Dim MyPoint As GwxPoint
Dim MyValue As Integer
Dim MyStr As String
Set MyPoint = _
ThisDisplay.GetPointObjectFromName("~~setenablecooling~~")
MyStr = InputBox("Enter 0 (cooling off) or 1 (cooling on)")
MyValue = Val(MyStr)
MyPoint.Value = MyValue
Set MyPoint = Nothing
End Sub

7. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
8. Use the property page to change the text on the button to "Write"

How the VBA program works:


Three variables are defined as shown in the table below:
Variable Type Function
MyPoint GwxPoint Make a connection to a point in the display.
MyValue Integer To store values in.
MyStr String To store text in.

A link is created between the MyPoint variable and the local variable ~~setenablecooling~~, for a
description of setting up the link see reading values.
To let the operator type in a value the InputBox function is used this function displays a message to the
operator and allows the operator to type in some text. The function returns with the typed in text. The
typed in text is stored in the variable MyStr. To be able to write the typed in text to MyPoint, the text

1.7
ProcessView - VBA Tutorial

has to be converted to a value. This can be achieved with the Val function, the result of this function is
stored in the variable MyValue. The value of the MyValue variable is assigned to the Value property of
the MyPoint variable.
In the end the link between the local variable and the MyPoint variable is destroyed by assigning
Nothing to MyPoint.
The result of adding this button is shown below. When pressing the Write button an input box is
displayed in the middle of the screen in which the operator can enter a value in this case the value 0 is
entered. Pressing the OK button or the Enter will close the input box and continue with the script.

Figure 1.6.Enabling the operator to change the value of a variable

1.7 Using forms in VBA programs


The example covers the following topics:
• Creating a VBA program attached to a button.
• Creating a form with the Form Editor
• Accessing an OPC variable or ProcessView local variable to write a value.

The example:
Forms can be created to make more complex user interaction possible or to limit the operator to what
values can be chosen. In this example a form will be created that allows the operator to turn the
cooling system on or off using option buttons. Option buttons must be created in at least a set of two.
And from that set of option buttons only one option button can and will be active at any point in time. In
the example a form with two option buttons will be created, one option button for turning the cooling
system off and one option button for turning the cooling system on. There is also an OK button on the
form to close the form. When the form is closed the value selected and the option button set is written
to the ProcessView variable.
Use the following steps to create a button and the form and code behind it to have the operator choose
an option button and write the value to a ProcessView local variable.
1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
1.8
ProcessView - Functionality

3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "FormWriteValue" as the Script Name
5. Check the box "Insert a from" and press the OK button
6. Press the Edit Button to open the VBA Editor
7. In the project window double click on "GwxFormWriteValue_MainForm" this will open the user
form and the form toolbox. If the toolbox is not visible choose View  Toolbox from the menu.
The Toolbox is shown below

Figure 1.7. VBA Toolbox

Create a frame in the form, and change the Caption property to "Cooling Section" using the property
window.

Figure 1.8.Properties Page


8. In the property window the properties of the selected object in the user form will be shown.
9. Create two Option buttons in the frame, with the following properties:
Option button 1: (Name) = CoolingOn, Caption = On
Option button 2: (Name) = CoolingOff, Caption = Off
10. Create a button outside the frame with the following properties:
Button: (Name) = FormExit, Caption = Exit
11. After creating these object the form will look like the figure shown below:

Figure 1.9.Using a form in VBA

12. Double click on the Exit button to attach code to the Exit button
1.9
ProcessView - VBA Tutorial

13. Type in the following lines of the code:

Private Sub FormExit_Click()


Dim MyPoint As GwxPoint
Set MyPoint = _
ThisDisplay.GetPointObjectFromName("~~setenablecooling~~")
If CoolingOn.Value Then
MyPoint.Value = 1
Else
MyPoint.Value = 0
End If
Set MyPoint = Nothing
Unload Me
End Sub

14. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
15. Use the property page to change the text on the button to "Write Form"

How the VBA program works:


The form is automatically loaded on execution of the script. The operator can choose the state of the
cooling system and press the Exit button. Once the exit button is pressed a variable is defined:
Variable Type Function
MyPoint GwxPoint Make a connection to a point in the display.

A link is created between the MyPoint variable and the local variable ~~setenablecooling~~, for a
description of setting up the link see reading values.
Using the If statement checks which option button is active. If the On button is active the value 1 is
assigned to the Value property of the MyPoint variable otherwise the value 0 is assigned to the Value
property of the MyPoint variable.
Assigning Nothing to MyPoint destroys the link between the local variable and the MyPoint variable.
At the end the form is closed using the Unload Me command.
The result of adding this button is shown below. When pressing the Write Form button a form is
presented, to the operator in which the appropriate setting for the cooling section can be selected.
Pressing the Exit button will close the form and write the selected value to a variable in ProcessView.

1.10
ProcessView - Functionality

Figure 1.10.VBA Form in Use

1.8 Defining user functions


The example covers the following topics:
• Creating a VBA program attached to a button.
• Defining reusable functions.
• Accessing an OPC variable or ProcessView local variable to read its value.

The example:
To be able to re-use already written code it will be useful to define functions and procedures that
perform a certain task with a number of parameters given to the function or procedure. The difference
between a function and a procedure is that a function returns a certain value and a procedure does
not.
In this example a function will be defined which takes 1 parameter, a string defining a ProcessView
point name, and return the value of that point. Use the following steps to create a push button and the
function example:
1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "FunctionExample" as the Script Name and press the OK button
5. Press the Edit Button to open the VBA Editor
6. Type the following lines of the code in the module GwxFunctionExample_Main to define a
function that returns the value of a given variable based on the name of that variable:
Function Example(Name As String) As Variant
Dim MyPoint As GwxPoint
Set MyPoint = ThisDisplay.GetPointObjectFromName(Name)
Example = MyPoint.Value
End Function

1.11
ProcessView - VBA Tutorial

7. To make use of the defined function enter the following code in the module
GwxFunctionExample_Main that displays the values of two variables using the MsgBox function:
Sub FunctionExample(o As GwxPick)
MsgBox Example("~~set_furnace1~~")
MsgBox Example("~~set_furnace2~~")
End Sub

8. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
9. Use the property page to change the text on the button to "Function"

How the VBA program works: Pressing the button will call the FunctionExample code. This code
contains a reference to the Example Function that takes a string as a parameter to identify a variable
and returns the value of that variable. The value of the variable is shown using the MsgBox function.
The function Example will do the following when called:
First it defines a variable called MyPoint, after that it sets up a link to the variable specified in the Name
parameter of the function. Once the link is created the Value property can be accessed. This value
property is then assigned to the function name which means that the function has now as return value
the value of the Value property of the ProcessView variable pointed at by MyPoint.
The result of adding this button and VBA code is shown below. When pressing the Function button a
dialog box is presented in which the current temperature of furnace 1 is show, closing this box using
the OK button will show another box which displays the current temperature of furnace 2.

Figure 1.11. User Function

1.9 Entering values with a touchscreen


The example covers the following topics:
• Creating a VBA program attached to a button.
• Creating forms
• Conversion of text to values
• Using properties of GraphWorX32 object for script execution
1.12
ProcessView - Functionality

The example:
When a touchscreen is the only means of interaction between the operator and application it is not as
easy for the operator to enter setpoint as when the operator also has a keyboard.
This example will show how to define a keypad in a form and how to connect this keypad to process
points making it possible for the operator to enter values and download these values to the process
point.
Use the following steps to create a push button and the code behind it:
1. Add a process point to the screen using the toolbar or by choosing Dynamics  Intrinsics 
Process Point from the menu.
2. Enter a datasource to connect to, in this example the datasource will be ~~set_furnace1~~.
3. Press OK to leave the dialog box
4. Add a pick action to the Process Point using the toolbar or by choosing Dynamics  Actions 
Pick from the menu.
5. Change the description of the pick action to ~~ set_furnace1~~. The name of the variable that
needs to be changed is placed in the description, to make it possible to create a script that can be
used for many different variables. The script will just have to look in the description field to find
out which variable to modify.
6. Change the Action to “Run VBA Script”
7. Press the Create Button to Open the VBA Script Wizard dialog
8. Enter "KeyPad" as the Script Name
9. Check the box "Insert a form" and press the OK button
10. Press the Edit Button to open the VBA Editor
11. Enter the following code:
Public ValueStr As String
Sub KeyPad(o As GwxPick)
Dim MyPoint As GwxPoint
' Show custom form
GwxKeyPad_MainForm.Show
If Len(ValueStr) > 0 Then
Set MyPoint = ThisDisplay.GetPointObjectFromName(o.UserDescription)
MyPoint.Value = Val(ValueStr)
End If
End Sub

12. In the project window double click on "GwxKeyPad_MainForm" this will open the userform for
editing and the toolbox. If the toolbox is not visible choose View  Toolbox from the menu.
13. The following form properties will have to be set:
Form: (Name): GwxKeyPad_MainForm
Caption: KeyPad
14. The following objects will have to be created on the form (the font for all objects is Tahoma 14
Bold):
TextBox: (Name): Value
Button: (Name): Key0 Caption: 0
Button: (Name): Key1 Caption: 1
Button: (Name): Key2 Caption: 2
Button: (Name): Key3 Caption: 3
Button: (Name): Key4 Caption: 4
Button: (Name): Key5 Caption: 5
Button: (Name): Key6 Caption: 6
Button: (Name): Key7 Caption: 7
Button: (Name): Key8 Caption: 8
Button: (Name): Key9 Caption: 9
Button: (Name): BS Caption: BS
Button: (Name): Cancel Caption: Close
Button: (Name): Enter Caption: Enter
15. Place all these buttons in the form the create the following layout
1.13
ProcessView - VBA Tutorial

Figure 1.12. VBA KeyPad

16. When all objects are placed on the screen double click on the BS button and enter the following
code:
Dim UsedDot As Boolean
Private Sub BS_Click()
Dim l As Integer
l = Len(Value.Text)
If l > 1 Then
If Mid$(Value.Text, l, 1) = "." Then UsedDot = False
Value.Text = Mid$(Value.Text, 1, l - 1)
Else
Value.Text = ""
UsedDot = False
End If
End Sub

Private Sub Cancel_Click()


ValueStr = ""
Unload Me
End Sub

Private Sub dot_Click()


If Not (UsedDot) Then
Value.Text = Value.Text + "."
UsedDot = True
End If
End Sub

Private Sub Enter_Click()


ValueStr = Value.Text
Unload Me
End Sub

Private Sub Key0_Click()


Value.Text = Value.Text + "0"
End Sub

Private Sub Key1_Click()


Value.Text = Value.Text + "1"
End Sub

1.14
ProcessView - Functionality

Private Sub Key2_Click()


Value.Text = Value.Text + "2"
End Sub

Private Sub Key3_Click()


Value.Text = Value.Text + "3"
End Sub

Private Sub Key4_Click()


Value.Text = Value.Text + "4"
End Sub

Private Sub Key5_Click()


Value.Text = Value.Text + "5"
End Sub

Private Sub Key6_Click()


Value.Text = Value.Text + "6"
End Sub

Private Sub Key7_Click()


Value.Text = Value.Text + "7"
End Sub

Private Sub Key8_Click()


Value.Text = Value.Text + "8"
End Sub

Private Sub Key9_Click()


Value.Text = Value.Text + "9"
End Sub

Private Sub UserForm_Initialize()


UsedDot = False
End Sub

1.15
ProcessView - VBA Tutorial

Figure 1.13. VBA Shortcut

17. In the VBA editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32
18. To use the script on other process points repeat step 1 to 6 for the different variables. After that
enter the following script name "GwxKeyPad_Main.KeyPad" instead of pressing the Create
button. Press OK to leave the dialog box.

How the VBA program works:


During runtime when the operator presses the process point the pick action attached to the process
point will load the KeyPad form. On the KeyPad form the operator can press the different numbers or
one of the other four keys.
Pressing a number will cause the program to add the pressed number to the text in the value box.
Pressing the "BS" button will cause the program to remove the last character.
Pressing the dot "." will add a dot and will set a Boolean variable to make sure that there will be only
one dot in the value.
Pressing the Enter button will cause the system to write the contents of the Value TextBox to the public
variable called ValueStr and closes the window.
Pressing the Close button will write an empty string to the variable ValueStr and will close the window.
When the KeyPad window is closed the script will check if the ValueStr variable is empty or not. If it is
not empty it will link to the variable specified in the description of the pick action and write the entered
value to it using the Value property of the MyPoint variable.
The result of adding this pick action to a process point is shown below. When pressing one of the
process points the Keypad dialog is shown and the operator can easily enter values using the
touchscreen.

1.16
ProcessView - Functionality

Figure 1.14. VBA KeyPad in use

1.17
Chapter 2

Accessing other Applications

2.1 Introduction
To be able to integrate different applications together it must be possible to access other applications
while using an application. Specific tasks can be executed in the most efficient way because other
applications can be used to do it. Therefore, let database functions be executed by a database
application such as Access, let spreadsheet functions be executed by a spreadsheet application such
as Excel and so on.
The technology behind this functionality is called OLE Automation. Using OLE Automation and simple
VBA commands it becomes possible to access and use other applications as desired.
The easiest way of using other applications functionality is by defining an object in VBA and assigning
that object to the desired application, for example:

Dim ExcelObj As Excel.Application


Dim WBObj As Excel.Workbook
Set ExcelObj = GetObject( ,”Excel.Application”)
Set WBObj = ExcelObj.WorkBook.Open(“MyFile.XLS”)

The above code will first define two variables one of the object type Excel.Application and a second of
the type Excel.Workbook, secondly it will try to connect Excel to the first variable and then it will open a
workbook and link that to the second variable.
If successful the situation can be represented as follows:

ProcessView Excel97
VBA Work
Work Book
Book
ExcelObj

Work
WBOb Book

Figure 2.1. How ProcessView connects to Excel

This method can be used to connect to any application that supports OLE Automation. This section
shows methods of setting up connections to Excel, Access and Outlook.

2.2 Accessing another Application


The example covers the following topics:
• Creating a VBA program attached to a button.
• Accessing applications using OLE Automation.
• Changing the window-state and appearance using OLE Automation

2-1
Accessing other Applications

The example:
In this example an already running instance of Excel will be accessed, a specific workbook will be
loaded in it and once the workbook is loaded, Excel will be shown on top. To create this functionality
use the following steps:
1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "UseExcel" as the Script Name and press the OK button
5. Press the Edit Button to open the VBA Editor
6. Go to Tools  References in the menu and mark the following library: "Microsoft Excel 8.0 Object
Library" to have easy access to Excel functionality.
7. Type in the following lines of the code in the module GwxUseExcel_Main:
Sub UseExcel(o As GwxPick)
Dim ExcelObj As Application
Set ExcelObj = GetObject(, "Excel.Application")
ExcelObj.Workbooks.Open ("d:\wwsc\wwsc.xls")
ExcelObj.WindowState = xlNormal
AppActivate ExcelObj
End Sub

8. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
9. Use the property page to change the text on the button to "Use Excel"

How the VBA program works:


First a variable called ExcelObj is defined as an Application which is defined in the Microsoft Excel 8.0
Object Library therefore it is very important that this library was added to the reference list in step 6.
Once the variable is defined it can be connected to the already running Excel application using the
GetObject function. The GetObject function searches for an already active instance of Excel on the
PC.
When the link is created between the VBA program and Excel an Excel workbook can be opened
using the Workbooks.Open command. This command is not a GraphWorX32 VBA command but it is a
command that is part of Excel. However GraphWorX32 VBA is capable of using this command
because it created a link to Excel. Once the workbook is opened the Excel window is resized to the
normal size using the WindowState command.
At last Excel is brought to the foreground using the AppActivate command.
The connection link between ProcessView and Excel can be represented as shown in the figure 2.1.
The result of adding this button and VBA code is shown below. When pressing the Use Excel button
the wwsc.xls workbook is loaded and Excel is shown on top of GraphWorX32.

2-2
ProcessView - VBA Tutorial

Figure 2.2. ProcessView running an Excel worksheet

2.3 Recipes based on Excel data


The example covers the following topics:
• Creating a VBA program attached to a button.
• Accessing and using the specific functionality of applications using OLE Automation in this
example Excel will be used.
• Creating advanced forms with text-boxes, list boxes and buttons and changing values based on
user interaction.
• Retrieving data from Excel and displaying it in a form list box.

The example:
The previous example showed how to gain access to another application and make use of functions
embedded in that other application. However sometimes it is better not to confront the operator with a
different program such as Excel, because it has a different interface or because of the security holes
within it. Yet some of the functionality offered by the other program (Excel) needs to be used for the
appropriate operation of integrated application. In this case a link to the other application can be setup
but the application will never be shown, instead data from the other application can be displayed in
user defined forms. The following example shows how to retrieve data from Excel and show it in a user
defined form.
In this example different recipes are retrieved from Excel using OLE automation and presented in a
user-defined form. The operator can choose a recipe and download the values in the recipe to the
ProcessView variables. Use the following steps to create a push button and the code behind it:
1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "Recipe" as the Script Name
5. Check the box "Insert a from" and press the OK button
6. Press the Edit Button to open the VBA Editor

2-3
Accessing other Applications

7. Go to Tools  References in the menu and mark the following library: "Microsoft Excel 8.0 Object
Library" to have easy access to Excel functionality.
8. In the project window double click on "GwxRecipe_MainForm" this will open the user form and the
form toolbox. If the toolbox is not visible choose View  Toolbox from the menu.
9. The following form will have to be created:

Figure 2.3. VBA Form


10. The form it self has the following properties:
Form: (Name): GwxRecipe_MainForm
Caption: Temperature Profile Selection
11. The large box on the right is a list box and has the following property:
ListBox: (Name): Profiles
12. The buttons at the bottom have the following properties from left to right:
Button: (Name): UseExit Caption: Use & Exit
Button: (Name): NoUseExit Caption: Use Not & Exit
13. The text labels in the middle have the following properties from top to bottom
Label: (Name): Label1 Caption: Temp. Furnace 1
Label: (Name): Label2 Caption: Temp. Furnace 2
Label: (Name): Label3 Caption: Cool Down
Label: (Name): Label4 Caption: Temp. Furnace 3
Label: (Name): Label5 Caption: Temp. Furnace 4
Label: (Name): Label6 Caption: Temp. Furnace 5
14. The text entry fields on the right have the following properties from top to bottom
TextBox: (Name): Furn1
TextBox: (Name): Furn2
TextBox: (Name): Cool
TextBox: (Name): Furn3
TextBox: (Name): Furn4
TextBox: (Name): Furn5
15. Double click on the form and add the following code:
Dim WBObj As Workbook
Dim ExcelObj As Application

Private Sub UserForm_Initialize()


Dim i As Integer
Set ExcelObj = GetObject(, "Excel.Application")
Set WBObj = ExcelObj.Workbooks.Open("d:\wwsc\wwsc.xls")
For i = 5 To 13
Profiles.AddItem (WBObj.Sheets(1).Cells(i, 2).Value)
Next i
End Sub

Private Sub UserForm_Terminate()


WBObj.Close
Set WBObj = Nothing
Set ExcelObj = Nothing
End Sub

2-4
ProcessView - VBA Tutorial

16. In the project window double click on "GwxRecipe_MainForm" this will open the user form again.
17. Double click on the List box this will change the view to the code window. Enter the following
code:
Private Sub Profiles_Click()
Dim index As Integer
index = Profiles.ListIndex + 5
Furn1.Text = WBObj.Sheets(1).Cells(index, 3)
Furn2.Text = WBObj.Sheets(1).Cells(index, 4)
Cool.Text = WBObj.Sheets(1).Cells(index, 5)
Furn3.Text = WBObj.Sheets(1).Cells(index, 6)
Furn4.Text = WBObj.Sheets(1).Cells(index, 7)
Furn5.Text = WBObj.Sheets(1).Cells(index, 8)
End Sub

18. In the project window double click on "GwxRecipe_MainForm" this will open the user form again.
19. Double click on the button labeled "Use & Exit" this will change the view to the code window.
Enter the following code:
Sub SetValue(Name As String, Value As Variant)
Dim MyPoint As GwxPoint
Set MyPoint = ThisDisplay.GetPointObjectFromName(Name)
MyPoint.Value = Value
Set MyPoint = Nothing
End Sub

Private Sub UseExit_Click()


Call SetValue("~~set_furnace1~~", Val(Furn1.Text))
Call SetValue("~~set_furnace2~~", Val(Furn2.Text))
Call SetValue("~~set_furnace3~~", Val(Furn3.Text))
Call SetValue("~~set_furnace4~~", Val(Furn4.Text))
Call SetValue("~~set_furnace5~~", Val(Furn5.Text))
Call SetValue("~~setenablecooling~~", Val(Cool.Text))
Unload Me
End Sub

20. In the project window double click on "GwxRecipe_MainForm" this will open the user form again.
21. Double click on the button labeled "Use Not & Exit" this will change the view to the code window.
Enter the following code:
Private Sub NoUseExit_Click()
Unload Me
End Sub

22. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
23. Use the property page to change the text on the button to "Recipes"

2-5
Accessing other Applications

How the VBA program works:


When the button is pressed the form is loaded. The initializing procedure takes place automatically
when loading the form. During the initialization a link to Excel is started, a specific workbook is loaded
and data from that workbook is added to the list box using the AddItem method of the list box, and the
cursor is set to the first item in the list box.
When the operator clicks on one of the profiles in the list box the text boxes on the right side of the
form are automatically updated with the data belonging to the selected profile. This data is retrieved
from Excel.
When the operator has selected a profile the form can be exited by clicking on either one of the
buttons. The "Use & Exit" button will download the currently selected profile to the variables in
ProcessView. The "Use Not & Exit" button will not download the profile to the variables in
ProcessView.
On exiting the form the workbook in Excel is closed and all links to Excel are terminated by reassigning
them to Nothing.
The VBA program makes use of the Excel workbook called wwsc.xls. This workbook has the following
data in it:

Figure 2.4. Excel workbook wwsc.xls

2-6
ProcessView - VBA Tutorial

The result of adding the Recipes button and VBA code is shown below. When pressing the Recipes
button the wwsc.xls workbook is loaded and the data from that workbook is shown in the created form.

Figure 2.5. Running the Recipe button

2.4 Recipes based on Access data


The example covers the following topics:
• Creating a VBA program attached to a button.
• Accessing and using the specific functionality of applications using OLE Automation in this
example Access will be used.
• Creating advanced forms with text-boxes, list boxes and buttons and changing values based on
user interaction.
• Retrieving data from Access and displaying it in a form list box.
• Changing and adding records in Access.
• Creating and using user defined functions

The example:
This example is very much like the previous example, only in this case data is retrieved from an
Access Database instead of an Excel spreadsheet. Besides that it is also possible to add and change
profiles (=records) whereas in the previous example this was not possible.
In this example different recipes are retrieved from Access using OLE automation and presented in a
user-defined form. The operator can either choose a recipe and download the values in the recipe to
the ProcessView variables or change/add a profile in the database. Use the following steps to create a
push button and the code behind it:
1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script

2-7
Accessing other Applications

3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "AccessRecipe" as the Script Name
5. Check the box "Insert a from" and press the OK button
6. Press the Edit Button to open the VBA Editor
7. Go to Tools  References in the menu and mark the following libraries: "Microsoft Access 8.0
Object Library" and “Microsoft DAO 3.5 Object Library” to have easy access to the Access
functionality.
8. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user form
and the form toolbox. If the toolbox is not visible choose View  Toolbox from the menu.

Figure 2.6. VBA Toolbox

9. The following form will have to be created:

Figure 2.7. Profiles Form

10. The form itself has the following properties:


Form: (Name): GwxAccessRecipe_MainForm
Caption: Profiles
11. The large box on the right is a list box and has the following property:
ListBox: (Name): Profiles
12. The text labels next to the ListBox have the following properties from top to bottom:
Label: (Name): Label1 Caption: Name
Label: (Name): Label2 Caption: Furnace 1
Label: (Name): Label3 Caption: Furnace 2
Label: (Name): Label4 Caption: Furnace 3
Label: (Name): Label5 Caption: Furnace 4
Label: (Name): Label6 Caption: Furnace 5
Label: (Name): Label7 Caption: Cool Down
13. The text entry fields in the middle have the following properties from top to bottom
TextBox: (Name): Furnace1
TextBox: (Name): Furnace2
TextBox: (Name): Furnace3
TextBox: (Name): Furnace4

2-8
ProcessView - VBA Tutorial

TextBox: (Name): Furnace5


Combobox (Name): Cooling MatchEntry: 1
14. The text labels on the right have the following properties from top to bottom:
Label: (Name): Label8 Caption: °C
Label: (Name): Label9 Caption: °C
Label: (Name): Label10 Caption: °C
Label: (Name): Label11 Caption: °C
Label: (Name): Label12 Caption: °C
15. The button on the right have the following properties from top to bottom:
Button: (Name): NewProfile Caption: Add Profile
Button: (Name): ChangeProfile Caption: Change Profile
Button: (Name): DelProfile Caption: Delete Profile
Button: (Name): UseProfile Caption: Use Profile
Button: (Name): Cancel Caption: Cancel
16. Double click on the form itself and add the following code:
Dim AccessObj As Access.Application
Dim Profdb As Database
Dim Profrec As Recordset
Private Sub UserForm_Initialize()
Set AccessObj = GetObject(, "Access.Application.8")
AccessObj.OpenCurrentDatabase ("d:\wwsc\documentation\wwsc.mdb")
Set Profdb = AccessObj.CurrentDb
Set Profrec = Profdb.OpenRecordset("Profiles")
Cooling.AddItem ("TRUE")
Cooling.AddItem ("FALSE")
Call UpDate
End Sub
Private Sub UserForm_Terminate()
Set Profdb = Nothing
Set Profrec = Nothing
AccessObj.CloseCurrentDatabase
Set AccessObj = Nothing
End Sub
Sub UpDate()
Dim i As Integer
Profiles.Clear
With Profrec
.MoveFirst
For i = 0 To .RecordCount – 1
Profiles.AddItem (.Fields(1).Value)
.MoveNext
Next i
End With
End Sub

The first three objects are defined to be able to connect to Access and the objects in Access.
The procedure UserForm_Initialize creates a connection to Access using the GetObject function.
When a link to Access is created a particular database can be opened. After that a link is setup to
the database object. When the link to the database exists a link to a particular table (Profiles) is
created with the OpenRecordSet method. Once the three links are created two items (TRUE and
FALSE) are added to the Cooling combobox.
When the procedure Update is started, this procedure will first clear the listbox on the screen,
after that it will read the records one by one in the table and add those to the profiles listbox. The

2-9
Accessing other Applications

procedure UserForm_Terminate runs when the form is closed, it closes the database and resets
the objects that are linked to Access.
17. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user form
again.
18. Double click on the listbox in the form this will open the code window again, enter the following
code here:
Private Sub Profiles_Click()
Dim i As Integer
Dim found As Boolean
Profrec.MoveFirst
found = False
For i = 0 To Profrec.RecordCount – 1
If Profrec.Fields(1).Value = Profiles.Value Then
found = True
Exit For
End If
Profrec.MoveNext
Next I
If found Then
ProfileName = Profrec.Fields(1).Value
Furnace1 = Profrec.Fields(2).Value
Furnace2 = Profrec.Fields(3).Value
Furnace3 = Profrec.Fields(4).Value
Furnace4 = Profrec.Fields(5).Value
Furnace5 = Profrec.Fields(6).Value
Cooling = Profrec.Fields(7).Value
Else
ProfileName = ""
Furnace1 = ""
Furnace2 = ""
Furnace3 = ""
Furnace4 = ""
Furnace5 = ""
Cooling = ""
End If
End Sub

This procedure tries to find the profile in the table that was clicked on in the profiles listbox. If this
record is found in the table, it displays the settings of this particular record in the form, if the
record is not found it empties the fields in the form.
19. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user form
again.
20. Double click on the “Add Profile”-button in the form this will open the code window again, enter
the following code here:
Private Sub NewProfile_Click()
With Profrec
.AddNew
!Profile = ProfileName
!Furnace1 = Furnace1
!Furnace2 = Furnace2
!Furnace3 = Furnace3
!Furnace4 = Furnace4
!Furnace5 = Furnace5
!Cooling = Cooling
.UpDate
2-10
ProcessView - VBA Tutorial

End With
Call UpDate
End Sub

This procedure uses the With statement to perform certain methods on the Profrec object. The
AddNew method adds a new record in the table. After that the different fields in the table are filled
in. To access a field in a table use the following form: tablename!fieldname. Once all the fields are
filled in the Update method is called to write the changes to the database. At the end the Update
function is called to update the listbox in the form.
21. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user form
again.
22. Double click on the “Change Profile”-button in the form this will open the code window again,
enter the following code here:
Private Sub ChangeProfile_Click()
With Profrec
.Edit
!Profile = ProfileName
!Furnace1 = Furnace1
!Furnace2 = Furnace2
!Furnace3 = Furnace3
!Furnace4 = Furnace4
!Furnace5 = Furnace5
!Cooling = Cooling
.UpDate
End With
Call UpDate
End Sub

This procedure uses the With statement to perform certain methods on the Profrec object. The
Edit method makes it possible to modify a record in the table. When the record is set into edit
mode the different fields in the table are updated. Once all the fields are filled in the Update
method is called to write the changes to the database. At the end the Update function is called to
update the listbox in the form.
23. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user form
again.
24. Double click on the “Delete Profile”-button in the form this will open the code window again, enter
the following code here:
Private Sub DelProfile_Click()
Profrec.Delete
Call UpDate
End Sub

This procedure deletes the current record and calls the Update function to update the listbox in
the form.
25. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user form
again.
26. Double click on the “Use Profile”-button in the form this will open the code window again, enter
the following code here:
Sub SetValue(Name As String, Value As Variant)
Dim MyPoint As GwxPoint
Set MyPoint = ThisDisplay.GetPointObjectFromName(Name)
MyPoint.Value = Value
Set MyPoint = Nothing
End Sub
Private Sub UseProfile_Click()
2-11
Accessing other Applications

Call SetValue("~~set_furnace1~~", Val(Furnace1.Text))


Call SetValue("~~set_furnace2~~", Val(Furnace2.Text))
Call SetValue("~~set_furnace3~~", Val(Furnace3.Text))
Call SetValue("~~set_furnace4~~", Val(Furnace4.Text))
Call SetValue("~~set_furnace5~~", Val(Furnace5.Text))
Call SetValue("~~setenablecooling~~", Val(Cooling.Text))
Unload Me
End Sub

The procedure SetValue takes two parameters, the first one is the name of a point name in
GraphWorX32 and the second one is the value that should be written to the point. The procedure
tries to find the specified name and writes the specified value to it. The procedure UseProfile calls
the SetValue procedure for each of the different points that should be written. At the end it
unloads the form (=Me).
27. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user form
again.
28. Double click on the “Cancel”-button in the form this will open the code window again, enter the
following code here:
Private Sub Cancel_Click()
Unload Me
End Sub

This procedure Unloads the current form (=Me).


29. In the VBA Editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32.
30. Use the property page to change the text on the button to "Recipe"
How the VBA program works:
When the button is pressed the form is loaded. The initializing procedure takes place automatically
when loading the form. During the initialization the links to Access are initiated, a specific database is
loaded and data from a table is added to the list box using the AddItem method of the list box, and the
cursor is set to the first item in the list box.
When the operator clicks on one of the profiles in the list box the text boxes on the right side of the
form are automatically updated with the data belonging to the selected profile. This data is retrieved
from the Access table.
Pressing the Use Profile button will download the selected profile to the GraphWorX32 variables. The
Add, Change and Delete Profile buttons make it respectively possible to add new profiles, change the
current profile and delete the current profile.
The cancel button closes the form and returns the operator to GraphWorX32.
When the form is exited, the database in Access is closed and all links to Access are terminated by
reassigning them to Nothing.
A table is present in Access that has the following settings:
Field Name DataType Description
Index AutoNumber
Profile Text Profile Name
Furnace1 Long Furnace Temperature
Furnace2 Long Furnace Temperature
Furnace3 Long Furnace Temperature
Furnace4 Long Furnace Temperature
Furnace5 Long Furnace Temperature
Cooling Yes/No Enable cooling section

2-12
ProcessView - VBA Tutorial

Figure 2.8. Profiles Access Worksheet

The result of using the Recipe button is shown below:

Figure 2.9. ProcessView running the Profiles form

2.5 Generating reports in Excel


The example covers the following topics:
• Creating a VBA program attached to a button.
• Accessing and using the specific functionality of applications using OLE Automation.
• Creating advanced forms using Visual Basic 5.0 components.
• Writing data into Excel and saving it under a specific name.

The example:
The functionality offered by Excel makes it possible to create advanced reports using some simple
VBA commands. This example creates an advanced Excel report with graphs based on an Excel
template workbook and data present in GraphWorX32.

2-13
Accessing other Applications

Use the following steps to create the script:


1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "GenerateReport" as the Script Name
5. Check the box "Insert a form" and press the OK button
6. Press the Edit Button to open the VBA Editor
7. In the project window double click on "GenerateReport_MainForm" this will open the user form
and the form toolbox. If the toolbox is not visible choose View  Toolbox from the menu. The
Toolbox is shown below

Figure 2.10. VBA Toolbox

8. Select the form and change the caption property to “Status”


9. Right mouse click on the Toolbox and choose “additional controls”
10. Mark the “Microsoft Progress Bar Control” and click OK
11. Add a label into the form with the following properties:
(name): Status
Caption: Searching Excel
Font: Tahoma 12
12. Add the progress bar into the form with the following properties:
(name): PB
13. In the end the following form is created:

Figure 2.11. Status Form

14. Double click on the form and enter the following code:

Public RunOnce As Boolean


Function ReadValue(P As String) As Variant
Dim MyPoint As GwxPoint
Set MyPoint = ThisDisplay.GetPointObjectFromName(P)
ReadValue = MyPoint.Value
End Function
Sub SetStatus(Stat As String)
Status = Stat
PB.Value = PB.Value + 10
End Sub
Private Sub UserForm_Activate()
Dim ExcelObj As Application
Dim WB As Workbook

2-14
ProcessView - VBA Tutorial

Dim FileName As String


If RunOnce Then Exit Sub
RunOnce = True
SetStatus ("Finding Excel")
Set ExcelObj = GetObject(, "Excel.Application")
SetStatus ("Opening Workbook")
Set WB =_ ExcelObj.Workbooks.Open("d:\wwsc\report_template.xls")
SetStatus ("Writing Value")
WB.Sheets(1).Cells(12, 5) = ReadValue("~~set_furnace1~~")
SetStatus ("Writing Value")
WB.Sheets(1).Cells(13, 5) = ReadValue("~~set_furnace2~~")
SetStatus ("Writing Value")
WB.Sheets(1).Cells(19, 5) = ReadValue("~~set_furnace3~~")
SetStatus ("Writing Value")
WB.Sheets(1).Cells(20, 5) = ReadValue("~~set_furnace4~~")
SetStatus ("Writing Value")
WB.Sheets(1).Cells(21, 5) = ReadValue("~~set_furnace5~~")
SetStatus ("Writing Value")
If ReadValue("~~setenablecooling~~") Then
WB.Sheets(1).Cells(16, 5) = "Yes"
Else
WB.Sheets(1).Cells(16, 5) = "No"
End If
SetStatus ("Saving file")
FileName = "SecPar" + Format$(Now(), "yymmddhhnnss")
WB.SaveAs (FileName)
SetStatus ("Closing workbook")
WB.Close
Set WB = Nothing
Set ExcelObj = Nothing
Unload Me
End Sub

Private Sub UserForm_Initialize()


RunOnce = False
End Sub

15. In the VBA editor use File  Close and Return to Gwx32 to close the menu and return to
GraphWorX32

How it works:
Once the form is opened a script is started this script connects to Excel and opens an Excel workbook.
This workbook functions as a template and the script will add the current values of 6 process points to
it. Based on these values the graph in the report will be updated. During the running of the script the
process bar is constantly updated, so the operator can see the progress of the script. Towards the end
of the script a new name for the workbook is determined based on the date and time, and using this
name the workbook is saved.

2-15
Accessing other Applications

Figure 2.12. ProcessView running the Status form


An example report is shown below:

Figure 2.13. Sample report

2-16
ProcessView - VBA Tutorial

2.6 Sending email


The example describes how to send email from GraphWorX32 using Outlook 97 and covers the
following topics:
• Creating a VBA program attached to a button.
• Accessing and using the specific functionality of applications using OLE Automation.
• Creating forms to enter user data.
• Writing an email in Outlook 97 and placing it in the Outbox folder, for further processing

The example:
The functionality offered by Outlook 97 makes it possible to create and send emails from within
GraphWorX32. In this example we will show how to enter some text in a form, create a new email and
add the entered text in the email.

Use the following steps to create the script:


1. Add a button to the screen using the toolbar or by choosing Dynamics  Intrinsics  Push-
button from the menu.
2. Change the Action to Run VBA Script
3. Press the Create Button to Open the VBA Script Wizard dialog
4. Enter "SendMail" as the Script Name
5. Check the box "Insert a form" and press the OK button
6. Press the Edit Button to open the VBA Editor
7. Go to Tools  References in the menu and mark the following library "Microsoft Outlook 8.0
Object Library"to have easy access to the Outlook functionality.
8. In the project window double click on "GwxSendMail_MainForm" this will open the user form and
the form toolbox. If the toolbox is not visible choose View  Toolbox from the menu. The Toolbox
is shown below

Figure 2.14. VBA Toolbox

9. Select the form and change the caption property to “Send an email”
10. On the form create the following objects:
Label: (Name): Label1 Caption: Send To:
Label: (Name): Label2 Caption: Message:
TextBox: (Name): SendTo
TextBox: (Name): Message Multiline: True
Button: (Name): Cancel Caption: Cancel
Button: (Name): Send Caption: Send

2-17
Accessing other Applications

11. Once all objects are created on the form the should look like the figure shown below

Figure 2.15. Send to Form

12. Double click on the “Cancel” button in the form and enter the following code:
Private Sub Cancel_Click()
Unload Me
End Sub

13. In the project window double click on "GwxSendMail_MainForm" this will open the user form and
the form toolbox.
14. Double click on the “Send” button in the form and enter the following code:

Private Sub Send_Click()


Dim OutlookObj As Outlook.Application
Dim MailObj As MailItem
Set OutlookObj = GetObject(, "Outlook.Application")
Set MailObj = OutlookObj.CreateItem(olMailItem)
MailObj.Recipients.Add SendTo.Text
MailObj.Subject = "GraphWorX32 mail message"
MailObj.Body = Message.Text
MailObj.Send
Set MailObj = Nothing
Set OutlookObj = Nothing
Unload Me
End Sub

The procedure Send first defines two objects one of the type Outlook.Application and one of the
type MailItem. After that it connects to Outlook. Using the OutlookObj a new Mail message is
created. The content of the SendTo textbox in the form is used as the recipient of the email. The
subject is set to GraphWorX32 mail message. The body text of the mail message is copied from
the Message textbox in the form. Once all properties are set, the mail is sent using the Send
method of the MailItem object. In the end both objects are set to Nothing and the form is closed
using the Unload statement.
16. In the VBA editor use File  Close and Return to Gwx32 from the menu to return to
GraphWorX32
17. Change the text of the button to “Send Mail”

How it works:
If the button is pressed the form is opened and the operator can enter an email address where the
email will be sent. The operator can also enter a text message. The operator can press either Cancel
to discard the email or Send to actually send the email.
2-18
ProcessView - VBA Tutorial

The resulting screen appears as shown below:

Figure 2.16. ProcessView running the Send to form

2-19
Accessing other Applications

2-20
Chapter 3
Accessing OPC Data via OLE Automation
3.1 Introduction
This last chapter will give an example on how an application that does not have direct access to OPC
Servers, such as ProcessView, is still able to read data from OPC Servers. The example will setup the
connection from Excel but basically any program that has VBA in it for example the Office 97 products
or programming languages such as Visual Basic 5.0 can use this method of connecting to OPC
Servers. The code given in this example can be used in any program except for the last 10 lines,
because these 10 lines enter the read data into Excel.
This program example does not support automatic updates initiated from the server. The user will have
to explicitly ask for the data by running the Excel 97 macro. Of course it is possible to make it change
driver, which means that the OPC Server will inform the OPC Client (Excel in this case) when new
data has arrived, but that is outside the scope of this tutorial.

3.2 Connecting Excel to an OPC Server


The example shows how to connect Excel to an OPC Server using OLE Automation and covers the
following topics:
• Creating a VBA program attached in another application (Excel 97)
• Accessing an OPC Server using OLE Automation
• Defining OPC Server objects
• Defining OPC Groups
• Defining OPC Tags
• Reading OPC values
• Attaching the VBA script to an Excel object.
• Modifying Excels properties from the VBA script.
The example:
Using OLE Automation it is possible for programs that have Visual Basic for Applications built in to
connect to OPC Servers. In this example Excels VBA will be used to connect to an OPC Server, read
the data from that OPC server and display it in an Excel sheet.
Type the following script in Excel to setup communication with the OPC Server. In this case the
ProcessView OPC Server is connected to, but basically any OPC Server with automation interface can
be used. The script is assigned to the SMAR Logo so whenever you click on the logo the script is
executed and the latest values are read.

Sub GenerateReport()
' Define variables
Dim OPCServer As IOPCServerDisp
Dim OPCItemMgt As IOPCItemMgtDisp
Dim OPCItem As IOPCItemDisp
Dim Updaterate As Long
Dim ServerHdl As Long
Dim ItemIDs(50) As String
Dim AccessPaths(50) As String
Dim ServerHandles As Variant
Dim Active(50) As Boolean
Dim Sections As Integer
Dim Units As Integer
Dim ClientHandles(50) As Long
Dim I As Integer
Dim j As Integer
Dim ItemObjects As Variant
Dim Errors As Variant

3.1
ProcessView VBA Tutorial

Dim Values As Variant


Dim io As IOPCSyncIODisp

' Create link to OPC Server


Set OPCServer = CreateObject("SMAR.GenOPCAuto")
If TypeName(OPCServer) = TypeName(Nothing) Then
MsgBox "Server could not be accessed"
Return 'no server
End If

' Create a Group


Updaterate = 500
Set OPCItemMgt = OPCServer.AddGroup("Excel", True, Updaterate, 22, _
1, 0, ServerHdl, Updaterate)
If TypeName(OPCItemMgt) = TypeName(Nothing) Then
MsgBox "OPC Group could not be created"
Return 'no group
End If
' prepare the items
For Sections = 1 To 3
For Units = 1 To 4
i = (Sections - 1) * 4 * 3 + (Units - 1) * 3
Active(i) = True
ClientHandles(i) = i
AccessPaths(i) = ""
ItemIDs(i) = "[SCR].Plant1.Section" + Format$(Sections) + _
".Unit" + Format$(Units) + ".C2H4"
Active(i + 1) = True
ClientHandles(i + 1) = i
AccessPaths(i + 1) = ""
ItemIDs(i + 1) = "[SCR].Plant1.Section" + Format$(Sections) + _
".Unit" + Format$(Units) + ".C2H6"
Active(i + 2) = True
ClientHandles(i + 2) = i
AccessPaths(i + 2) = ""
ItemIDs(i + 2) = "[SCR].Plant1.Section" + Format$(Sections) + _
".Unit" + Format$(Units) + ".C3H8"
Next Units
Next Sections
' Add the items
OPCItemMgt.AddItems 36, ItemIDs, Active, ClientHandles, ServerHandles, Errors,
ItemObjects, AccessPaths

' Read the values


Set io = OPCItemMgt
io.OPCRead 1, 36, ServerHandles, Values

' remove links to group and opc server


Call OPCItemMgt.RemoveItems(36, ServerHandles, Errors, True)
Call OPCServer.RemoveGroup(ServerHdl, True)
Set OPCServer = Nothing
Set OPCItemMgt = Nothing

' Enter the values into the spreadsheet


For Sections = 1 To 3
For Units = 1 To 4
i = (Sections - 1) * 4 * 3 + (Units - 1) * 3
3.2
Accessing OPC Data via OLE Automation

j = Sections * 7 + Units + 3
Sheets(1).Cells(j, 5).Value = Values(i)
Sheets(1).Cells(j, 6).Value = Values(i + 1)
Sheets(1).Cells(j, 7).Value = Values(i + 2)
Next Units
Next Sections
End Sub
How the VBA program works:
First the program creates an OPC Server object using the CreateObject function. The CreateObject
function takes the name of an OPC Server Automation Interface as the only parameter.
When the OPC Server object is created the program adds a group to it with an update rate of 500 ms.
Once the group is created the different point names are prepared and the different parameters
belonging to the points are set as well. All this information is stored in the following arrays
• ItemIDs contains the names of the points
• Active contains whether or not the points are active, in this example they are always True
• AccessPaths contains the accesspath to the point in this example always ""
• ClientHandles contains the handles associated with the points.

When the points are prepared they are added to the group. After that the values are read and then
stored in the Values array. When the values are read all points are removed, the group is deleted, and
the connection with the OPC Server is terminated. At last the values are written into the Excel
spreadsheet.

Figure 3.1. Excel Report


3.3
ProcessView VBA Tutorial

Notes:

3.4

Das könnte Ihnen auch gefallen