Programming Interfaces
Programming Interfaces
Table of contents
© 2019 ABB Oy. All rights reserved. Printed under license of Ing. Punzenberger COPA-DATA GmbH.
Distribution and/or reproduction of this document or parts thereof in any form are permitted solely with the
written permission of the company COPA-DATA. Technical data is only used for product description and are
not guaranteed qualities in the legal sense. Subject to change, technical or otherwise.
Table of contents 3
Table of contents
1 Programming Interfaces
2 Add-Ins
Prior knowledge ................................................................................... 12
Terminology ........................................................................................ 12
Limitations ......................................................................................... 13
Create add-in ...................................................................................... 13
Basics ........................................................................................... 14
Types of extensions ........................................................................... 16
Wizard in the Editor - Editor wizard extension ......................................... 16
Services in the Editor - Editor Service Extension ..................................... 17
Wizard in Runtime - project wizard extension ......................................... 17
Service in the Runtime - project service extension ................................... 18
Content of add-in packages ................................................................. 18
Microsoft Visual Studio ....................................................................... 19
ABB Developer Tools ...................................................................... 19
Create add-in package with Visual Studio ............................................. 20
Deploying and debugging add-ins ....................................................... 21
Search function and introduction to zenon API documentation ..................... 22
SharpDevelop .................................................................................. 23
Create add-in package with SharpDevelop ............................................ 23
Deploying and debugging add-ins ....................................................... 24
Source code administration .................................................................. 25
Add-in analysis and packaging utility (AddInUtility) ...................................... 25
Command line tool AddInUtility.exe ..................................................... 25
Action in the event of reloading ............................................................. 26
Isolation ......................................................................................... 26
Use of add-ins in Editor and Runtime .......................................................... 26
Activate add-ins in zenon .................................................................... 28
Action during installation ..................................................................... 28
Add-ins node in the Project Manager ................................................... 29
Add-ins node in the Project Manager ...................................................... 29
Project tree context menu ................................................................ 29
Use in the zenon Editor ....................................................................... 29
Installing and managing add-ins for the Editor ........................................ 29
Use in zenon Runtime ........................................................................ 33
Installing and manging add-ins for Runtime ........................................... 33
Troubleshooting ............................................................................... 35
zenon functions ................................................................................... 35
Display dialog "Manage Runtime services" ............................................... 35
Execute Project Wizard Extension .......................................................... 37
Switch/conversion from VSTA .................................................................. 39
3 Macro list
VBA toolbar and context menu detail view .................................................... 42
VBA on 64-bit systems ........................................................................... 43
4 Table of contents
Basics .............................................................................................. 44
Object PROPERTIES ......................................................................... 44
Object METHODS ............................................................................. 44
Object EVENTS ............................................................................... 45
VBA object structure in zenon ............................................................... 45
How to use VBA macros ..................................................................... 46
Inserting existing macros ................................................................. 48
How to insert an ActiveX element in zenon? .............................................. 48
Access from an external program ........................................................... 50
Visual Basic 6 .............................................................................. 50
Functionality of online variables ............................................................. 51
Functionality of the event: ................................................................ 51
Define and create container .............................................................. 51
Put variables in the container ............................................................ 51
Create event ................................................................................ 51
Activate event .............................................................................. 51
Switching off the event .................................................................... 52
Remove on closing ........................................................................ 52
List of status bits ............................................................................... 52
Lasso for selecting dynamic elements in the Runtime ................................... 54
Macros in the Editor .............................................................................. 55
Toolbar Macro List ............................................................................. 56
Macros allocation .............................................................................. 56
Macro selection for allocation ............................................................ 57
Macro selection for elements ............................................................ 58
Functions in zenon ................................................................................ 59
Execute VBA macro .......................................................................... 60
Macro selection ............................................................................ 61
Developing wizard in VBA ....................................................................... 61
Using a wizard ................................................................................. 62
Structure of a wizard .......................................................................... 63
Integration in VBA ............................................................................. 63
Developing a wizard .......................................................................... 63
Updating wizards .............................................................................. 69
Frequently asked questions ..................................................................... 69
Why does the button stay pressed? ........................................................ 69
Macro is not performed with the first click ................................................. 69
Macros no longer work in the Runtime? ................................................... 70
Windows CE and VBA ........................................................................ 70
Examples ........................................................................................... 70
MouseEvents and ActiveX Control initialization .......................................... 70
Display variable information ................................................................. 71
Read and write variable values ............................................................. 71
Read and write variables and implement online variables .............................. 72
Use dialog multiple times ..................................................................... 73
Alarm Events and ActiveX Control handling ............................................ 75
Access to alarms .............................................................................. 77
Set switch (working with process variables) ............................................... 79
4 VSTA
Basics .............................................................................................. 84
Setting up the VSTA environment ........................................................... 84
Table of contents 5
6 Object Model
Further information
Programming Interfaces 7
1
Programming Interfaces
Different interfaces to integrate your own programs or to automate planning are available
in zenon:
• Macro list (on page 41) (VBA)
• VSTA (on page 83)
• Use of add-ins in Editor and Runtime (on page 26) (Add-Ins)
• Process Control Engine (PCE)
Starting from version 7.20, PCE will not be supported anymore and it will not be shown
in the module tree of zenon anymore. While converting projects from versions lower
than 7.20, which contain PCE tasks, the node PCE will be shown for these projects
again. PCE will not further be developed or further documented.
Recommendation: Please use zenon Logic instead of PCE
Context Menu
Open the VSTA Editor with Projectaddin Opens the VSTA editor.
Information
you can find information on the creation and implementation of controls (ActiveX,
.NET, WPF) in the Controls manual.
You can find information on engineering and use of the SAP interface in the SAP
interface chapter.
8 Programming Interfaces
Open editors
Add-In
To open the Add-In Editor:
1. Click on the Tools menu in the zenon Editor.
2. Select the Open Add-In Editor entry
Alternatively: Press the short cut Ctrl+F9
To open the Editor in the Runtime:
• In the Startup Tool under Tools, select the SharpDevelop IDE link.
VSTA Editor
VSTA provides separate development environments for Workspace and project. You can
only use one of them at a time. At the start every other VSTA development environment
which is open will be close.
To open the VSTA Editor for the workspace:
1. Press the Alt+F10 keyboard shortcut.
A notice dialog is opened.
The code for the workspace and all loaded projects is displayed.
To open the VSTA Editor for the currently loaded project:
1. Navigate to the Programming interfaces node
2. Expand the view of this node by clicking on [+].
The view of the node is expanded.
3. Right-click on VSTA.
4. In the context menu, select Open VSTA editor with ProjectAddin.
A notice dialog is displayed.
Click on the OK button in order to continue with the VSTA project configuration.
The VSTA editor is opened for the project that is currently loaded.
A VBA file created with a 32-bit version cannot be used without changes in a 64-bit
version of VBA.
Attention
Errors in applications such as ActiveX, PCE, VBA, VSTA, WPF and external
applications that access zenon via the API can also influence the stability of Runtime.
10
Add-Ins 11
2
Add-Ins
Add-Ins provide possibilities to expand the functionality of zenon in the Editor and in Runtime
with different development environments.
The following are available to you to create Add-Ins:
• Microsoft Visual Studio (on page 19)
• SharpDevelop (on page 23) SharpDevelop (on page 23)
Add-Ins can be created with each .NET programming language. IDE support is available
for the programming languages C# and Visual Basic.NET.
Note: You define the development environment that is used when clicking on Open add-In
editor in the zenon settings of the Extras menu under Settings... in the Add-Ins tab.
Note:
• All lists and interfaces support IEnumerable.
Reference: https://msdn.microsoft.com/de-de/library/9eekhta0(v=vs.110).aspx
• LINQLanguage Integrated Query can be used.
Reference: https://msdn.microsoft.com/en-us/library/mt693024.aspx
Attention
Functionality
Add-Ins allow you to do the following, among other things:
• Provide project configuration aids (such as wizards)
• To enhance the project in Runtime with additional functionality
You can find Add-Ins:
• For the Editor in the Extras menu under the following entries:
• Manage Editor Add-Ins
• Start Edior Wizards
• Manage Editor services...
• For Runtime in the Programming interfaces - - nodeAdd-Ins
Compatibility
zenon add-ins are forwards and backwards compatible.
Backwards compatibility
Add-Ins Are also compatible with newer versions of zenon. If, for example, an Add-In is
compiled for version 7.60, it can also run in version 8.00.
Backward compatibility
Add-Ins Can be compiled for earlier zenon versions. Thus, for example, an Add-In with
zenon 8.00 can be created for zenon 7.60.
Prior knowledge
As with the creation of other software components, certain prior knowledge is also necessary
for the development of Add-Ins for zenon.
This includes
• Programming knowledge in C# or VB.NET (depending on the requirement / complexity
of the Add-Ins to be developed)
• Good zenon knowledge
The following is also recommended
• Experience in using professional development environments (such as Microsoft Visual
Studio)
• The use of a version management system for the developments (TFS, SVN, GIT)
Terminology
Specialist terms and their meaning in relation to Add-Ins.
Add-Ins 13
Term Meaning
Add-In Package A ZIP file (*.scadaAddIn), that contains metadata and libraries with
their dependencies.
An Add-In Package includes an Add-In Assembly
Extension Extensions are classes that can be derived from an interface with one
or more methods. They are entry points in the Add-In Package.
Each class that represents an Extension is marked with a .NET attrib-
ute.
There are two Types of extensions (on page 16) Types of exten-
sions (on page 16) , one for the Editor and one for Runtime
• Wizard Extensions (Wizards)
• Service Extensions (Services)
Project Add-In Management Components for zenon Editor and Runtime that manage the Project
Add-In Packages.
Note: Specialist terms are only used in English in the documentation for Add-Ins.
Limitations
The following limitations are applicable for Add-Ins:
• The zenon Web Client supports the execution of Add-Ins, however without IDE support.
The local debugging of Add-Ins is not possible in the zenon Web Client for this reason;
debugging using remote debugging tools is supported.
• The execution of Add-Ins is not supported in the HTML web engine.
Create add-in
General information
Add-Ins are identified by means of the Add-In ID. It is used for installation and import.
An Add-InID consists of an optional Namespace and a local ID, namespace.localId. The
Local ID identifies an Add-In; the Namespace assigns an Add-In to an organization. Both
pieces of information are defined with the .NET attribute Mono.AddIn.AddInAttribute attribute.
In order for the name for an Add-In Package to also remain unique beyond organization
boundaries, the Namespace of the Add-In project is used as part of the ID.
14 Add-Ins
■ Basics
There are different Extensions available for the zenon Editor and zenon Runtime. Depending
on the application, a corresponding Extension can be selected.
All interfaces required for the development of Add-Ins are defined in the
Scada.AddIn.Contracts assembly.
An Add-In Package can contain one or more Extensions .
Extension attributes
The following metadata is defined using the .NET attributewith the name AddInExtension.
Key:
• X: is true
• --: is not true
Add-in attributes
An Add-In Assembly needs several .NET attributes, which are defined in the AddInInfo.cs
file.
The most important attributes and those necessary for use in zenon are:
16 Add-Ins
Key:
• X: is true
• --: is not true
■ Types of extensions
Wizard in the Editor - Editor wizard extension
Editor Wizard Extensions are used to implement wizards or other user-controlled API
processes in the Editor.
• Execution is triggered by the user using the Extras -> Editor Wizards... dialog in the
zenon Editor.
• Implements the Run method in order to execute a Wizard Extension in the zenon Editor.
}
Add-Ins 17
XML-File
The content of an Add-In Package is listed in its own XML file (Content.xml).
Binary files
Binary files are saved in their own ZIP file. This file must contain all components that are
needed on another system to execute the Add-In. Direct and indirect references to .NET
Assemblies. In doing so, only external Assemblies are included. Assemblies that are not
part of the .NET Framework Class Library or are installed during the zenon installation.
Attention: Ensure that you have all the licenses required for this.
Note: Dynamically-loaded .NET Assemblies are not included in the metadata of .NET
Assemblies.
Information
ABB accepts no liability and offers not technical support for external Libraries.
zenon add-ins
ABB Developer Tools allow users to create and debug zenon Add-Ins quickly and easily
with Microsoft Visual Studio. They provide project templates for zenon Editor and Runtime.
Templates for services and wizards (extensions) are available for both applications.
ABB Developer Tools support:
• C#
• VB.NET
With the ABB Developer Tools, Add-In packages are created when building Add-Ins. The
deployment and debugging of Add-In packages is integrated. That means: If debugging is
started, Add-Ins are deployed and the debugging tool is automatically linked to zenon Editor
or Runtime.
Requirements
In order to be able to use the ABB Developer Tools, you need:
• Visual Studio 2015 (Community, Professional or Enterprise)or higher
• zenon 7.60
20 Add-Ins
Create project
To create a new project, use the New Project dialog.
An empty Extension class is created once the project has been created:
Debugging
To debug, select a target in the project properties:
Deployment
To deploy, use the Deploy command in the Build menu:
Note: If the debugging is started directly, the deployment is also started directly.
During deployment and debugging, the SCADA category shows detailed information in the
output window.
Information
22 Add-Ins
As an alternative to the method described, you can also debug your Add-Ins by
means of Debug -> Attach to Process. In doing so, connect from the corresponding
Add-In project in Visual Studio to the zenon Editor process.
Recommended debugger type (Debugger Type): Managed mit CLR 4.0
Debugging in Runtime
To debug an Add-In in Runtime, proceed as follows:
1. Compile the Add-In and import it as described in Installing and manging add-ins for
Runtime (on page 33) Installing and manging add-ins for Runtime (on page 33) Installing
and manging add-ins for Runtime (on page 33) .
2. Start the zenon Runtime.
3. Select the project in Visual Studio under Debug Target.
The respective instance must be running at the time.
4. Start the debugging using F5 or Debug -> Run.
5. The Add-In project is compiled and deployed.
When deploying again, note that the wizard or service is not running.
6. Debug the Add-In.
Information
As an alternative to the methods described, you can also debug your Add-Ins using
Debug -> Attach to Process. Then select the zenon Runtime process (Zenrt32.exe)
and click on Attach
• If you enter @zenoncom and the term being searched for in the search bar of the Visual
Studio user interface , a search for content in the Com documentation is carried out.
Example:@zenoncom Alarm
Enter the term being searched for in the search bar and confirm the selection by clicking
on the Enter key.
You can jump directly to the zenon API documentation again from the result of the search.
■ SharpDevelop
SharpDevelop (also #develop) is an open-source development environment that is based
on Microsoft's .NET platform. SharpDevelop is supplied with zenon and is also installed
during the installation of zenon.
Note: You can find the respective current version and the official documentation for
SharpDevelop online at: www.icsharpcode.net/opensource/sd/.
To check the version for which compiling is being carried out in zenon Editor:
1. Click on the Add-In.
2. Open the General properties group.
Check the Minimum version property.
Debugging in Runtime
Debugging is carried out project-by-project in Runtime.
To debug an Add-In in Runtime:
1. Start the zenon Runtime.
2. Start SharpDevelop.
To do this, select zenon Startup Tool and under Tools select the SharpDevelop IDE
link.
3. Open the project.
4. In the project settings in SharpDevelop, go to the Add-In tab.
5. Select, under Debug Target, the project in Runtime in which you want to debug the
Add-In.
The respective instance must be currently running.
6. Start the debugging using F5 or Debug -> Run.
7. The Add-In project is compiled and temporarily deployed in the selected zenon project.
ensure that the wizard or service is not running when deploying again.
Add-Ins 25
Information
As an alternative to the methods described, you can also debug your Add-Ins using
Debug -> Attach to Process. In doing so, connect from the corresponding Add-In
project in SharpDevelop to the process in the zenon Editor or Runtime.
Attention
In contrast to VSTA and VBA, the Source Code of Add-Ins is not saved and
administered in the zenon project.
Argument Description
Examples
• Creates an Add-In Package (arguments written out in full):
AddInUtility.exe --action BuildPackage --path C:\Addin.dll --targetDir C:\Directory\
• Creates an Add-In Package (arguments in abbreviated form):
AddInUtility.exe -a BuildPackage -p C:\Addin.dll -t C:\Directory\
• Returns information about the given Add-In Package:
AddInUtility.exe -a GetPackageInfo -p C:\Directory\Addin.scadaAddIn
■ Isolation
All Add-Ins are executed in an isolated memory area (App-Domain). As a result, different
versions of the same Assemblies can be loaded at the same time.
• For the Editor in the Extras menu under the following entries:
• Manage Editor Add-Ins
• Start Edior Wizards
• Manage Editor services...
• For Runtime in the Programming interfaces - - nodeAdd-Ins
Properties
If an Add-In is highlighted in the Editor, its properties are shown in the General node:
• Name: Name of the Add-In.
• Description: Description of the Add-In.
• Version: Version number of the Add-In.
• Source code: Shows whether the source code is contained in the package.
• Minimum version: Lowest zenon version, in which the Add-In can be used. This is
defined when creating the Add-In for:
• Create add-in package with Visual Studio (on page 20)
• Create add-in package with SharpDevelop (on page 23)
These properties cannot be changed in the Editor or Runtime. They are for information only.
The same properties are also shown in the detail view for all add-ins.
History of Changes
If the change history has been activated for the project, entries for the change history are
generated in the project when installing and uninstalling Add-In Packages.
Information
Add-Ins 29
The Add-In ID is unique for each Add-In and is defined using a .NET attribute in the
AddInInfo.cs file.
Example (Add-In ID = AddInProject):
// Declares that this assembly is an add-in
Entry Description
Add-In Import... Opens the dialog to import an Add-In Package that is to be used in the
Runtime.
Note: The package is only imported, not installed. Installation is carried
out in the Runtime.
Editor profile Opens the drop-down list with predefined editor profiles.
Option Description
Symbol Description
Import and install Open the dialog to select an Add-In. This can be imported and installed.
Uninstall and delete Uninstalls and deletes the selected Add-In after requesting confirmation.
Remove all filters Removes all filters that are currently applied in the list of Add-Ins.
Option Description
List of services Shows all installed Services. Information on the following is shown:
• Name
• Description
• Start type
• Status
Elements can be shown filtered and sorted.
Note: This dialog is also Display dialog "Manage Runtime services" (on page 35) via the
Display dialog "Manage Runtime services" function.
Symbol Description
Add-Ins 33
Start type manually Sets the start type for the selected service to manual.
Start type automatically Sets the start type for the selected service to automatic.
Remove all filters Removes all filters that are currently applied in the list of services.
Hint
You can get to the Runtime folder most quickly by highlighting the project in the
Editor and pressing the key combination Ctrl+Alt+R.
Import Add-In
To import an Add-in :
1. In the Editor, open the detail view for Add-Ins in the project tree.
34 Add-Ins
2. Click on the ImportAdd-In symbol, select this entry in the context menu or press the
Insert key.
The dialog to select an Add-In is opened.
3. Select the desired Add-In.
4. Click on Open.
The Add-in is imported.
Info:
During modification, the sync is carried out using the time stamp of the Add-In Package.
• Only once the Runtime files have been created is the Add-In saved in the Runtime
files.
Save folder: ...\RT\FILES\zenon\system\AddInStore\...
• When starting or reloading Runtime, it is installed, modified or updated in the
following folder:
...\RT\FILES\zenon\system\AddInCache\...
5. Click on Close to close the dialog.
Note: Only Add-Ins with Project Extensions can be imported and installed. If no Project
Extensions are found during import, a corresponding warning is shown.
Reload add-in
Amended and new add-ins can be reloaded in the Runtime.
Before reloading, a check is carried out to see whether the Add-In Cache and the Add-In
Store differ. Reloading is started if there are differences.
Procedure:
1. All Add-In services are stopped.
2. The status is saved.
3. The Cache is updated with the content from the Store.
4. The statuses of all services that already existed before reloading are restored.
5. Newly-added services are started with the automatic start type.
Note: With wizards, the reloading is only triggered if a wizard that is already running has
been ended.
Delete add-in
To delete an Add-In:
1. In the Editor, open the detail view for Add-Ins in the project tree.
Add-Ins 35
2. Select an Add-In.
3. Click on the Delete symbol or press the Delete key
A dialog requesting confirmation is opened.
4. Confirm this when requested to do so.
The Add-In is deleted.
After the Runtime files have been compiled the next time, it is uninstalled when Runtime
is reloaded or restarted.
■ Troubleshooting
Solution:
To change it on a permanent basis:
1. Uninstall the ABB SCADA Add-Ins.
2. Use DuplicateExtensiuonFinder to remove all remaining files of the installation.
You can find the application at: https://github.com/remcoros/DuplicateExtensionFinder
3. Install the ABB SCADA Add-In again.
zenon functions
In zenon, there are functions for Add-Ins available:
• Display dialog "Manage Runtime services" (on page 35) : Opens the dialog to manage
the services in Runtime.
• Execute Project Wizard Extension (on page 37) : Selection of a wizard that is executed
in the Runtime.
Engineering of a function
Steps to create the function:
1. Create a new function:
In the toolbar or in the context menu of the Functions node, select New function.
The dialog to select a function is opened.
2. Navigate to the node Add-In.
3. Select the Display dialog "Manage Runtime services" function.
The dialog is closed.
4. Name the function in the Name property.
Option Description
List of services Shows all installed Services. Information on the following is shown:
• Name
• Description
• Start type
• Status
Elements can be shown filtered and sorted.
Actions for the displayed elements can be executed using the tool bar or
the context menu.
Entries in the context menu and meaning of the symbols (from left to right):
Symbol Description
Start type manually Sets the start type for the selected service to manual.
Start type automatically Sets the start type for the selected service to automatic.
Remove all filters Removes all filters that are currently applied in the list of services.
Engineering of a function
Steps to create the function:
1. Create a new function:
In the toolbar or in the context menu of the Functions node, select New function.
The dialog to select a function is opened.
2. Navigate to the node Add-In.
3. Select the Execute Project Wizard Extension function.
The dialog to select a wizard is opened.
4. Select the desired wizard.
5. Close the dialog by clicking on OK.
6. Name the function in the Name property.
38 Add-Ins
Option Description
List of wizards Shows all wizards found in the project tree in the Programming
interfaces/Add-Ins node.
The elements displayed can be filtered and sorted.
Criteria:
• Name
• Description
• Category
Only one wizard can be selected.
Show this dialog in the Runtime Active: When calling up the function in the Runtime, this dialog
is opened and the user can amend the configuration before exe-
cution.
The dialog is displayed on the current computer in the Runtime.
During network operation when activating the client the dialog is
also displayed on the client
Close dialog
Option Description
Runtime
To convert existing VSTA functionality from Runtime, proceed as follows.
40 Add-Ins
3
Macro list
You can use VBA and VSTA in order to extend zenon functionality. The usage of macros
with zenon is described.
Context menu
Export all VBE Opens the dialog for selecting the storage directory for the VBE export.
Import VBE Opens the dialog for selecting the VBE import file.
Editor profiles Opens the drop-down list with predefined editor profiles.
Information
VBA starts the same development environment for Workspace and Project.
To open the VBA Editor:
1. In the zenon Editor, navigate to the Programming interface node.
2. Expand the view of this node by clicking on [+].
The view of the node is expanded.
3. Right-click on Macro list
42 Macro list
New VBA macro Creates a new macro and opens the macro Editor.
Export all VBE Opens the dialog for selecting the storage directory for the VBE export.
Import VBE Opens the dialog for selecting the VBE import file.
Export all VBE Opens the dialog for selecting the storage directory for the VBE export.
Import VBE Opens the dialog for selecting the VBE import file.
New VBA macro Creates a new macro and opens the VBA Editor.
Toolbar Editor
Macros that were created with VBA can be administrated via toolbar-item Macro list.
If a filter is selected, this selection is also visible in the tool bar.
Symbol Description
Reload list of VBA/VSTA macros Loads all Public Sub Name () macros that are included in my-
Workspace and in modules to the drop-down list of the toolbar.
Search Macro Search for macros via combobox input field or selection from drop-
down list. The drop-down list is adjusted to the widest element when
opened.
Execute selected macro Executes the macro selected in the drop-down list.
execute allocated macro #<x> Executes the macro allocated with the symbol.
Allocate macros Opens the allocation dialog for macros. Up to 5 macros can be alloc-
ated with the symbols 1 to 5.
ALL Cancels the current filter and all macros are displayed.
Information
If the macro assignment dialog does not list all macros from myWorkspace, execute
the function Reload list of VBA macros in the toolbar.
Basics
Describes the basics of the programming language VBA - Visual Basic for Applications
■ Object PROPERTIES
An object property is a certain attribute of the object. In case of a variable object this e.g.
can be the value, the name or the identification. In case of a circle the position or the color
of the circle in the screen. Each object has at least one property (usually more), each property
has a certain value. While the property name is a text, the property value is a value between
0 and e.g. 1000.
The special thing with properties is, that with changing the property value in a VBA program
you can change the behavior or the appearance of the object. If you e.g. change the property
value of a variable object, the currently selected variable gets this new value. You cannot
cange the value of each property. The property count of the variable object cannot be
changed, because it represents the number of created variables. You cannot add variables
by changing the value of Count. So some properties are read only, i.e. their values only can
be read.
■ Object METHODS
Beside the properties each object can have methods. A method is not an attribute but a
request to the object to do something. So a form has the method Show. What does it do?
It requests the form to appear on the screen. Accordingly the form disappears when using
the method Unload.
The advantage of methods is, that the programmer does not have to know anything about
the structure of the object and most of all has no opportunity to chnage the internal data of
the object.
Executing the method Show or Unload works as follows:
frmSollwert.Show or Unload frmSollwert
Macro list 45
If you want to open another form, the method stays the same, only the name of the form
(object name) changes.
frmChange.Show or Unload frmChange
So one and the same method can be used for different object types. But not every object
must have methods.
■ Object EVENTS
In 90% of working with objects you will use properties and methods, but there is a third kind
of attributes objects can have: Events. Some objects of the control system object hierarchy
can react on events. Events take place during the work with zenon on their own.
Example
Clicking on this event with the right mouse button opens a menu.
Select the menu entry "New macro..." Thus zenon generates a procedure:
Public Sub LeftClickUp_Sollwert(obElem As Element)
End Sub
If a macro already exists, it can be edited, deleted or renamed by clicking it with the right
mouse button.
Attention
48 Macro list
If you select menu item Rename macro, take care that you do not change the name
of the event e.g. LeftClickUp_..., - of the current name. Otherwise renaming will not
be executed. Additionally you have to change the name of the sub program to be
executed in the VBA Editor by hand, if you rename a macro.
After you have filled the procedure generated by zenon with the source code to be executed,
the created macro has to be linked to an element.
Doubleclicking the element opens the property dialog of the element.
On the property page Events the macro is linked to the element.
Clicking the element with the left mouse button executed the LeftClickDown event of the
element and the linked macro.
• After you have selected the element from the list, you can links variables to it. For this
click the button Variable and select a variable or create a new one.
• In the next step we give the ActiveX element an object name, so that we can access it
in VBA.
• In our example we give it the object name Slide6_DW18, because it is an AcziveX
element Slider linked to the variable Doubleword18.
• Now the Slider element has to be activated and edited in the VBA Editor.
• For this we create a new macro as described in chapter "How to use VBA macros (on
page 46) ".
The macro Init_Slider passes the element to be initialized to a sub program in the control
system object thisProject, whereby the allocation to the current project is defined.
Public SubInit_Slider(obElem AsElement)
thisProject . Init _ Slider obElem
End Sub
Just like in the macro Init_Slider also Draw_SliderValue passes the element to the control
system object thisProject.
Public Sub Draw_SliderValue (obElem As Element, ByVal hdc As OLE _ HANDLE )
thisProject.Draw_Slider obElem
50 Macro list
obElem.Draw hdc
End Sub
The code below is added in the control system object this Project.
Public Declarations Public WithEvents obSlider As Slider
Public obSliderPV As Variable
Public Sub Init_Slider (obElem As Element)
Set obSlider = obElem.ActiveX
Visual Basic 6
In order to be able to access the COM interface it has to be implemented:
With this type library you can access the application object of zenon (the Runtime).
As here there is no thisProject object, it has to be created to get access to the data.
Dim obProject As zenon.Project
Set obProject = zenon.Application.Projects.Item(PROJEKTNAME)
If the VB project should work with all zenon projects - should be project name independent
- it can be defined in the following way:
Set obProject = zenon.Application.Projects.Item(0)
After the project object (thisProject) has been created, e.g. the variables can be accessed
for reading and writing.
Macro list 51
Read:
Value = obProject.Variables.Item(Variablenname).Value
Write:
obProject.Variables.Item(Variablenname).Value = Value
Create event
Private Sub Container_VariableChange(ByVal obVar As zenon.IVariable)
...
End Sub
This event is automatically created, when the container is selected in the left combobox at
the top of the VBA Editor. The procedure above then is added to the source code. With
obVar the variable with the changed value is passed on. When this event occurs, e.g. the
current value of the variable (ob-Var.Value) can be read. Refer to the object hierarchy in
the VBA documentation to see the properties and values of variables, which can be used.
Activate event
Container.Define
52 Macro list
This command line activates the monitoring of the variables in the container. After executing
the command Define, the container is active.
With this command the surveillance in the container is switched off. The event
(VariableChange) is no longer carried out.
Remove on closing
In order not to leave anything in the memory on closing the Runtime, the container has to
be removed at the latest on closing the Runtime.
thisProject . OnlineVariables . DeleteOnlineVariables ( Container_name )
Not before the container is deleted can another container with the same name be created.
Bit number Short term Long name zenon Logic long name
Information
In formulas all status bits are available. For other use the availability can be limited.
You can read details on status processing in the Status processing chapter.
Default: activated
• The Move Frame via mouse property must be deactivated in the desired screens under
Interaction
Default: deactivated
There are several methods for selecting elements available in the Runtime, depending on
the settings for touch operation:
• Touch operation deactivated or Windows 7 (Recognition property deactivated or
Windows 7):
• Left mouse click + movement: New selection is created.
• Left mouse click + Ctrl key + movement: Selection is expanded.
• Native Windows 8 touch operation active (Recognition property on Windows 8):
• Left mouse click + movement: Screen is moved
• Left mouse click + Ctrl key + movement: Screen is moved.
• Left mouse click + Shift key + movement: New selection is created.
• Left mouse click + Ctrl key + Shift key + movement: Selection is expanded.
Rules:
• Only elements that are visible can be selected.
• If a button is selected and it is clicked on, the respective function is executed.
• If a mouse click on a selected button is executed and the mouse is moved before
releasing the mouse button, the respective function will not be executed.
• Cancel selection: Left-click with the mouse in an area outside the selection.
Editor events
Editor events are part of the VBA workspace and make it possible to react to Events in the
workspace programming, e.g. for wizards or Remote Transport. For example:
• OnElementCreated
• OnElementDeleted
• OnElementDoubleClicked
• OnObjectCreated
• ...
All Events and information about them can be found in the help in chapter Object Model (on
page 131) .
56 Macro list
Symbol Description
Reload list of VBA/VSTA macros Loads all Public Sub Name () macros that are included in my-
Workspace and in modules to the drop-down list of the toolbar.
Search Macro Search for macros via combobox input field or selection from drop-
down list. The drop-down list is adjusted to the widest element when
opened.
Execute selected macro Executes the macro selected in the drop-down list.
execute allocated macro #<x> Executes the macro allocated with the symbol.
Allocate macros Opens the allocation dialog for macros. Up to 5 macros can be alloc-
ated with the symbols 1 to 5.
ALL Cancels the current filter and all macros are displayed.
Information
If the macro assignment dialog does not list all macros from myWorkspace, execute
the function Reload list of VBA macros in the toolbar.
■ Macros allocation
Macros can be called via a button in the toolbar. A maximum of five macros can be linked
this way. Via button Assign macros the dialog for assigning macros is opened.
Macro list 57
Option Description
Macro # Macro number matches the number of the button in the toolbar.
A click on button ... opens the dialog for selecting the macro.
Parameter Description
Macro # Macro number matches the number of the button in the toolbar.
A click on button ... opens the dialog for selecting the macro.
Parameter Description
Parameter Description
Functions in zenon
In dialog Function selection you can find the following functions under element VBA.
Function Description
Open PCE editor Opens the editor of the optional module Process Control
Engine (PCE).
Parameters Description
Macro selection Opens the dialog for selecting the macros (see also Macro selection (on page 61) )
Hint: Only lists VBA macros that match the number of parameters defined at the
function Parameter (below).
New Click on this button in order to apply the value at parameter in the list of available
parameter.
Delete Click on this button in order to delete the selected entry from the list of available
parameter. You can always only delete one entry at a time.
Up Click on this button in order to move the selected entry up one place. In the para-
meter order the entry is moved one place to the front.
Down Click on this button in order to move the selected entry down one place. In the
parameter order the entry is moved one place to the back.
It is possible to add strings to macros which were created with parameters. These strings
are transferred in the Runtime as individual parameters when the macro is carried out.
Information
Macro list 61
You must make sure that the number of parameters of the linked macro matches
the number of the created parameters.
Macro selection
After clicking button ..., the following dialog is displayed.
Select the desired macro from the available macros and then click OK.
■ Using a wizard
The menu entry Editor Wizards in the menu Tools opens the wizard selection. In this dialog,
all available wizards are shown according to their category.
If wizards do not contain a category, a Not linked entry is created automatically. In this
category all not linked wizards are displayed.
By selecting a wizard and pressing the button OK the selected wizard is executed.
Information
■ Structure of a wizard
A wizard is a UserForm stored in the application specific node of the application. Usually
the UserForm consists of a multi-page element displaying the single steps of the wizard.
With a button Next the next page of the multi-page element is displayed. All entries have to
be stored temporarily - the creation of objects, e.g. frames, screens, ... has to be done with
Finishing the wizards.
Information
■ Integration in VBA
The wizards are stored in the application specific node ZWorkspace. This object represents
the currently loaded workspace in the Editor and is only available in the zenon Editor.
All objects in this VBA project can access the current workspace with teh object
MyWorkspace. It is always linked to the currently active project, which can be accessed
with the property ActiveDocument.
The contents of the object ZWorkspace are stored in the file ZenWorkspace.vba. It is
copied to the installation directory with the first installation of version 6. This file is not
overwritten by later updates. You will find more information on updating wizards at the end
of this tutorial.
■ Developing a wizard
This tutorial develops a wizard creating variables for a defined driver.
Start the VBA environment from the zenon Editor and change to folder ZWorkspace/Forms.
This file contains the basics for developing a wizard. Change the name of the UserForm.
If the folder mentioned above is not available, you can import it via Import the Import file
command.
Information
For developing a wizard knowledge about the object model of zenon and VBA are
required. These topics are not part of this tutorial.
64 Macro list
Macro list 65
Create the surface displayed above. Then switch to the code module of the UserForm and
scroll to the end of the file. There you will find the following methods.
• Public Function GetWizardName () As String
Returns the unique name of the wizard. Change the contents to Wizard for creating
variables
• Public Function GetWizardInfo () As String
Returns a short description displayed in the wizard selection. Change the contents to
Wizard for creating variables to a selected driver
• Public Function GetWizardCategory () As String
Returns the category of the wizard. In the wizard selection the wizards are displayed in
a tree structure of the categories. Change the contents to Variables.
• Public Function IsZenOnWizard () As Boolean
Displaying the wizard in the wizard selection. If this method returns False, the wizard
is not displayed, e.g. because it is not yet finished. Change the return type to True.
These methods provide the information about the wizard, which is requested by the control
system. Keep in mind that the wizard is only displayed in the wizard selection if the method
IsZenOnWizard returns True.
66 Macro list
Switch to the event Initialize of the UserForm and change the contents of the string array
m_strCaption. As oru wizard only consits of two steps, you can delete the other allocations.
Add the following definitions to the top area of the code module:
Private m_obDriver As Driver
Private m_obVarType As VarType
Private m_nChannelType As Integer
Create a method for initializing the driver combobox. The task of this routine is to display
all the loaded drivers of the current project in a combobox.
cbDriver.Clear
Dim nIndex As Long
For nIndex = 0 To MyWorkspace.ActiveDocument.Drivers.Count - 1
Dim obDriver As Driver
Set obDriver = MyWorkspace.ActiveDocument.Drivers.Item(nIndex)
If (Not obDriver Is Nothing) Then
cbDriver.AddItem
obDriver.Name
End If
Next nIndex
If (cbDriver.ListCount > 0) Then
cbDriver.ListIndex = 0
End If
Additionally we need a routine displaying all defined variable types of the project in a
combobox.
If (Not m_obDriver Is Nothing) Then
cbVarType.Clear
Dim nIndex As Long , nSelect As Integer
For nIndex = 0 To MyWorkspace.ActiveDocument.VarTypes.Count - 1
Dim obVarType As VarType
Set obVarType = MyWorkspace.ActiveDocument.VarTypes.Item(nIndex)
If ( Not obVarType Is Nothing And obVarType.IsSimple = True) Then
cbVarType.AddItem
obVarType.Name
If (obVarType.Name = INT) Then
nSelect = nIndex
End If
End If
Next nIndex
cbVarType.ListIndex = nSelect
End If
On opening the wizard all existing variables are checked to find a free start offset for the
the new variables to be created. This is done with the following method.
Private Function FindHighestOffsetVar() As Long
On Error GoTo Error
Dim nIndex As Long , nOffset As Long
Macro list 67
Switch to the event Initialize of the UserForm and add the following lines to this method:
txtStart.Value = CStr(FindHighestOffsetVar + 1)
InitializeDriver
The allocation to txtStart sets the proposed start offset for the variables to be created. The
method InitializeDriver fills the combobox with the existing drivers.
Create an event Change for the driver combobox and add the following code. After having
selected a driver the variable types are acquired. The selected driver object is stored in the
variable m_obDriver for later use.
Private Sub cbDriver_Change()
cmdNext.Enabled = True
Set m_obDriver = MyWorkspace.ActiveDocument.Drivers.Item(cbDriver.Value)
If ( Not m_obDriver Is Nothing) Then
InitializeVarType
End If
End Sub
Create an event Change for the variable type combobox and add the following code. The
selected variable type is stored in the variable m_obVarType for later use.
Private Sub cbVarType_Change()
Set m_obVarType = MyWorkspace.ActiveDocument.VarTypes.Item(cbVarType.Value)
End Sub
Now the only thing left is to create the event routine for creating the variables with the defined
settings. This is done with the button Finish.
Private Sub cmdFinish_Click()
On Error GoTo Error
If (cbVarType.ListIndex = -1) Then
MsgBox 'Please select a variable type'
cbVarType.SetFocus
Exit Sub
68 Macro list
End If
If (txtStart.Value= Or txtCount.Value = Or txtStep.Value = ) Then
MsgBox 'Please enter Start-Offset', 'count of creating variables and the step'
txtStart.SetFocus
End If
If (m_obVarType Is Nothing) Then
MsgBox 'Variable type + cbVarType.Name + doesnt exist!'
Exit Sub
End If
Dim nPrvMousePtr As Integer
nPrvMousePtr = MousePointer
MousePointer = fmMousePointerHourGlass
DoEvents
Dim strName As String
Dim nIndex As Long , nVarIndex As Integer
Dim nStartOff As Long , nStep As Integer
nVarIndex = 1
nStartOff = CLng (txtStart.Value)
nStep = CLng (txtStep.Value)
For nIndex = 0 To CLng (txtCount.Value - 1)
Dim obVar As Variable
strName = txtName.Value + _ + CStr (nIndex + 1)
'*** Guaranteeing uniqueness of the variable name
Dim bResult As Boolean
bResult = False
Do
Set obVar = MyWorkspace.ActiveDocument.Variables.Item(strName)
If (obVar Is Nothing) Then
bResult = True
Else
nVarIndex = nVarIndex + 1
strName = txtName.Value + _ + CStr (nVarIndex)
End If
Loop While
bResult = False
'*** Create variable
Set obVar = MyWorkspace.ActiveDocument.Variables.CreateVar (strName, m_obDriver,
tpSPSMerker, m_obVarType)
If ( Not obVar Is Nothing) Then
obVar.Offset = nStartOff
nStartOff = nStartOff + nStep
End If
Next nIndex
MousePointer = nPrvMousePtr
Unload Me
Exit Sub
Error :
MousePointer = nPrvMousePtr
MsgBox Error occurs: + Err.Description + Source + Err.Source
End Sub
Macro list 69
On finishing the wizard it is checked, if the defined settings are valid. If this is not the case,
a messages is displayed and the user is demanded to correct the entries.
If the defined settings are valid, the variables are created. The variables are named with a
name and an index. If a variables with the same name already exists in the project, the next
free index is acquired. In our code example always a variable with the channel type PLC
marker is created. With each cycle the offset of the variable is increased.
■ Updating wizards
To update the wizards:
1. In the Extras menu, select the Update Editor Add-Ins entry.
A dialog for updating available wizards is opened
2. Select the desired wizards
3. Start the update by clicking Start update
If a wizard or a class already exists in the workspace, a warning is displayed.
Attention
Already existing wizards are overwritten during the update. Individual changes made
at the wizard are lost.
Examples
Here you can find a few examples for VBA
'Initializing ActiveX...
thisProject.Init_MSChart_AX obElem
End Sub
'Initializing Userform...
frmSample1.InitForm obElem
'Show Userform
frmSample1.Show
End Sub
'Initializing Userform...
frmSample2.InitForm obElem
'Show Userform
frmSample2.Show
End Sub
'Initializing Userform...
frmSample3.InitForm obElem
'Show Userform
frmSample3.Show
End Sub
NewForm.InitForm obElem
'Show NEW Userform
NewForm.Show (0)
End Sub
'set the variable object like the linked variable of the element
txtVarName.Text = obVar.Name
End Sub
'close Userform
Unload Me
End Sub
'set the variable object like the linked variable of the element
txtVarName.Text = obVar.Name
End Sub
'close Userform
Unload Me
End Sub
txtValue.Text = obVar.Value
End Sub
obVar.Value = txtValue.Text
'or changing text to value before writing...
'obVar.Value = Val(txtValue.Text)
End Sub
'set the variable object like the linked variable of the element
txtVarName.Text = obVar.Name
'create an OnlineVariable container
zOnlineVariable.Add obVar.Name
End Sub
'close Userform
Unload Me
End Sub
txtValue.Text = obVar.Value
End Sub
obVar.Value = txtValue.Text
'or changing text to value before writing...
Macro list 73
'obVar.Value = Val(txtValue.Text)
End Sub
zOnlineVariable.Define
End Sub
zOnlineVariable.Undefine
End Sub
txtOLV.Text = obVar.Value
End Sub
zOnlineVariable.Undefine
'delete OnlineVariable container
thisProject.OnlineVariables.DeleteOnlineVariables ("OLV")
End Sub
txtVarName.Text = obVar.Name
'create name for Online Container
zOnlineVariable.Add obVar.Name
End If
End Sub
End Sub
txtValue.Text = obVar.Value
End Sub
obVar.Value = txtValue.Text
'or changing text to value before writing...
'obVar.Value = Val(txtValue.Text)
End Sub
zOnlineVariable.Define
End Sub
zOnlineVariable.Undefine
End Sub
txtOLV.Text = obVar.Value
End Sub
zOnlineVariable.Undefine
Macro list 75
thisProject.OnlineVariables.DeleteOnlineVariables (strOLVName)
End Sub
thisProject.OnlineVariables.DeleteOnlineVariables "CHART"
End Sub
zOLV.Define
End Sub
obChart.RowLabel = "Var3"
obChart.Data = obVar.Value
End Select
End Sub
■ Access to alarms
Description:
In the form frmAlarm an alarm from the memory can be selected in a combobox. After the
selection all data of the alalm are written to the textboxes below (group, class, variable, ...).
We use an event independent macro to display frmAlarm, because we do not link it to an
element.
SubAlarm ()
frmAlarm.Show
End Sub
'On opening the form it is initialized and so the following procedure is executed.
This procedure cares, that all alarms in the memory are written to the combobox
in the form. Private Sub UserForm _ Initialize ()
'fill combobox with all AlarmItems
Dim i As Integer
78 Macro list
'Wenn nun ein Alarm aus der Combobox ausgewählt wird reagiert das Change - Ereigniss
der Combobox.Private Sub cmbAlarmItems _ Change ()
'put actual properties from AlarmItem in textboxes
Dim obAlarmItems As AlarmItems
Dim obAlar As Alarm
Set obAlarm = thisProject.Alarm
Set obAlarmItems = obAlarm.AlarmItems (*)
txtComputer.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Computer
txtCountreactivated.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Countreactivated
txtName.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ). Name
txtProjectname.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Projectname
txtStatus.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Status
txtStatusreactivated.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Statusreactivated
txtTagname.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Tagname
txtTimecomes.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Timecomes
txtTimegoes.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Timegoes
txtTimequitted.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Timequitted
txtTimereactivated.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Timereactivated
txtUser.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).User
txtUsertext.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Usertext
txtValue.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).Value
tbGroup.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).AlarmGroup
tbClass.Text = obAlarmItems.Item ( cmbAlarmItems.ListIndex ).AlarmClass
End Sub
Macro list 79
In this example we draw a pump consisting of a circle and a triangle. Define the triangle as
a symbol. On top draw a multibinary element and link it to three bit marker variables.
Additionally define, which color the triangle should get, if the values of the variables change.
First we combine the multibinary element with a macro, which opens a form frmSwitch.
In the form frmSwitch we will be able to change the values of the three bit marker variables.
Information
Only one of the three variables may have the value 1. (i.e. if one variable is set to
1, the other two have to be set to 0)
To be able to use this macro several times in project with different variables, you only may
link bit marker variables ti the multibinary element, which contail in their names, which status
of the pump they control.
for example:
Variable_Auto
Variable_Hand
Variable_Revi
Information
The suffixes _Auto, _Hand and _Revi are fixly defined in the source code of the
example.
With this five characters suffix of the variable names it is defined, which variable is set to 1
and which is set to 0 on clicking a toggle button.
In the macro LeftClickUp_Switch a sub program FindVariable is called in the form frmSwitch,
which gets the clicked element obElem.
80 Macro list
The self-created function VarExists only checks, whether the linked variables really exist.
If this is not the case, an error message is displayed. Variable doesn't exist.
Function VarExists ()
Dim obVariable As Variable
Set obVariable = thisProject . Variables . Item (strHand)
If obVariable Is Nothing Then
MsgBox (Variable doesnt extist)
VarExitsts = False
Exit Function
End If
Set obVariable = thisProject . Variables . Item (strAuto)
If obVariable Is Nothing Then
MsgBox ( Variable doesnt extist )
VarExitsts = False
Exit Function
End If
Set obVariable = thisProject . Variables . Item (strRev)
If obVariable Is Nothing Then
MsgBox ( Variable doesnt extist )
VarExitsts = False
Exit Function
End If
VarExists = True
End Function
If the user clicks Cancel, the value change is undone and the original status is reset.
Private SubcmdExit _ Click ()
cmdLast.Value = True
Unload Me
End Sub
Private Sub cmdOk _ Click ()
Unload Me
End Sub
In the click event of every toggle button it is checked, whether it is pressed and whether the
variable exists. If both conditions are true, the values are sent to the linked variables.
82
VSTA 83
4
VSTA
With Visual Studio Tools for Applications (VSTA), the functionality of zenon Runtime and
the Editor can be enhanced independently by means of .NET programming.
Attention
VSTA is also, with a few restrictions, available on the zenon Web Client.
VSTA provides separate development environments for Workspace and project. You can
only use one of them at a time. At the start every other VSTA development environment
which is open will be close.
To open the VSTA Editor for the workspace:
1. Press the Alt+F10 keyboard shortcut.
A notice dialog is opened.
The code for the workspace and all loaded projects is displayed.
To open the VSTA Editor for the currently loaded project:
1. Navigate to the Programming interfaces node
2. Expand the view of this node by clicking on [+].
The view of the node is expanded.
3. Right-click on VSTA.
4. In the context menu, select Open VSTA editor with ProjectAddin.
A notice dialog is displayed.
Click on the OK button in order to continue with the VSTA project configuration.
The VSTA editor is opened for the project that is currently loaded.
84 VSTA
Information
Warning dialog
A warning dialog is shown before the VSTA editor is opened in zenon. Click on the OK
button to open the VSTA editor.
Basics
VSTA is a Microsoft tool set that is based on .NET technology. It is necessary to have basic
knowledge of object-orientated programming, .NET and C#/Visual Basic.NET to understand
it.
Attention
Note in the Runtime: Referenced dlls cannot be replaced if they are loaded. Runtime
must be ended in order for a reference file to be updated.
[VSTA] [VSTA]
ON=1 ON=0
VSTA 85
[VBA] [VBA]
EIN=1 EIN=0
Information
Attention
Some changes to the object model have been made due to limitations in naming
VSTA objects. You can find these in the table below
IDriver.Name IDriver.Identification
IDriver.Driver IDriver.Name
IApplication.Close IApplication.OnClose
IZenWorkspace.Startup IZenWorkspace.OnStartup
IZenWorkspace.Exit IZenWorkspace.OnExit
Access is VSTA is enabled via the this object and the replaces the MyWorkspace object in
VBA. The following methods and objects are identical. In the following method, a template
with the name "TemplateName" is created in zenon.
public void Macro1()
{
this.ActiveDocument.Templates().Create("TemplateName", true);
}
86 VSTA
Information
In contrast to VBA, capitalization and brackets after function names are important
in VSTA.
To access the methods in zenon, the project must be saved and compiled using via the
following steps:
1. Click on File -> Save MyWorkspace.cs to save the project.
2. Click on File -> Build WorkspaceAddin to compile the project.
After this, the method is available as a macro in the VBA macro toolbar in the zenon editor.
If the macro assignment dialog does not list all macros from MyWorkspace, the function
'Reload list of VBA macros' has to be executed from the toolbar.
Information
■ Functions in zenon
For VSTA, functions were created in zenon. These are in the VSTA node.
VSTA 87
88 VSTA
At the same time as existing VBA functions, similar functions were implemented for VSTA:
Execute VSTA macro A VSTA macro can be selected in the editor, which is started
when executing the function in Runtime.
Note: VSTA macros with parameters, e.g. Public void Mac-
roWithParam(string mString), are not supported. They
are neither offered at the engineering in the Editor nor at the start
of the function in the Runtime.
Show VSTA macro dialog A dialog is shown in Runtime, in which existing VSTA macros
are shown and can be selected and executed
Parameters Description
VSTA 89
Existing macros
Information
■ Events in VSTA
Because an add-in is terminated when compiling amended code, starting a debug session
or ending a debug session, corresponding events were implemented in VSTA. These enable,
for example, an object reference to be evaluated and approved and existing data to be
saved.
Two events exist for each termination. The first event is started shortly before termination,
the second after the start of a new add-in session.
Event Description
Attention
Information
VSTA editor help can be accessed via the Help / Contents menu. This help gives
an overview of the editor's functions, the features of the .NET framework and
programming in Visual Basic.NET and C#.
The VSTA add-in basically consists of the MyWorkspace class. This class can now be
expanded with your own methods. The class accommodates the following two methods by
default:
Function Description
Attention
VSTA 91
The method names may only start with Macro (for example Macro1, MacroVSTA)
may not contain parameters and must be defined as Public . In addition, the class
names and other methods and events created by VSTA may not be changed.
To access the methods in zenon, the project must be saved and compiled using via the
following steps:
1. Click on File -> Save MyWorkspace.cs to save the project.
2. Click on File -> Build WorkspaceAddin to compile the project.
After this, the method is available as a macro in the VBA macro toolbar in the zenon editor.
If the macro assignment dialog does not list all macros from MyWorkspace, the function
'Reload list of VBA macros' has to be executed from the toolbar.
Information
In this project, a class named ThisProject is created by zenon, which accommodates the
following two methods:
Function Description
Attention
The method names may only start with Macro (for example Macro1, MacroVSTA)
may not contain parameters and must be defined as Public . In addition, the class
names and other methods and events created by VSTA may not be changed.
There is access to all Runtime functionalities via the zenon object model. Editor-specific
functions cannot be used, as in VBA.
zenon Runtime is automatically started when the debugger is started. Further information
can be found in the chapter on Debugging a VSTA add-in (on page 89) .
92 VSTA
Information
VSTA editor help can be accessed via the Help / Contents menu. This help gives
an overview of the editor's functions, the features of the .NET framework and
programming in Visual Basic.NET and C#.
Examples
Here you find some examples of VSTA being used, both in Runtime and in the editor.
the text file and creates the variables. The GetDataType method is then required to determine
and assign the attendant data type when creating the variables.
C# code
94 VSTA
using System;
using System.Windows.Forms;
using System.IO;
using zenOn;
namespace WorkspaceAddin
{
[System.AddIn.AddIn("MyWorkspace", Version = "1.0", Publisher = "", Description = "")]
public partial class MyWorkspace
{
private void MyWorkspace_Startup(object sender, EventArgs e)
{
}
private void MyWorkspace_Shutdown(object sender, EventArgs e)
{
}
public IVarType GetDataType(string vType)
{
//gets the corresponding vartypes for bool, int, real and strings
IVarType retType;
switch (vType)
{
case "BOOL":
retType = this.ActiveDocument.VarTypes().Item("BOOL");
break;
case "INT":
retType = this.ActiveDocument.VarTypes().Item("INT");
break;
case "REAL":
retType = this.ActiveDocument.VarTypes().Item("REAL");
break;
case "STRING":
retType = this.ActiveDocument.VarTypes().Item("STRING");
break;
default:
retType = this.ActiveDocument.VarTypes().Item("INT");
break;
}
return retType;
}
//Reads a defined text file and creates corresponding variables on the zen-
on internal driver
public void MacroCreateVariablesFromFile()
{
//create objects that will take the internal driver and the variable type
IDriver zenonInternDriver = null;
//search for the Internal driver and throw exception if no driver was found
try
VSTA 95
{
for (int driverCount = 0; driverCount < this.ActiveDocument.Drivers().Count; driverCount++)
{
if (this.ActiveDocument.Drivers().Item(driverCount).Name == "Intern")
{
zenonInternDriver = this.ActiveDocument.Drivers().Item(driverCount);
break;
}
}
}
catch (Exception driverEx)
{
MessageBox.Show("Unable to find zenon 'Intern' driver. Error: " + driverEx.Mes-
sage);
throw;
}
this.ActiveDocument.Variables().DoAutoSave(false);
try
{
OpenFileDialog varFileSelect = new OpenFileDialog();
String[] varLine = new String[2];
//read in line by line, split the lines when a ',' occurs and create vari-
ables
while ((line = importReader.ReadLine()) != null)
{
varLine = line.Split(new Char[] { ',' });
this.ActiveDocument.Variables().CreateVar(varLine[0], zenonInternDriver, tpKanaltypes.tpSys-
temVariable, GetDataType(varLine[1]));
}
importReader.Close();
}
}
catch (Exception fileEx)
{
MessageBox.Show("An error occurred while opening the file: " + fileEx.Message);
throw;
}
this.ActiveDocument.Variables().DoAutoSave(true);
}
#region VSTA generated code
private void InternalStartup()
{
96 VSTA
C# code
VSTA 97
using System;
namespace WorkspaceAddin
{
[System.AddIn.AddIn("MyWorkspace", Version = "1.0", Publisher = "", Description = "")]
public partial class MyWorkspace
{
private void MyWorkspace_Startup(object sender, EventArgs e)
{
//go through all pictures and print name and used template into output window
//go through all drivers and print name and description into output window
Information
It is possible that manual references may have to be added to execute the example
in zenon Runtime. To do this, open the context menu in the Project Explorer and
click on Add Reference...
The references required in this example are:
• Microsoft.VisualStudio.Tools.Applications.Runtime.v9.0
• System
• System.AddIn
• System.Data
• System.Windows.Forms
• System.Xml
• zenonVSTAProxy6500
C# code
VSTA 99
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Forms;
namespace ProjectAddin
{
[System.AddIn.AddIn("ThisProject", Version = "1.0", Publisher = "", Description = "")]
public partial class ThisProject
{
private void ThisProject_Startup(object sender, EventArgs e)
{
}
private void ThisProject_Shutdown(object sender, EventArgs e)
{
}
public void MacroGetFilteredVariables()
{
string filename = string.Empty;
string name = string.Empty;
string description = string.Empty;
string value = string.Empty;
Helper class to convert .NET colors in accordance with zenon and vice versa
C# code
VSTA 101
namespace WorkspaceAddin
{
class ZenonColorHelper
{
// convert .net Color to zenon API color
publicstaticuint Color2Api(System.Drawing.Color color)
{
// zenon stores as ABGR, where A is the highest significant bit
return (uint)((color.A << 24) | (color.B << 16) | (color.G << 8) | (color.R << 0));
}
// extracts the index in the color palette, which is encoded in the zenon API
color
// returns -1 if the given color does not represent a color palette index
publicstaticint GetColorPaletteIndex(uint apiColor)
{
System.Drawing.Color color = Api2Color(apiColor);
if (color.A == 128) // alpha value == 128 -> ind from color palette
{
// G defines the nr of 8bit chunks, R is the actual index
return color.G * 256 + color.R;
}
return -1;
102 VSTA
// encodes the index in the color palette into a zenon API color
publicstaticuint EncodeColorPaletteIndex(int index)
{
int chunks = (int)(index / 256.0);
int idx = (int)(index % 256);
C# code
VSTA 103
using zenOn;
publicvoid Macro_ColorHandlingSample()
{
// first we need a project to work with
// delete and recreate sample picture or create a new one if it not yet exists
IDynPicture pic = null;
IDynPictures pictures = project.DynPictures();
for (int i = 0; i < pictures.Count; i++)
{
IDynPicture picture = pictures.Item(i);
if (picture.get_DynProperties("Title").ToString() == "SamplePicture")
{
pic = picture;
break;
}
}
if (null != pic)
{
pic.Save();
pictures.Delete(pic.Name);
}
pic = project.DynPictures().Create("SamplePicture", "SampleFrame", tpDynPicturesTypes.tpStandard);
// look for existing color palette in current project or create a new one
IColorPalettes palettes = project.ColorPalettes();
int nrOfPalettes = (int)palettes.get_DynProperties("Palette");
if (0 == nrOfPalettes)
{
//Create a new palette
palettes.CreateDynProperty("Palette");
//Define a color in the new palette
String htmlColor = "#00FFFF"; // System.Drawing.Color.Aqua
palettes.set_DynProperties("Palette[0].PaletteColors", htmlColor);
}
5
Process Control Engine (PCE)
Attention
Starting from version 7.20, PCE will not be supported anymore and it will not be
shown in the module tree of zenon anymore. While converting projects from versions
lower than 7.20, which contain PCE tasks, the node PCE will be shown for these
projects again. PCE will not further be developed and documented.
Recommendation: Please use zenon Logic instead of PCE
■ The Taskmanager
The Taskmanager of the PCE Editor lists the existing tasks and the linked variables.
A doubleclick on a task opens it in the editing area. With the right mouse button the context
menu of a task can be opened.
Process Control Engine (PCE) 107
Parameters Description
Task variables... Opens the variable selection. So you can add new variables to the task.
Parameters Description
108 Process Control Engine (PCE)
Menu Edit
The menu Edit includes the following commands:
Parameter Description
Delete
Menu Run
The menu Run includes the following commands:
Menu View
The menu View includes the following commands:
Parameters Description
Menu Window
The menu Window includes the following commands:
Close
Arrange
Divide
Align symbols
Menu help
The menu Help includes the following commands:
Command Action
Parameters Description
Start debugger
Course of actions
■ Creating a task
With the context menu of the Taskmanager a new task can be created.
Parameter Description
Priority Process priorities for operating system multithreading (idle, low, normal, high, highest,
time critical).
Default: Normal
main process: the task runs in the same thread as Runtime. If the task gets into a
waiting loop or crashes, that also influences the Runtime.
Process Control Engine (PCE) 111
Script file Selection of the script file: VB-Files (*.vbs) for VB Script or JS-Files (*.js) for Java
Script.
The according file is created, when the task is opened in the editing area for the first
time.
Start type System start : automatically started with Runtime. (This is the only way to use the
PCE under Windows CE, as Windows CE does not support VBA.)
event triggered: the task is started in a VBA macro with the statement "thisPro-
ject.Tasks.Item("Taskname").Run".
Cycle time to reach For cyclic tasks the interval in milliseconds that should be achieved.
If this cycle time is not achieved, the task is executed as fast as possible.
For a later change of the properties this dialog can also be opened with the context menu
of the task and the entry Task Properties….
■ Entering code
Double-clicking the task in the Taskmanager opens it in the editing area. If the task is opened
for the first time, the according VBS or JS file is created now.
Four procedures are automatically created:
Parameters Description
Task_Main() This procedure is either executed once (type once) or cyclically (type cyclic).
Task_Timer(lTimerId) This procedure is executed cyclically, as long as the according time is running.
The cycle time is defined as a parameter with the starting of the timer.
Generally speaking the PCE uses the same object model as VBA (see VBA Tutorials). When
using VBA objects (except the object Task) multithreading is lost, because these objects
only can be accessed from the main thread.
Attention
Not all funtions of the COM interface are multithread-able and therefore can only
be used in a main tread context. If a different property than "in the main process"
is set as PCE task, there must not be any access from the PCE to the main thread.
112 Process Control Engine (PCE)
In case there is an access to the COM interface nevertheless, this can lead to
undefined system states, e.g. a Runtime freeze.
Of special importance are the collection Tasks and the object Task.
Count
Item
Parent
DynProperties Property
ErrorNumber Property
ErrorString Property
Exit Event
On init Event
ItemVariable Method
Main Event
Status Property
Timer Event
Type Property
■ Executing tasks
Tasks can be executed when the system is started or can be event-triggered.
On a PC
A task can also be started event triggered. In this case the Start typehas to be set to Event
driven. Now the task is no longer automatically started with the Runtime.
A VBA macro has to be created in order to execute a task by pressing a button, by a limit
value violation or any other event. With the following VBA statement the task can be started:
thisProject.Tasks.Item(Taskname).Run
The task is automatically started in an own thread if in the configuration Priority Main process
has not been set.
With the following VBA statement the task can be stopped at any time:
thisProject.Tasks.Item("Taskname").Stop
Note: To execute a task more than once, it must also be explicitly stopped after it has ended,
so that it can be restarted.
Instruction: thisProject.Tasks.Item(Taskname).Stop
It can be restarted after being stopped properly.
On a CE terminal
As Windows CE does not support VBA, the procedure for execution on a PC is not possible
on a CE terminal. But there is a possibility to execute tasks event triggered also here.
A task with the Start typeSystem startis created. This task is automatically started with
the Runtime. And this task gets the PriorityMain process so that it runs in the same thread
as the Runtime. Now bit variables are linked to that task, then will execute other tasks event
triggered. With the following statement the task can be started: Parent.Item(Taskname).Run
Now the task is automatically started in an own Thread if in the configuration the Priority
Main process has not been set.
With the following statement the task can be stopped at any time:
Parent.Item("Taskname").Stop
VB Script - Introduction
■ Data types
Variant
VBScript has only one data type called a Variant. A Variantis a special kind of data type
that can contain different kinds of information, depending on how it is used. Because Variantis
the only data type in VBScript, it is also the data type returned by all functions in VBScript.
114 Process Control Engine (PCE)
Variant Subtypes
Beyond the simple numeric or string classifications, a Variant can make further distinctions
about the specific nature of numeric information. For example, you can have numeric
information that represents a date or a time. When used with other date or time data, the
result is always expressed as a date or a time. You can also have a rich variety of numeric
information ranging in size from Boolean values to huge floating-point numbers. These
different categories of information which can be contained in a Variant are called subtypes.
Most of the time, you can just put the kind of data you want in a Variant, and the Variant
behaves in a way that is most appropriate for the data it contains.
The following summary shows subtypes of data that a Variantcan contain.
Subtype Meaning
Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string
variables.
Date (Time) Contains a number that represents a date between January 1, 100 to December 31, 9999.
■ Variables
A variable is a convenient placeholder that refers to a computer memory location where
you can store program information that may change during the time your script is running.
For example, you might create a variable called ClickCount to store the number of times a
user clicks an object on a particular Web page. Where the variable is stored in computer
memory is unimportant. What is important is that you only have to refer to a variable by
name to see or change its value. In VBScript, variables are always of one fundamental data
type, Variant.
Process Control Engine (PCE) 115
Declaring Variables
You declare variables explicitly in your script using the Dim statement, the Public statement,
and the Private statement. Example:
Dim DegreesFahrenheit
You declare multiple variables by separating each variable name with a comma. Example:
Dim Top, Bottom, Left, Right
You assign data to each of the elements of the array using an index into the array. Beginning
at zero and ending at 10, data can be assigned to the elements of an array as follows:
A(0) = 256
A(1) = 324
A(2) = 100
...
A(10) = 55
Similarly, the data can be retrieved from any element using an index into the particular array
element you want. Example:
...
SomeVariable = A(8)
...
Arrays aren't limited to a single dimension. You can have as many as 60 dimensions,
although most people can't comprehend more than three or four dimensions. You can
declare multiple dimensions by separating an array's size numbers in the parentheses with
commas. In the following example, the MyTable variable is a two-dimensional array consisting
of 6 rows and 11 columns:
Dim MyTable(5, 10)
In a two-dimensional array, the first number is always the number of rows; the second
number is the number of columns.
You can also declare an array whose size changes during the time your script is running.
This is called a dynamic array. The array is initially declared within a procedure using either
the Dim statement or using the ReDim statement. However, for a dynamic array, no size
or number of dimensions is placed inside the parentheses. Example:
(Dim AnArray()
ReDim AnotherArray()
To use a dynamic array, you must subsequently use ReDim to determine the number of
dimensions and the size of each dimension. In the following example, ReDim sets the initial
size of the dynamic array to 25. A subsequent ReDim statement resizes the array to 30,
but uses the Preserve keyword to preserve the contents of the array as the resizing takes
place.
ReDim MyArray(25)
...
ReDim Preserve MyArray(30)
■ Constants
A constant is a meaningful name that takes the place of a number or string and never
changes. VBScript defines a number of intrinsic constants . You can get information about
these intrinsic constants from the VBScript Language Reference.
You create user-defined constants in VBScript using the Const statement. So you can assign
a meaningful name to string or numerical constants. Then you can assign them literal values
and use them in a script.
Process Control Engine (PCE) 117
The string literal is enclosed in quotation marks (e.g. “sample text"). Quotation marks are
the most obvious way to differentiate string values from numeric values. You represent Date
literals and time literals by enclosing them in number signs (#).
You may want to adopt a naming scheme to differentiate constants from variables. This will
prevent you from trying to reassign constant values while your script is running. For example,
you might want to use a "vb" or "con" prefix on your constant names, or you might name
your constants in all capital letters. Care that constants and variables can be distinguished.
So you avoid problems when creating complex scripts.
■ Operators
VBScript has a full range of operators, including arithmetic operators, comparison operators,
concatenation operators, and logical operators.
Operator Precedence
If several operators appear in a statement, each part is evaluated and resolved in a
pre-defined sequence. This sequence is called operator precedence. You can use
parentheses to override the order of precedence and force some parts of an expression to
be evaluated before others. Operations within parentheses are always performed before
those outside. Within parentheses, however, standard operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic operators
are evaluated first, comparison operators are evaluated next, and logical operators are
evaluated last. Comparison operators all have equal precedence; that is, they are evaluated
in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated
in the following order of precedence.
Arithmetic Operators
Description Symbol
Exponentiation ^
Unary negation -
Multiplication *
Division /
Integer division /
Addition +
118 Process Control Engine (PCE)
Subtraction -
String concatenation
Comparison Operators
Description Symbol
Equality =
Inequality <>
Opject equivalence Is
Logical Operators
If several operators appear in a statement, each part is evaluated and resolved in a
pre-defined sequence. This sequence is called operator precedence. You can use
parentheses to override the order of precedence and force some parts of an expression to
be evaluated before others. Operations within parentheses are always performed before
those outside. Within parentheses, however, standard operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic operators
are evaluated first, comparison operators are evaluated next, and logical operators are
evaluated last. Comparison operators all have equal precedence; that is, they are evaluated
in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated
in the following order of precedence.
■ Conditional Statements
You can control the flow of your script with conditional statements and looping statements.
Using conditional statements, you can write VBScript code that makes decisions and repeats
actions.
End Sub
To run more than one line of code, you must use the multiple-line (or block) syntax. This
syntax includes the End If statement, as shown in the following example:
Sub AlertUser(value)
If value = 0 Then
AlertLabel.ForeColor = vbRed
AlertLabel.Font.Bold = True
AlertLabel.Font.Italic = True
End If
End Sub
To run only one statement when a condition is True, use the single-line syntax for the
If...Then...Else statement. The following example shows the single-line syntax. In this
example, the key word Else is left out.
Sub FixDate()
Dim myDate
myDate = #2/13/95#
If myDate < Now Then myDate = Now
End Sub
To run more than one line of code, you must use the multiple-line (or block) syntax. This
syntax includes the End If statement, as shown in the following example:
Sub AlertUser(value)
If value = 0 Then
AlertLabel.ForeColor = vbRed
AlertLabel.Font.Bold = True
AlertLabel.Font.Italic = True
End If
End Sub
Sub ReportValue(value)
If value = 0 Then
MsgBox value
ElseIf value = 1 Then
MsgBox value
ElseIf value = 2 then
Msgbox value
Else
Msgbox Walue out of range!
End If
Parameters Description
Using For...Next (on Uses a counter to run statements a specified number of times.
page 123) :
Process Control Engine (PCE) 121
Using For Repeats a group of statements for each item in a collection or each element of an
Each...Next (on array.
page 123) :
Using Do Loops
You can use Do...Loop statements to run a block of statements an indefinite number of
times. The statements are repeated either while a condition is True or until a condition
becomes True.
MsgBox 'The loop made ' & counter & ' repetitions.'
End Sub
Sub ChkLastWhile()
Dim counter, myNum
counter = 0
myNum = 9
Do myNum = myNum - 1
counter = counter + 1
Loop While myNum > 10
MsgBox 'The loop made ' & counter & ' repetitions.'
End Sub
myNum = 20
Do Until myNum = 10
myNum = myNum - 1
counter = counter + 1
Loop
MsgBox 'The loop made ' & counter & ' repetitions.'
End Sub
Sub ChkLastUntil()
Dim counter, myNum
counter = 0
myNum = 1
Th
myNum = myNum - 1
counter = counter + 1
Loop Until myNum = 10
MsgBox 'The loop made ' & counter & ' repetitions.'
End Sub
MsgBox 'The loop made ' & counter & ' repetitions.'
End Sub
Process Control Engine (PCE) 123
Using While...Wend
The While...Wend statement is provided in VBScript for those who are familiar with its
usage. However, because of the lack of flexibility in While...Wend, it is recommended that
you use Do...Loop instead.
Using For...Next
You can use For...Next statements to run a block of statements a specific number of times.
For loops, use a counter variable whose value increases or decreases with each repetition
of the loop.
The following example causes a procedure called MyProc to execute 50 times. The For
statement specifies the counter variable x and its start and end values. The Next statement
increments the counter variable by 1.
Sub DoMyProc50Times()
Dim x
For x = 1 To 50
MyProc
Next
End Sub
Using the Step keyword, you can increase or decrease the counter variable by the value
you specify. In the following example, the counter variable j is incremented by 2 each time
the loop repeats. When the loop is finished, the total is the sum of 2, 4, 6, 8, and 10.
Sub DoMyProc50Times()
Dim x
For x = 1 To 50
MyProc
Next
End Sub
To decrease the counter variable, use a negative Step value. You must specify an end
value that is less than the start value. In the following example, the counter variable myNum
is decreased by 2 each time the loop repeats. When the loop is finished, total is the sum of
16, 14, 12, 10, 8, 6, 4, and 2.
Sub NewTotal()
Dim myNum, total
For myNum = 16 To 2 Step -2
total = total + myNum
Next
item in a collection of objects or for each element of an array. This is especially helpful if
you don't know how many elements are in a collection.
In the following HTML code example, the contents of a Dictionary object is used to place
text in several text boxes.
<HTML>
<HEAD><TITLE>Formulare und Elemente</TITLE></HEAD>
<SCRIPT LANGUAGE='VBScript'>
<!--
Sub cmdChange_OnClick
Dim d 'Create a variable
Set d = CreateObject('Scripting.Dictionary')
d.Add '0', 'Athen' 'Add some keys and items
d.Add '1', 'Belgrad'
d.Add '2', 'Kairo'
ForEach I in d
Document.frmForm.Elements(I).Value = D.Item(I)
Next
End Sub
-->
</SCRIPT>
<BODY>
<CENTER>
<FORM NAME='frmForm'
<Input Type = 'Text'><p>
<Input Type = 'Text'><p>
<Input Type = 'Text'><p>
<Input Type = 'Text'><p>
<Input Type = 'Button' NAME='cmdChange' VALUE='Hierauf klicken'><p>
</FORM>
</CENTER>
</BODY>
</HTML>
■ Types of procedures
Sub Procedures
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub
statements) that perform actions but don't return a value. A Sub procedure can take
arguments (constants, variables, or expressions that are passed to it by a calling procedure).
Process Control Engine (PCE) 125
If a Sub procedure has no arguments, its Sub statement must include an empty set of
parentheses ().
The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and
InputBox, to prompt a user for information. It then displays the results of a calculation based
on that information. The calculation is performed in a Function procedure created using
VBScript. The Function procedure is shown after the following discussion.
Sub ConvertTemp()
temp = InputBox('Please enter the temperature in degrees F.', 1)
MsgBox 'The temperature is ' & Celsius(temp) & ' degrees C.'
End Sub
Function Procedures
A Function procedure is a series of VBScript statements enclosed by the Function and
End Function statements. A Function procedure is similar to a Sub procedure, but can
also return a value. A Function procedure can take arguments (constants, variables, or
expressions that are passed to it by a calling procedure). If a Function procedure has no
arguments, its Function statement must include an empty set of parentheses. A Function
returns a value by assigning a value to its name in one or more statements of the procedure.
The return type of a Function is always a Variant.
In the following example, the Celsius function calculates degrees Celsius from degrees
Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable
containing the argument value is passed to the function.The result of the calculation is
returned to the calling procedure and displayed in a message box.
Sub ConvertTemp()
temp = InputBox('Please enter the temperature in degrees F.', 1)
MsgBox 'The temperature is ' & Celsius(temp) & ' degrees C.'
End Sub
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
Examples:
Temp = Celsius(fDegrees)
or
MsgBox 'The temperature is ' & Celsius(temp) & ' degrees C.'
To call a Sub procedure from another procedure, type the name of the procedure along
with values for any required arguments, each separated by a comma. The Call statement
is not required, but if you do use it, you must enclose any arguments in parentheses.
The following example shows two calls to the MyProc procedure. In the one case the Call
statement is used in the code, in the other one it is not. Both calls have the same result.
Call MyProc(firstarg, secondarg)
MyProc firstarg, secondarg
■ Coding Conventions
Coding conventions are suggestions are designed to help you write code using Microsoft
Visual Basic Scripting Edition.
Coding conventions can include the following:
Commenting conventions
The main reason for using a consistent set of coding conventions is to standardize the
structure and coding style of a script or set of scripts so that you and others can easily read
and understand the code. Using good coding conventions results in clear, precise, and
readable source code that is consistent with other language conventions and is intuitive.
Variable Scope
Variables should always be defined with the smallest scope possible. VBScript variables
can have the following scope.
Procedure-level Event, Function, or Sub procedure. Visible in the procedure in which it is de-
clared.
Script-level HEAD section of an HTML page, outside Visible in every procedure in the script.
any procedure.
Assumptions List of the procedure's effect on each external variable, control, or other ele-
ment.
Effects List of the procedure's effect on each external variable, control, or other ele-
ment.
Inputs Explanation of each argument that is not obvious. Each argument should be
on a separate line with inline comments.
Every important variable declaration should include an inline comment describing the use of the variable
being declared.
Variables, controls, and procedures should be named clearly to ensure that inline comments are only needed
for complex implementation details.
At the beginning of your script, you should include an overview that describes the script, enumerating objects,
procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode
describing the algorithm can be helpful.
Code formating
Screen space should be conserved as much as possible, while still allowing code formatting
to reflect logic structure and nesting. Here are a few suggestions:
• Indent standard nested blocks four spaces.
• Indent the overview comments of a procedure one space.
• The statements on the highest level, directly following the overview comment, should
be indented with four blanks. Each nested block should again be indented by four blanks.
Example:
The following code adheres to VB Script coding conventions.
• ' Purpose: Searches for the first appearance of the stated user in the data field UserList.
• Inputs: strUserList(): the list of users to be searched.
• strZielUser: the name of the user to search for.
• Return values: Index of the first appearance of strTargetUser in the data field strUserList.
If the target user is not found, return -1. -1.
Function intFindUser (strUserList(), strTargetUser)
Dim i ' Loop counter.
End Function
130
Object Model 131
6
Object Model
In this area you can find the zenon Object Model help. This is available for Add-Ins as well
as VBA, VSTA and the external COM interface.
You can find the most-recent version online at: https://onlinehelp.copadata.com.
—
Further information
Project support
You can receive support for all real projects you may have from our Support team. Contact via
email at [email protected].
General help
If you cannot find any information you require in this help chapter or can think of anything that
you would like added, contact via email at [email protected].
[email protected]
[email protected]
www.abb.com/zenon
3AXD50000327140 v.8.10 Rev B (EN) EFFECTIVE 2019-09-16
© 2019 ABB Oy. All rights reserved. Printed under license of Ing. Punzenberger COPA-DATA GmbH.Distribution and/or reproduction of this document or
parts thereof in any form are permitted solely with the written permission of the company COPA-DATA. Technical data is only used for product description
and are not guaranteed qualities in the legal sense. Subject to change, technical or otherwise.