49
- VBA TUTORIAL INSTALLATIONAND OPERATION MANUAL PROCESS VIEW VBA TUTORIAL FIRST IN FIELDBUS FIRST IN FIELDBUS smar PVI EWTUTME PROCESS VIEW VBA TUTORIAL JUN / 02 VERSION 6.0 FOUNDATION TM

PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

  • Upload
    donhi

  • View
    240

  • Download
    2

Embed Size (px)

Citation preview

Page 1: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

-V

BA

TU

TO

RIA

L INSTALLATION AND OPERATION MANUAL

PROCESS VIEW

VBA TUTORIAL

FIR

ST

INF

IEL

DB

US

FIR

ST

INF

IEL

DB

US

sm

ar

P V I E W T U T M E

PROCESS VIEW

VBA TUTORIAL

JUN / 02

VERSION 6.0

FOUNDATION

TM

Page 2: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

web: www.smar.com e-mail: [email protected] Specifications and information are subject to change without notice.

BRAZILSmar Equipamentos Ind. Ltda.Rua Dr. Antonio Furlan Jr., 1028Sertãozinho - SP 14170-480Tel.: +55 16 645-6455Fax: +55 16 645-6450e-mail: [email protected]

ARGENTINASmar ArgentinaSoldado de La Independencia, 1259(1429) Capital Federal – ArgentinaTelefax: 00 (5411) 4776-1300 / 3131e-mail: [email protected]

CHINASmar China Corp.3 Baishiqiao Road, Suite 30233Beijing 100873, P.R.C.Tel.: +86 10 6849-8643Fax: +86-10-6894-0898e-mail: [email protected]

FRANCESmar France S. A. R. L.42, rue du Pavé des GardesF-92370 ChavilleTel.: +33 1 41 15-0220Fax: +33 1 41 15-0219e-mail: [email protected]

GERMANYSmar GmbHRheingaustrasse 955545 Bad KreuznachGermanyTel: + 49 671-794680Fax: + 49 671-7946829e-mail: [email protected]

MEXICOSmar MéxicoCerro de las Campanas #3 desp 119Col. San Andrés AtencoTlalnepantla Edo. Del Méx - C.P. 54040Tel.: +53 78 46 00 al 02Fax: +53 78 46 03e-mail: [email protected]

SINGAPORESmar Singapore Pte. Ltd.315 Outram Road#06-07, Tan Boon Liat BuildingSingapore 169074Tel.: +65 6324-0182Fax: +65 6324-0183e-mail: [email protected]

USASmar International Corporation6001 Stonington Street, Suite 100Houston, TX 77040Tel.: +1 713 849-2021Fax: +1 713 849-2022e-mail: [email protected]

Smar Laboratories Corporation10960 Millridge North, Suite 107Houston, TX 77070Tel.: +1 281 807-1501Fax: +1 281 807-1506e-mail: [email protected]

Smar Research Corporation4250 Veterans Memorial Hwy.Suite 156Holbrook , NY 11741Tel: +1-631-737-3111Fax: +1-631-737-3892e-mail: [email protected]

Page 3: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

© ICONICS, Inc., 2000GraphWorX32 , 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, Windows2000, Visual Basic, Visual Basic for Applications (VBA), and the MicrosoftVisual Basic logo, ActiveX are either registered trademarks or trademarks ofMicrosoft 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 thisguide are subject to change without notice.

Page 4: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation
Page 5: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Index

III

Contents

Introduction - About this Guide ...................................................................... VIntroduction............................................................................................................................... VStep One – A Display............................................................................................................... V

1. ProcessView Functionality........................................................................1-11.1 Introduction...................................................................................................................... 1-11.2 The Programming Environment ...................................................................................... 1-11.3 VBA Basics...................................................................................................................... 1-3

1.3.1 Procedures and Functions ...................................................................................... 1-31.3.2. Declaring variables ................................................................................................ 1-31.3.3. Assigning values .................................................................................................... 1-4

