VBA Visual Basic for Application training

Transcription

VBA Visual Basic for Application training
VBA
Visual Basic for Application training
May 2001
OPC automation at your fingertips
VISUAL BASIC FOR APPLICATIONS TRAINING
Contents
1.1 Scope of the Document ____________________________________________ 3
1.2 Copyright and Confidentiality ______________________________________ 3
LICENSE_____________________________________________________________________
TERM _______________________________________________________________________
LIMITED WARRANTY___________________________________________________________
LIMITATION OF REMEDIES _____________________________________________________
GENERAL____________________________________________________________________
ICONICS RETURN POLICY ______________________________________________________
3
3
3
3
3
3
2.0 Introduction_______________________________________________________ 4
3.0 Starting Point _____________________________________________________ 5
4.0 Displaying Messages to the Operator _______________________________ 6
4.1 Reading the Value of a Variable_____________________________________ 7
4.2 Changing the Value of a Variable ___________________________________ 9
5.0 Using Forms in VBA Programs ____________________________________ 11
6.0 Defining User Functions __________________________________________ 14
7.0 Accessing Another Application____________________________________ 16
8.0 Recipes Based on Excel Data _____________________________________ 17
9.0 Entering Values With a Touchscreen ______________________________ 22
10.0 Connecting Excel to an OPC Server Using OLE Automation ________ 26
© Copyright 2001, ICONICS, Inc.
May 2001
2/28
VISUAL BASIC FOR APPLICATIONS TRAINING
1.1 Scope of the Document
There are no comprehensive documents available to users that address the configuration issues
and detailed methods to set up the distributed client/sever environment over DCOM.
This document is written to introduce ICONICS Representatives, Distributors, System Integrators
and Customers with this upcoming technology as well as provide training. It addresses DCOM
configuration issues on Win 95/98/NT and 2000. Reading this document will benefit the user and
help the user to configure a system in a true distributed Client/Server environment over DCOM.
1.2 Copyright and Confidentiality
The document is © Copyright 2001, Iconics, Inc., Foxborough, Massachusetts. It is considered
CONFIDENTIAL, and may contains trade secret information proprietary to Iconics, Inc. and Microsoft
Corp.
ICONICS LICENSE AGREEMENT
YOU SHOULD CAREFULLY READ THE FOLLOWING TERMS AND CONDITIONS!
Opening and using the enclosed software for any purpose indicates your acceptance of the terms and conditions of this license agreement. If you do not agree
with them you should return all software, documentation, and copy protection keys within seven days of shipment unopened and your money will be refunded.
ICONICS provides this program and licenses its use in the United States, Puerto Rico, or internationally. You assume the responsibility for the selection of the
program to achieve your intended results, and for the installation, use and results obtained from the program.
LICENSE
You are granted a personal license to use this program under the terms stated in this Agreement. You may: 1) Install and use the program on a single machine. 2)
Make archival back-up copies of the program for the sole purpose of supporting your use of the single program on a single machine. 3) You may not use, copy,
modify, or transfer the program, or transfer any copy, in whole or in part, except as expressly provided in this license, or with a written contractual agreement with
ICONICS, Inc.
TERM
The license is effective until terminated. It will terminate if you fail to comply with any term or condition of this Agreement. You agree, upon such termination, to
destroy the program and all copies which were made from it and to promptly return any copy protection key(s) to ICONICS.
LIMITED WARRANTY
ICONICS WARRANTS THE CD-ROM OR PHYSICAL DISKETTES, ON WHICH THE PROGRAM IS FURNISHED, AND PHYSICAL DOCUMENTATION TO BE
FREE OF DEFECTS IN MATERIALS AND WORKMANSHIP UNDER NORMAL USE FOR A PERIOD OF NINETY (90) DAYS FROM THE DATE OF DELIVERY
TO YOU AS EVIDENCED BY YOUR RECEIPT. THIS PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU
ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
ICONICS SPECIFICALLY DISCLAIMS ALL OTHER WARRANTIES, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO, IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN PARTICULAR, WITH RESPECT TO ANY PARTICULAR APPLICATION, USE, OR
PURPOSE, IN NO EVENT SHALL ICONICS INC. BE LIABLE FOR ANY OTHER COMMERCIAL DAMAGE, INCLUDING BUT NOT LIMITED TO SPECIAL,
INCIDENTAL, CONSEQUENTIAL OR OTHER DAMAGES. ICONICS DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE PROGRAM WILL
MEET YOUR REQUIREMENTS OR THAT THE OPERATION OF THE PROGRAM WILL BE UNINTERRUPTED OR ERROR FREE.
LIMITATION OF REMEDIES
ICONICS' ENTIRE LIABILITY AND YOUR EXCLUSIVE REMEDY SHALL BE THE REPLACEMENT OF ANY CD-ROM OR DISKETTE NOT MEETING ICONICS'
"LIMITED WARRANTY" WHICH IS RETURNED TO ICONICS WITH A COPY OF YOUR RECEIPT WITHIN THE WARRANTY PERIOD. THE REMEDY FOR
BREACH OF THIS WARRANTY SHALL BE LIMITED TO REPLACEMENT AND SHALL NOT ENCOMPASS ANY OTHER DAMAGES INCLUDING BUT NOT
LIMITED TO LOSS OF PROFIT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER SIMILAR CLAIMS ARISING OUT OF THE USE OR INABILITY TO
USE SUCH PROGRAM EVEN IF ICONICS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER THIRD
PARTY.
GENERAL
This Agreement will be governed by the laws of the Commonwealth of Massachusetts. Should you have any questions concerning this Agreement, you may
contact ICONICS in writing at:
ICONICS Inc.
100 Foxborough Blvd.
Foxborough, MA 02035
You acknowledge that you have read this agreement, understand it and agree to be bound by its terms and conditions. You further agree that it is the complete
and exclusive statement of the agreement between you and ICONICS which supersedes any proposal or prior agreement, oral or written, and any other
communications between you and ICONICS relating to the subject matter of this agreement.
ICONICS RETURN POLICY
All sales are final (NO RETURNS) unless one of the following conditions is applicable: Program is returned in its original packing material within 7 days after
shipment. In such a case, a full refund is provided, less all incurred shipping and handling costs. Program is returned within 30 days from the original shipment
date. In such a case, a 20 % restocking fee is applicable.
© Copyright 2001, ICONICS, Inc.
May 2001
3/28
VISUAL BASIC FOR APPLICATIONS TRAINING
2.0 Introduction
This Visual Basic for Application Training Class will cover the following topics:
1. Displaying messages to the operator.
2. Reading the value of a variable either coming from an OPC server or a local variable
that is already used in GraphWorX32.
3. Writing values to variables based on user input.
4. Creating user forms to write values to variables.
5. Defining user functions to simplify certain tasks.
6. Accessing other applications via OLE Automation.
7. Downloading recipes from Excel using OLE Automation and user defined forms.
8. Entering values with a touchscreen using only the keypad form.
9. Using VBA in Excel to connect to OPC Servers.
© Copyright 2001, ICONICS, Inc.
May 2001
4/28
VISUAL BASIC FOR APPLICATIONS TRAINING
3.0 Starting Point
To have a starting point from where the different actions will take place a display is
already created. This display shows a part of a plant that is used to harden metal. To
harden metal, the metal is first heated in furnaces 1 and 2, it is then cooled down using a
fluid. When material leaves the cool down section it will be heated again to re-crystallize
the material for optimal results.
The bottom 65% of the display contains a visualization of the actual process; the top
35% of the display contains the parameters of the different sections. These parameters
are data entry fields.
© Copyright 2001, ICONICS, Inc.
May 2001
5/28
VISUAL BASIC FOR APPLICATIONS TRAINING
4.0 Displaying Messages to the Operator
To advise the operator when needed a help button has to be implemented in the Heating
section of the display. When pressed this button will show the operator information on
the Heating section.
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 as Script Name "HeatingHelp" 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 takes as parameter a string that will be displayed in a dialog
box on execution of the script.
7. In the VBA Editor use File è Exit from the menu to return to GraphWorX32.
8. Change, in the property page, 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.
© Copyright 2001, ICONICS, Inc.
May 2001
6/28
VISUAL BASIC FOR APPLICATIONS TRAINING
4.1 Reading the Value of a Variable
To really unleash the power of scripting, data will have to be exchanged between the
VBA program and the variables (OPC or Genesis32 Internal). Due to the object oriented
structure of Genesis32 is very easy to read data into the VBA program and use that data
as desired.
Use the following steps to create a button, and the VBA code behind it, to read and
display the value of a Genesis32 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 as Script Name "ReadingValue" 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
7. In the VBA Editor use File è Exit from the menu to return to GraphWorX32.
8. Change, in the property page, 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 MyPoints gets an object assigned to it coming from the display.
It is searched for the GetPointObjectFromName method that is part of the Thisdisplay
object. It takes, as a parameter, the name of a variable. If the point object (in this case,
called ~~setenablecoolling~~) is found, the MyPoint object variable can be used to read
and modify the parameters of the object on the screen.
In this case the Value property is read and displayed using the MsgBox function
described earlier.
The figure below shows where the ~~setenablecooling~~ object and the MyPoint object
variable are located, and the link between them.
GraphWorX32
ThisDisplay
VBA
MyPoint
~~
setenable
cooling
~~
© Copyright 2001, ICONICS, Inc.
MyPoint
May 2001
7/28
VISUAL BASIC FOR APPLICATIONS TRAINING
The result of adding this button is shown below. When pressing the button located on
the center/left, a message box is displayed in the middle of the screen with the current
value of the variable ~~setenablecooling~~. In this case, 1, because cooling is enabled
(Enable Cooling = Yes):
© Copyright 2001, ICONICS, Inc.
May 2001
8/28
VISUAL BASIC FOR APPLICATIONS TRAINING
4.2 Changing the Value of a Variable
Besides being able to read the value of a point, it is necessary to able to change the
value of point. Writing is very much like reading; the only difference being that instead of
assigning the value property to a local variable, a local variable is assigned to the value
property.
Use the following steps to create a button, and the VBA code behind it, to give the ability
to type in a value and write that value to a Genesis32 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 as Script Name "WriteValue" 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 è Exit from the menu to return to GraphWorX32.
8. Change, in the property page, the text on the button to "Write".
How the VBA program works:
Three variables are defined: MyPoint, of the type GwxPoint, to make a connection to a
point in the display; MyValue, of the type Integer, to store values in; and, MyStr, of the
type 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 the input text. The input text is stored in the variable MyStr. To be able to write
the input text to MyPoint, the text 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.
Finally, the link between the local variable and the MyPoint variable is destroyed by
assigning Nothing to MyPoint.
© Copyright 2001, ICONICS, Inc.
May 2001
9/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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.
Pressing the OK button or the Enter will close the input box and continue with the script.
© Copyright 2001, ICONICS, Inc.
May 2001
10/28
VISUAL BASIC FOR APPLICATIONS TRAINING
5.0 Using Forms in VBA Programs
To make more complex user interaction possible, or to limit the operator as to what can
be chosen, forms are used. In this example a form will be created that allows the
operator to turn the cooling system on or off, using option buttons. When using option
buttons, at least a set of two will always have to be created. And from that set of option
buttons only one option button can and will be active at a point in time. In this example, a
form with two option buttons will be created; one option button for turning the cooling
system on and one option button for turning the cooling system off. There is also an OK
button on the form to close the form. When the form is closed the value selected in the
option button set is written to the Genesis32 variable.
Use the following steps to create the form with a button set, and the VBA code behind it,
to allow the operator to choose an option and write that value to a Genesis32 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 as Script Name "FormWriteValue".
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 "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.
8. Create, in the form, a frame. In the property window change the Caption property to
"Cooling Section".
© Copyright 2001, ICONICS, Inc.
May 2001
11/28
VISUAL BASIC FOR APPLICATIONS TRAINING
In the property window, the properties of the selected object, in the user form, will be
shown.
9. Create in the frame two Option buttons 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) = ExitForm, Caption = Exit
11. After the creating these object the form will look as shown below:
12. Double click on the Exit button attach code to the Exit button
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 è Exit from the menu to return to GraphWorX32.
15. Change, in the property page, 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 MyPoint, of the type GwxPoint, is defined to 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”.
Next, 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.
Finally, the link between the local variable and the MyPoint variable is destroyed by
assigning Nothing to MyPoint and the form is closed using the Unload Me command.
© Copyright 2001, ICONICS, Inc.
May 2001
12/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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 the Genesis32 variable.
© Copyright 2001, ICONICS, Inc.
May 2001
13/28
VISUAL BASIC FOR APPLICATIONS TRAINING
6.0 Defining User Functions
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 of 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 that takes 1 parameter, a string defining a
Genesis32 point name. The function will return the value of that point. Use the follow
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 as Script Name "FunctionExample" 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 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
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 è Exit from the menu to return to GraphWorX32.
9. Change, using the property page, the text on the button to "Function".
How the VBA program works:
Pressing the button will call function Example. This function takes a string as parameter
to identify a variable and returns the value of that variable. The value of the variable is
shown using the MsgBox function.
Specifically, it does the following:
First it defines a variable called MyPoint. Then 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. This means that
the function now has, as a return value, the value of the Genesis32 variable referred to
by MyPoint.
© Copyright 2001, ICONICS, Inc.
May 2001
14/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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 shown. After closing this box, using the OK button, another box will show the current
temperature of furnace 2.
© Copyright 2001, ICONICS, Inc.
May 2001
15/28
VISUAL BASIC FOR APPLICATIONS TRAINING
7.0 Accessing Another Application
To be able to integrate different applications together it has to be possible to get access
to other applications. This way specific tasks can be executed in the most efficient way
because other application can be used for it. That means 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 it becomes possible to access and use other applications as desired using
simple VBA commands.
In this example an already running instance of Excel will accessed, a specific workbook
will be loaded in it and once the workbook is loaded Excel 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 as Script Name "UseExcel" 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.Application.Visible = True
ExcelObj.Workbooks.Open ("d:\wwsc\wwsc.xls")
ExcelObj.WindowState = xlNormal
AppActivate ExcelObj
End Sub
8. In the VBA Editor use File è Exit from the menu to return to GraphWorX32.
9. Change, using the property page, the text on the button to "Use Excel".
How the VBA program works:
First a variable called ExcelObj is defined this variable is of the type Application this type
is defined in the Microsoft Excel 8.0 Object Library therefore this library had to be 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 is resized to the normal size using the
WindowState command.
At last Excel is brought to the foreground using the AppActivate command.
© Copyright 2001, ICONICS, Inc.
May 2001
16/28
VISUAL BASIC FOR APPLICATIONS TRAINING
The connection link between Genesis32 and Excel can be represented as shown in the
following figure:
GraphWorX32
ThisDisplay
~~
setenable
cooling
~~
Excel
VBA
ExcelObj
WorkBook
Sheet1
Sheet2
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.
8.0 Recipes Based on Excel Data
The previous example showed how to get access to other application and make use of
functions embedded in that other application. However sometimes it is better not to
confront to operator with a different program such as Excel, because it has a different
interface or because of the security holes it has. But in the meanwhile certain
functionality offered by the other program (Excel) needs to be used for the appropriate
operation of integrated application. In this case a link to 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.
© Copyright 2001, ICONICS, Inc.
May 2001
17/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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 Genesis32 variables. Use the following steps to create a push
button and the code behind it:
1.
2.
3.
4.
5.
6.
7.
8.
9.
Add a button to the screen using the toolbar or by choosing Dynamics è Intrinsics
è Push-button from the menu.
Change the Action to Run VBA Script.
Press the Create Button to Open the VBA Script Wizard dialog.
Enter as Script Name "Recipe".
Check the box "Insert a from" and press the OK button.
Press the Edit Button to open the VBA Editor.
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.
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.
The following form will have to be created:
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 from left to right the following properties:
Button:
(Name): UseExit
Caption: Use & Exit
Button:
(Name): NoUseExit Caption: Use Not & Exit
13. The text labels in the middle have from top to bottom the following properties:
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 from top to bottom the following properties:
TextBox: (Name): Furn1
TextBox: (Name): Furn2
TextBox: (Name): Cool
TextBox: (Name): Furn3
TextBox: (Name): Furn4
TextBox: (Name): Furn5
© Copyright 2001, ICONICS, Inc.
May 2001
18/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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
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
© Copyright 2001, ICONICS, Inc.
May 2001
19/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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 è Exit from the menu to return to GraphWorX32.
23. Change, using the property page, the text on the button to "Recipes".
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 initiated, a
specific workbook is loaded and data from that workbook is added to the list box using
the AddItem method of the list box. After 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 Genesis32. The "Use Not & Exit" button will not download the profile to the
variables in Genesis32.
On exiting the form the workbook in Excel is closed and all links to Excel are terminated
by reassigning them to Nothing.
© Copyright 2001, ICONICS, Inc.
May 2001
20/28
VISUAL BASIC FOR APPLICATIONS TRAINING
The VBA program makes use of the Excel workbook called wwsc.xls. This workbook has
the following data in it:
The result of adding this 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.
© Copyright 2001, ICONICS, Inc.
May 2001
21/28
VISUAL BASIC FOR APPLICATIONS TRAINING
9.0 Entering Values With a Touchscreen
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 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 as Script Name "KeyPad".
9. Check the box "Insert a from" 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
© Copyright 2001, ICONICS, Inc.
May 2001
22/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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 to create the following layout.
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
© Copyright 2001, ICONICS, Inc.
May 2001
23/28
VISUAL BASIC FOR APPLICATIONS TRAINING
Private Sub Key0_Click()
Value.Text = Value.Text + "0"
End Sub
Private Sub Key1_Click()
Value.Text = Value.Text + "1"
End Sub
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
17. In the VBA editor use File è Exit from the menu to return to GraphWorX32.
18. To use the script also 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. After that press OK to leave the dialog box.
How the VBA program works:
When during runtime to 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
on the different numbers or one of the other four keys.
© Copyright 2001, ICONICS, Inc.
May 2001
24/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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 the variable ValueStr and closes 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.
© Copyright 2001, ICONICS, Inc.
May 2001
25/28
VISUAL BASIC FOR APPLICATIONS TRAINING
10.0 Connecting Excel to an OPC Server Using OLE Automation
Using OLE Automation it is possible for programs that have Visual Basic for
Applications build 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 in the following script in Excel to be able to communicate with the OPC Server.
In this case the Genesis OPC Server is used to connect to, but basically any OPC
Server with automation interface can be used. The script is assigned to the Iconics
Europe BV 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
Dim Values As Variant
Dim io As IOPCSyncIODisp
' Create link to OPC Server
Set OPCServer = CreateObject("ICONICS.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) = ""
© Copyright 2001, ICONICS, Inc.
May 2001
26/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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
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 uses the CreateObject function. The
CreateObject function takes as only parameter the name of an OPC Server
Automation Interface.
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 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 the stored in the Values array.
© Copyright 2001, ICONICS, Inc.
May 2001
27/28
VISUAL BASIC FOR APPLICATIONS TRAINING
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.
© Copyright 2001, ICONICS, Inc.
May 2001
28/28