1.4 Displaying messages to the operator.............................................................................. 1-41.5 Reading the value of a variable....................................................................................... 1-51.6 Changing the value of a variable..................................................................................... 1-71.7 Using forms in VBA programs......................................................................................... 1-81.8 Defining user functions.................................................................................................. 1-111.9 Entering values with a touchscreen .............................................................................. 1-12

2. Accessing other Applications...................................................................2-12.1 Introduction...................................................................................................................... 2-12.2 Accessing another Application........................................................................................ 2-22.3 Recipes based on Excel data.......................................................................................... 2-32.4 Recipes based on Access data....................................................................................... 2-72.5 Generating reports in Excel........................................................................................... 2-132.6 Sending email................................................................................................................ 2-17

3. Accessing OPC Data via OLE Automation ..............................................3-13.1 Introduction...................................................................................................................... 3-13.2 Connecting Excel to an OPC Server............................................................................... 3-1

Page 6: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Process View VBA Tutorial

IV

Notes:

Page 7: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Introduction

V

About this Guide1.1 Introduction

Welcome to the ProcessView VBA Tutorial. This tutorial explains how to use Visual Basic forApplications as it is implemented in ProcessView (GraphWorX32). Using step by step examples thistutorial will show the almost unlimited possibilities of Visual Basic for Applications for new andexperienced 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 FunctionalityThe first section covers the programming environment and the ProcessView functionality that can beused for operations in GraphWorX32, TrendWorX32, AlarmWorX32 or the objects inside one of theseapplications.

• Accessing Other ApplicationsThe second section covers methods of accessing other applications using OLE Automation. Examplesinclude reporting with Excel, making recipes in Access and sending email.

• Accessing OPC Data via OLE AutomationThe third and last section explains how to connect to the Automation DLL of an OPC Server from aVB(A) engine. Many products might have VBA functionality, but only very few besides the SMARproducts actually include easy to use OPC capabilities. Therefore an example is included that makes itpossible to access OPC data from Excel using the Automation DLL of the OPC Server.

1.2 Step One – A DisplayA sample display (base.gdf) has been created and should be used to execute the examples in thistutorial. This display shows a part of a plant that is used to harden metal. To harden metal, the metal isfirst heated in the furnaces 1 and 2, after that it is cooled down using a fluid. When material leaves thecool 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 thescreen the parameters of the different sections can be filled in using data entry fields.

Page 8: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Process View VBA Tutorial

VI

Figure 1. - Sample display file: base.gdf

Page 9: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Section 1

1.1

ProcessView Functionality1.1 Introduction

This section covers the ProcessView functions, including GraphWorX32, TrendWorX32 andAlarmWorX32 functions.

The different functions of an application can easily be accessed from within the application itself. Forexample in GraphWorX32 starting at the ThisDisplay object any GraphWorX32 method or property canbe accessed. From this object either direct access to a property is provided, or if the property belongsto 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 toprogram.

Once familiar with the programming environment the programming can start. In this section thefollowing 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 EnvironmentThe Visual Basic for Applications programming environment is a so-called integrated developmentenvironment. It is build up out of different parts as shown below.

Page 10: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.2

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 theprojects are shown. Usually the following three folders are present: GWX32 Objects, containing allGraphWorX32 objects, in this case the ThisDisplay object; Forms, which contains all defined formsand Modules that contains all defined code modules. There is also a fourth folder possible that willcontain 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 toolboxshown next to it. This toolbox contains by default about 15 component that can be used to createforms, but it is also possible to add more components. VB 5.0 components as well as any ActiveXcontrol can be used in addition to VBA components.

• The code window: In the code window, the actual coding takes places and the different functionsand procedures are displayed. Different functions and or procedures can be selected from the twopull 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 valuewhile running the code.

• The last window is the property window (View � Properties Window): This window shows theproperties of a module or function when the code window is active. It can also show the propertiesof 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 quiteuseful:

• The Object Browser (View � Object Browser): In the object browser all methods and propertiesbelonging to a particular library can be viewed.

• The References Windows (Tools � References): In the references-window, the currently usedreferences can be viewed. Additionally, it is possible to add references to the VBA project. Addingadditional references increases the functionality of the VBA project.

Page 11: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.3

1.3 VBA BasicsThis section will only give a short introduction to some of the many possibilities and options that VisualBasic for Applications offers. Only the most basic topics like procedures and functions, declaringvariables and assigning values will be covered.

1.3.1. Procedures and FunctionsA program can be built out of one or more parts. Such a program part can either be a function or aprocedure. 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 thefunction 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 variablecould be used as long as it is the same type as the return value of the function.

1.3.2. Declaring variablesIn the previous section the name variable was already mentioned. A variable is an object in which avalue can be stored. In almost any VBA program developed variables will be used. A variable caneither be defined inside a procedure or function using the Dim statement or outside the proceduresand functions using the Dim or Public statements. If a variable is defined within a procedure orfunction with the Dim statement it can be used within that procedure or function. If a variable is definedwith a Dim statement outside the function or procedure all functions and procedures in the module canuse the variable. If the variable is defined with Public all functions and procedures in all the modulescan use the variable.

Page 12: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.4

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 IntegerPublic Var2 As VariantDim ExcelObj As Excel.Application

1.3.3. Assigning valuesDepending on the type of variable a value will either be assigned directly using the = characterotherwise the set name = object format must be used. The first format is used for normal values suchas integers, doubles and variants, while the second format is used for objects. Examples:

Var_1 = 15Var_2 = 89.4345Set ExcelObj = CreateObject(“Excel.Application”)

1.4 Displaying messages to the operatorThe 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 theoperator 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 VBAcode behind it:

1. Add a button to the screen using the toolbar or by choosing Dynamics � Intrinsics � Push-buttonfrom the menu.

2. Change the Action to Run VBA Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "HeatingHelp" as the Script Name and press the OK button5. Press the Edit Button to open the VBA Editor6. 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 thescript, as a parameter.

7. In the VBA Editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32.

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 amessage box is displayed in the middle of the screen.

Page 13: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.5

Figure 1.3. Displaying a message to the operator

1.5 Reading the value of a variableThe 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 beexchanged between the VBA program and the variables (OPC or ProcessView Internal). Due to theobject oriented structure of ProcessView is very easy to read data into the VBA program where it canthen be used as desired.

Use the following steps to create a button and the code behind it to read and display the value of aProcessView 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 Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "ReadingValue" as the Script Name and press the OK button5. Press the Edit Button to open the VBA Editor6. 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 = NothingEnd Sub

Page 14: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.6

7. In the VBA Editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32.

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 variablecalled MyPoint of the (object) type GwxPoint.

After that the variable MyPoint gets an object assigned to it coming from the display. It is searched forusing the GetPointObjectFromName method that is part of the ThisDisplay object, the name of thevariable is taken from the parameter. If the point object (in this case ~~setenablecoolling~~) is foundthe 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 describedbefore.

The figure below shows where the ~~setenablecooling~~ object and the MyPoint object variable arelocated 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 messagebox 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

Page 15: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.7

1.6 Changing the value of a variableThe 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 ofpoint. Writing to a variable is very much like reading from a variable, the only difference is that insteadof assigning the value property to a local variable, you will assign a local variable, result of a formula orconstant value to the value property.

Use the following steps to create a button and the code behind it, which will allow the operator to typein 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 Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "WriteValue" as the Script Name and press the OK button5. Press the Edit Button to open the VBA Editor6. 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 = NothingEnd Sub

7. In the VBA Editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32.

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 adescription 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 theoperator and allows the operator to type in some text. The function returns with the typed in text. Thetyped in text is stored in the variable MyStr. To be able to write the typed in text to MyPoint, the text

Page 16: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.8

has to be converted to a value. This can be achieved with the Val function, the result of this function isstored in the variable MyValue. The value of the MyValue variable is assigned to the Value property ofthe MyPoint variable.

In the end the link between the local variable and the MyPoint variable is destroyed by assigningNothing to MyPoint.

The result of adding this button is shown below. When pressing the Write button an input box isdisplayed in the middle of the screen in which the operator can enter a value in this case the value 0 isentered. 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 programsThe 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 whatvalues can be chosen. In this example a form will be created that allows the operator to turn thecooling 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. Inthe example a form with two option buttons will be created, one option button for turning the coolingsystem off and one option button for turning the cooling system on. There is also an OK button on theform to close the form. When the form is closed the value selected and the option button set is writtento the ProcessView variable.

Use the following steps to create a button and the form and code behind it to have the operator choosean 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

Page 17: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.9

3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "FormWriteValue" as the Script Name5. Check the box "Insert a from" and press the OK button6. Press the Edit Button to open the VBA Editor7. 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 propertywindow.

Figure 1.8.Properties Page8. 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 = OnOption 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

Page 18: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.10

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 MeEnd Sub

14. In the VBA Editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32.

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 thecooling 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 adescription 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 isassigned to the Value property of the MyPoint variable otherwise the value 0 is assigned to the Valueproperty 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 ispresented, 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.

Page 19: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.11

Figure 1.10.VBA Form in Use

1.8 Defining user functionsThe 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 thatperform a certain task with a number of parameters given to the function or procedure. The differencebetween a function and a procedure is that a function returns a certain value and a procedure doesnot.

In this example a function will be defined which takes 1 parameter, a string defining a ProcessViewpoint name, and return the value of that point. Use the following steps to create a push button and thefunction 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 Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "FunctionExample" as the Script Name and press the OK button5. Press the Edit Button to open the VBA Editor6. 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.ValueEnd Function

Page 20: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.12

7. To make use of the defined function enter the following code in the moduleGwxFunctionExample_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 toGraphWorX32.

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 codecontains a reference to the Example Function that takes a string as a parameter to identify a variableand 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 Nameparameter of the function. Once the link is created the Value property can be accessed. This valueproperty is then assigned to the function name which means that the function has now as return valuethe 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 adialog box is presented in which the current temperature of furnace 1 is show, closing this box usingthe 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 touchscreenThe 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

Page 21: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.13

The example:

When a touchscreen is the only means of interaction between the operator and application it is not aseasy 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 processpoints making it possible for the operator to enter values and download these values to the processpoint.

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 box4. 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 beused for many different variables. The script will just have to look in the description field to findout which variable to modify.

6. Change the Action to “Run VBA Script”7. Press the Create Button to Open the VBA Script Wizard dialog8. Enter "KeyPad" as the Script Name9. Check the box "Insert a form" and press the OK button10. Press the Edit Button to open the VBA Editor11. Enter the following code:

Public ValueStr As StringSub 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 IfEnd Sub

12. In the project window double click on "GwxKeyPad_MainForm" this will open the userform forediting 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: KeyPad14. The following objects will have to be created on the form (the font for all objects is Tahoma 14

Bold):TextBox: (Name): ValueButton: (Name): Key0 Caption: 0Button: (Name): Key1 Caption: 1Button: (Name): Key2 Caption: 2Button: (Name): Key3 Caption: 3Button: (Name): Key4 Caption: 4Button: (Name): Key5 Caption: 5Button: (Name): Key6 Caption: 6Button: (Name): Key7 Caption: 7Button: (Name): Key8 Caption: 8Button: (Name): Key9 Caption: 9Button: (Name): BS Caption: BSButton: (Name): Cancel Caption: CloseButton: (Name): Enter Caption: Enter

15. Place all these buttons in the form the create the following layout

Page 22: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.14

Figure 1.12. VBA KeyPad

16. When all objects are placed on the screen double click on the BS button and enter the followingcode:

Dim UsedDot As BooleanPrivate 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 IfEnd Sub

Private Sub Cancel_Click() ValueStr = "" Unload MeEnd Sub

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

Private Sub Enter_Click() ValueStr = Value.Text Unload MeEnd Sub

Private Sub Key0_Click() Value.Text = Value.Text + "0"End Sub

Private Sub Key1_Click() Value.Text = Value.Text + "1"End Sub

Page 23: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.15

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 = FalseEnd Sub

Page 24: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

1.16

Figure 1.13. VBA Shortcut

17. In the VBA editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32

18. To use the script on other process points repeat step 1 to 6 for the different variables. After thatenter the following script name "GwxKeyPad_Main.KeyPad" instead of pressing the Createbutton. 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 processpoint will load the KeyPad form. On the KeyPad form the operator can press the different numbers orone 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 onlyone dot in the value.

Pressing the Enter button will cause the system to write the contents of the Value TextBox to the publicvariable 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 isnot empty it will link to the variable specified in the description of the pick action and write the enteredvalue 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 theprocess points the Keypad dialog is shown and the operator can easily enter values using thetouchscreen.

Page 25: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - Functionality

1.17

Figure 1.14. VBA KeyPad in use

Page 26: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Chapter 2

2-1

Accessing other Applications

2.1 IntroductionTo be able to integrate different applications together it must be possible to access other applicationswhile using an application. Specific tasks can be executed in the most efficient way because otherapplications can be used to do it. Therefore, let database functions be executed by a databaseapplication such as Access, let spreadsheet functions be executed by a spreadsheet application suchas Excel and so on.

The technology behind this functionality is called OLE Automation. Using OLE Automation and simpleVBA 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 assigningthat object to the desired application, for example:

Dim ExcelObj As Excel.ApplicationDim WBObj As Excel.WorkbookSet 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 ofthe type Excel.Workbook, secondly it will try to connect Excel to the first variable and then it will open aworkbook and link that to the second variable.

If successful the situation can be represented as follows:

Figure 2.1. How ProcessView connects to Excel

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

2.2 Accessing another ApplicationThe 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

ProcessView Excel97

VBA WorkBook

WorkBook

WorkBook

ExcelObj

WBOb

Page 27: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-2

The example:

In this example an already running instance of Excel will be accessed, a specific workbook will beloaded in it and once the workbook is loaded, Excel will be shown on top. To create this functionalityuse 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 Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "UseExcel" as the Script Name and press the OK button5. Press the Edit Button to open the VBA Editor6. 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 ExcelObjEnd Sub

8. In the VBA Editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32.

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.0Object 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 theGetObject function. The GetObject function searches for an already active instance of Excel on thePC.

When the link is created between the VBA program and Excel an Excel workbook can be openedusing the Workbooks.Open command. This command is not a GraphWorX32 VBA command but it is acommand that is part of Excel. However GraphWorX32 VBA is capable of using this commandbecause it created a link to Excel. Once the workbook is opened the Excel window is resized to thenormal 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 buttonthe wwsc.xls workbook is loaded and Excel is shown on top of GraphWorX32.

Page 28: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-3

Figure 2.2. ProcessView running an Excel worksheet

2.3 Recipes based on Excel dataThe 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 functionsembedded in that other application. However sometimes it is better not to confront the operator with adifferent program such as Excel, because it has a different interface or because of the security holeswithin it. Yet some of the functionality offered by the other program (Excel) needs to be used for theappropriate operation of integrated application. In this case a link to the other application can be setupbut the application will never be shown, instead data from the other application can be displayed inuser defined forms. The following example shows how to retrieve data from Excel and show it in a userdefined form.

In this example different recipes are retrieved from Excel using OLE automation and presented in auser-defined form. The operator can choose a recipe and download the values in the recipe to theProcessView 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 Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "Recipe" as the Script Name5. Check the box "Insert a from" and press the OK button6. Press the Edit Button to open the VBA Editor

Page 29: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-4

7. Go to Tools � References in the menu and mark the following library: "Microsoft Excel 8.0 ObjectLibrary" to have easy access to Excel functionality.

8. In the project window double click on "GwxRecipe_MainForm" this will open the user form and theform 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 & ExitButton: (Name): NoUseExit Caption: Use Not & Exit

13. The text labels in the middle have the following properties from top to bottomLabel: (Name): Label1 Caption: Temp. Furnace 1Label: (Name): Label2 Caption: Temp. Furnace 2Label: (Name): Label3 Caption: Cool DownLabel: (Name): Label4 Caption: Temp. Furnace 3Label: (Name): Label5 Caption: Temp. Furnace 4Label: (Name): Label6 Caption: Temp. Furnace 5

14. The text entry fields on the right have the following properties from top to bottomTextBox: (Name): Furn1TextBox: (Name): Furn2TextBox: (Name): CoolTextBox: (Name): Furn3TextBox: (Name): Furn4TextBox: (Name): Furn5

15. Double click on the form and add the following code:

Dim WBObj As WorkbookDim 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 iEnd Sub

Private Sub UserForm_Terminate() WBObj.Close Set WBObj = Nothing Set ExcelObj = NothingEnd Sub

Page 30: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-5

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 followingcode:

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 = NothingEnd 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 MeEnd 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 MeEnd Sub

22. In the VBA Editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32.

23. Use the property page to change the text on the button to "Recipes"

Page 31: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-6

How the VBA program works:

When the button is pressed the form is loaded. The initializing procedure takes place automaticallywhen loading the form. During the initialization a link to Excel is started, a specific workbook is loadedand data from that workbook is added to the list box using the AddItem method of the list box, and thecursor 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 theform are automatically updated with the data belonging to the selected profile. This data is retrievedfrom Excel.

When the operator has selected a profile the form can be exited by clicking on either one of thebuttons. The "Use & Exit" button will download the currently selected profile to the variables inProcessView. The "Use Not & Exit" button will not download the profile to the variables inProcessView.

On exiting the form the workbook in Excel is closed and all links to Excel are terminated by reassigningthem to Nothing.

The VBA program makes use of the Excel workbook called wwsc.xls. This workbook has the followingdata in it:

Figure 2.4. Excel workbook wwsc.xls

Page 32: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-7

The result of adding the Recipes button and VBA code is shown below. When pressing the Recipesbutton 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 dataThe 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 anAccess Database instead of an Excel spreadsheet. Besides that it is also possible to add and changeprofiles (=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 auser-defined form. The operator can either choose a recipe and download the values in the recipe tothe ProcessView variables or change/add a profile in the database. Use the following steps to create apush 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

Page 33: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-8

3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "AccessRecipe" as the Script Name5. Check the box "Insert a from" and press the OK button6. Press the Edit Button to open the VBA Editor7. 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 Accessfunctionality.

8. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user formand 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: NameLabel: (Name): Label2 Caption: Furnace 1Label: (Name): Label3 Caption: Furnace 2Label: (Name): Label4 Caption: Furnace 3Label: (Name): Label5 Caption: Furnace 4Label: (Name): Label6 Caption: Furnace 5Label: (Name): Label7 Caption: Cool Down

13. The text entry fields in the middle have the following properties from top to bottomTextBox: (Name): Furnace1TextBox: (Name): Furnace2 TextBox: (Name): Furnace3TextBox: (Name): Furnace4

Page 34: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-9

TextBox: (Name): Furnace5Combobox(Name): Cooling MatchEntry: 1

14. The text labels on the right have the following properties from top to bottom:Label: (Name): Label8 Caption: °CLabel: (Name): Label9 Caption: °CLabel: (Name): Label10 Caption: °CLabel: (Name): Label11 Caption: °CLabel: (Name): Label12 Caption: °C

15. The button on the right have the following properties from top to bottom:Button: (Name): NewProfile Caption: Add ProfileButton: (Name): ChangeProfile Caption: Change ProfileButton: (Name): DelProfile Caption: Delete ProfileButton: (Name): UseProfile Caption: Use ProfileButton: (Name): Cancel Caption: Cancel

16. Double click on the form itself and add the following code:

Dim AccessObj As Access.ApplicationDim Profdb As DatabaseDim Profrec As RecordsetPrivate 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 UpDateEnd SubPrivate Sub UserForm_Terminate() Set Profdb = Nothing Set Profrec = Nothing AccessObj.CloseCurrentDatabase Set AccessObj = NothingEnd SubSub 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 WithEnd 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 tothe database object. When the link to the database exists a link to a particular table (Profiles) iscreated with the OpenRecordSet method. Once the three links are created two items (TRUE andFALSE) 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

Page 35: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-10

procedure UserForm_Terminate runs when the form is closed, it closes the database and resetsthe objects that are linked to Access.

17. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user formagain.

18. Double click on the listbox in the form this will open the code window again, enter the followingcode 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 IfEnd Sub

This procedure tries to find the profile in the table that was clicked on in the profiles listbox. If thisrecord is found in the table, it displays the settings of this particular record in the form, if therecord 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 formagain.

20. Double click on the “Add Profile”-button in the form this will open the code window again, enterthe 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

Page 36: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-11

End With Call UpDateEnd Sub

This procedure uses the With statement to perform certain methods on the Profrec object. TheAddNew method adds a new record in the table. After that the different fields in the table are filledin. To access a field in a table use the following form: tablename!fieldname. Once all the fields arefilled in the Update method is called to write the changes to the database. At the end the Updatefunction is called to update the listbox in the form.

21. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user formagain.

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 UpDateEnd Sub

This procedure uses the With statement to perform certain methods on the Profrec object. TheEdit method makes it possible to modify a record in the table. When the record is set into editmode the different fields in the table are updated. Once all the fields are filled in the Updatemethod is called to write the changes to the database. At the end the Update function is called toupdate the listbox in the form.

23. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user formagain.

24. Double click on the “Delete Profile”-button in the form this will open the code window again, enterthe following code here:Private Sub DelProfile_Click() Profrec.Delete Call UpDateEnd Sub

This procedure deletes the current record and calls the Update function to update the listbox inthe form.

25. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user formagain.

26. Double click on the “Use Profile”-button in the form this will open the code window again, enterthe 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 = NothingEnd SubPrivate Sub UseProfile_Click()

Page 37: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-12

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 MeEnd Sub

The procedure SetValue takes two parameters, the first one is the name of a point name inGraphWorX32 and the second one is the value that should be written to the point. The proceduretries to find the specified name and writes the specified value to it. The procedure UseProfile callsthe SetValue procedure for each of the different points that should be written. At the end itunloads the form (=Me).

27. In the project window double click on "GwxAccessRecipe_MainForm" this will open the user formagain.

28. Double click on the “Cancel”-button in the form this will open the code window again, enter thefollowing code here:Private Sub Cancel_Click() Unload MeEnd 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 toGraphWorX32.

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 automaticallywhen loading the form. During the initialization the links to Access are initiated, a specific database isloaded and data from a table is added to the list box using the AddItem method of the list box, and thecursor 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 theform are automatically updated with the data belonging to the selected profile. This data is retrievedfrom the Access table.

Pressing the Use Profile button will download the selected profile to the GraphWorX32 variables. TheAdd, Change and Delete Profile buttons make it respectively possible to add new profiles, change thecurrent 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 byreassigning them to Nothing.

A table is present in Access that has the following settings:

Field Name DataType DescriptionIndex AutoNumberProfile Text Profile NameFurnace1 Long Furnace TemperatureFurnace2 Long Furnace TemperatureFurnace3 Long Furnace TemperatureFurnace4 Long Furnace TemperatureFurnace5 Long Furnace TemperatureCooling Yes/No Enable cooling section

Page 38: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-13

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 ExcelThe 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 simpleVBA commands. This example creates an advanced Excel report with graphs based on an Exceltemplate workbook and data present in GraphWorX32.

Page 39: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-14

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 Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "GenerateReport" as the Script Name5. Check the box "Insert a form" and press the OK button6. Press the Edit Button to open the VBA Editor7. 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. TheToolbox 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 OK11. Add a label into the form with the following properties:

(name): StatusCaption: Searching ExcelFont: 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 BooleanFunction ReadValue(P As String) As Variant Dim MyPoint As GwxPoint Set MyPoint = ThisDisplay.GetPointObjectFromName(P) ReadValue = MyPoint.ValueEnd FunctionSub SetStatus(Stat As String) Status = Stat PB.Value = PB.Value + 10End SubPrivate Sub UserForm_Activate() Dim ExcelObj As Application Dim WB As Workbook

Page 40: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-15

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 MeEnd Sub

Private Sub UserForm_Initialize() RunOnce = FalseEnd Sub

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

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 toit. Based on these values the graph in the report will be updated. During the running of the script theprocess bar is constantly updated, so the operator can see the progress of the script. Towards the endof the script a new name for the workbook is determined based on the date and time, and using thisname the workbook is saved.

Page 41: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-16

Figure 2.12. ProcessView running the Status formAn example report is shown below:

Figure 2.13. Sample report

Page 42: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-17

2.6 Sending emailThe example describes how to send email from GraphWorX32 using Outlook 97 and covers thefollowing 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 withinGraphWorX32. In this example we will show how to enter some text in a form, create a new email andadd 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 Script3. Press the Create Button to Open the VBA Script Wizard dialog4. Enter "SendMail" as the Script Name5. Check the box "Insert a form" and press the OK button6. Press the Edit Button to open the VBA Editor7. 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 Toolboxis 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): SendToTextBox: (Name): Message Multiline: TrueButton: (Name): Cancel Caption: CancelButton: (Name): Send Caption: Send

Page 43: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-18

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 MeEnd Sub

13. In the project window double click on "GwxSendMail_MainForm" this will open the user form andthe 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 MeEnd Sub

The procedure Send first defines two objects one of the type Outlook.Application and one of thetype MailItem. After that it connects to Outlook. Using the OutlookObj a new Mail message iscreated. The content of the SendTo textbox in the form is used as the recipient of the email. Thesubject is set to GraphWorX32 mail message. The body text of the mail message is copied fromthe Message textbox in the form. Once all properties are set, the mail is sent using the Sendmethod of the MailItem object. In the end both objects are set to Nothing and the form is closedusing the Unload statement.

16. In the VBA editor use File � Close and Return to Gwx32 from the menu to return toGraphWorX32

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 theemail will be sent. The operator can also enter a text message. The operator can press either Cancelto discard the email or Send to actually send the email.

Page 44: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView - VBA Tutorial

2-19

The resulting screen appears as shown below:

Figure 2.16. ProcessView running the Send to form

Page 45: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing other Applications

2-20

Page 46: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Chapter 3

3.1

Accessing OPC Data via OLE Automation3.1 Introduction

This last chapter will give an example on how an application that does not have direct access to OPCServers, such as ProcessView, is still able to read data from OPC Servers. The example will setup theconnection from Excel but basically any program that has VBA in it for example the Office 97 productsor programming languages such as Visual Basic 5.0 can use this method of connecting to OPCServers. 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 haveto explicitly ask for the data by running the Excel 97 macro. Of course it is possible to make it changedriver, which means that the OPC Server will inform the OPC Client (Excel in this case) when newdata has arrived, but that is outside the scope of this tutorial.

3.2 Connecting Excel to an OPC ServerThe example shows how to connect Excel to an OPC Server using OLE Automation and covers thefollowing 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 toconnect to OPC Servers. In this example Excels VBA will be used to connect to an OPC Server, readthe 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 theProcessView OPC Server is connected to, but basically any OPC Server with automation interface canbe used. The script is assigned to the SMAR Logo so whenever you click on the logo the script isexecuted 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

Page 47: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView VBA Tutorial

3.2

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

Page 48: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

Accessing OPC Data via OLE Automation

3.3

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 SectionsEnd Sub

How the VBA program works:

First the program creates an OPC Server object using the CreateObject function. The CreateObjectfunction 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 parametersbelonging 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 thenstored in the Values array. When the values are read all points are removed, the group is deleted, andthe connection with the OPC Server is terminated. At last the values are written into the Excelspreadsheet.

Figure 3.1. Excel Report

Page 49: PROCESS VIEW VBA TUTORIAL - Industrial · PDF filePROCESS VIEW VBA TUTORIAL FIELDBUSFIRST IN smar FIELDBUS PVI EWTUTME ... possible to access OPC data from Excel using the Automation

ProcessView VBA Tutorial

3.4

Notes: