Học vb trong wincc

36

Click here to load reader

description

wincc

Transcript of Học vb trong wincc

Page 1: Học vb trong wincc

HỌC VB TRONG WINCCCác lệnh trong VB

1. HMIRuntime Object

Description

The HMIRuntime object represents the graphic runtime environment.

Usage

The "HMIRuntime" object can be used for the following, for example:

Read or set the current Runtime language ("Language" property).

Read or set the name of the current base picture ("BaseScreenName" property).

Read the path of the active Runtime project ("ActiveProject" property).

Access tags ("Tags" property).

Access tags of a list ("DataSet" property).

Exit runtime ("Stop" method).

Display messages in a diagnostics window ("Trace" method).

Example

The following command terminates WinCC runtime:

'VBS3

HMIRuntime.Stop

 DataSet Object (List)

Description

1

Page 2: Học vb trong wincc

Using the DataSet object, data may be exchanged across several actions.

A DataSet object is global and defined by the Screen object. Any VBS action may access the

data.

The DataSet object at the Screen object must be addressed according to picture hierarchy and

shall persist as long as the picture is displayed. The global object persists over the entire Runtime

time period.

Access uses the DataItem object.   

Note:

Objects of type Screen, Screens, ScreenItem, ScreenItems, Tag and TagSet cannot be included in

the DataSet list.

The DataSet object does not support any classes.

 Usage

Using the "DataSet" list, you may:

Output or process (enumerate) all objects in the list.

Output the number of elements contained ("Count" property).

Process a specific object in the list ("Item" method).

Add an object to the list ("Add" method).

Remove a specific object from the list ("Remove" method).

Remove all objects from the list ("RemoveAll" method).

 Access to list elements uses:

 HMIRuntime.DataSet("Itemname")

 For a picture-specific list, access uses:

 HMIRuntime.Screens("Screenname").DataSet("Itemname")

 In a picture, you may access the DataSet object of the picture by using:

 DataSet("Itemname")

 If upon access the stated name does not exist in the list, VT_Empty is returned and an Exception

is triggered.

Example

The example shows how to add a value to the list, how to read it and remove it. It make sense to

perform this in several different actions.

2

Page 3: Học vb trong wincc

 'VBS162

HMIRuntime.DataSet.Add "motor1", 23

HMIRuntime.Trace "motor1: " & HMIRuntime.DataSet("motor1").Value & vbNewLine

HMIRuntime.DataSet.Remove("motor1")

The DataItem object is used to access the contents of the DataSet list. Values or object references

are stored in the list as DataItem.

Access uses the name under which the value was added to the list. Single access using an index is

not recommended since the index changes during adding or deleting of values. The index may be

used to output the complete contents of the list. The output is in alphabetical order.

Note:

For object references it must be ascertained that objects are multiread-enabled.

 Example

The example shows how the value of 'Motor1' is output as Trace.

 'VBS163

HMIRuntime.Trace "motor1: " & HMIRuntime.DataSet("motor1").Value & vbNewLine

 The following example enumerates all DataItem objects of the DataSet list. Name and value are

output as Trace.

'VBS164

Dim data

For Each data In HMIRuntime.DataSet

HMIRuntime.Trace data.Name & ": " & data.Value & vbNewLine

Next

 Note:

For objects, value may possibly not be output directly

ActiveScreen Property

Description

Supplies a reference to the picture which contains the object with the current focus.

Usage

"ActiveScreen" is used in Runtime to address the properties of the picture which contains the

currently focussed object.

Example

The following example assigns the name of the current picture to the tag "strScrName" and

outputs it in a message:

 'VBS68

Dim strScrName

strScrName = HMIRuntime.ActiveScreen.Objectname

MsgBox strScrName

3

Page 4: Học vb trong wincc

BaseScreenName Property

Function

Defines or returns the current basic picture.

STRING (write-read access)

A picture change is executed using the

HMIRuntime.BaseScreenName = (<Serverpräfix>::)<Neues Grundbild>

command.

When reading out the "BaseScreenName" property, only the picture name without server prefix is

returned.

Note:

Always enter picture names without the extension "PDL" for reasons of compatibility with future

versions.

Example

The following example executes a picture change to "bild1.pdl":

HMIRuntime.BaseScreenName = "bild1"

Screens Property

Description

Returns an object of type "Screens".

Screens (read only)

Example

The following example accesses the picture "NewPDL1":

 'VBS84

Dim objScreen

Set objScreen = HMIRuntime.Screens("NewPDL1")

Tags Property

Description

Returns an object of type "Tags".

Tags (read only)

Example

The following example accesses the tag "Tag1":

Example

The following example accesses the tag "Tag1":

 'VBS86

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

4

Page 5: Học vb trong wincc

Set oVisible Property

Description

witches an object visible or invisible or issues a corresponding value:

TRUE: Object is visible

FALSE: Object is invisible

VARIANT_BOOL (write-read access)

Example

The following example sets all the objects in the picture "NewPDL1" to invisible:

'VBS95

Dim objScreen

Dim objScrItem

Dim lngIndex

Dim strName

lngIndex = 1

Set objScreen = HMIRuntime.Screens("NewPDL1")

For lngIndex = 1 To objScreen.ScreenItems.Count

strName = objScreen.ScreenItems(lngIndex).ObjectName

Set objScrItem = objScreen.ScreenItems(strName)

objScrItem.Visible = False

Next

5

Page 6: Học vb trong wincc

MỘT SỐ BÀI TẬP MẪU VB TRONG WINCC

Example: Accessing objects in Graphics Designer

Introduction

Access can be made to all Graphic Designer objects using VBS WinCC in order to make the graphic runtime environment dynamic. Graphic objects can be made dynamic on operation (e.g. clicking the mouse on a button), depending on a tag or cyclically (e.g. flashing).

The following examples illustrate how to change a graphic object following a mouse click.

Procedure

In the following example, the radius of a circle is set to 20 in runtime per mouse click:

'VBS121

Dim objCircle

Set objCircle = ScreenItems("Circle1")

objCircle.Radius = 20

Note:

The expression used in the example only applies to Graphics Designer. In the case of analog actions in Global Script, address the objects using the HMIRuntime object.

Example: Defining the color of objects

Introduction

The colors of graphic objects are defined via RGB values (Red/Green/Blue). The color values for graphic objects can be set or read out.

Procedure

The following example defines the fill color for "ScreenWindow1" to blue:

'VBS122

Dim objScreen

6

Page 7: Học vb trong wincc

Set objScreen = HMIRuntime.Screens("ScreenWindow1")

objScreen.FillStyle = 131075

objScreen.FillColor = RGB(0, 0, 255)

Example: Configuring language changes

Introduction

The runtime language of WinCC can be changed using VBS. The most typical use is buttons with the corresponding language codes which are placed on the start page of a project.

The runtime language is specified in VBS by means of a language code, e.g. 1031 for German - Germany, 1033 for English - United States etc. An overview of all language codes is provided in the principles of VBScript under the topic "Locale ID (LCID) Chart ".

Procedure

Use the "Mouse click" event on a button to create a VBS action and enter the following action code to switch the runtime language to German:

'VBS123

HMIRuntime.Language = 1031

Example: Deactivating runtime

Introduction

It is possible to terminate WinCC runtime with VBS, e.g. via a mouse click or on tag values or other events, such as multiple faulty input of a password when starting runtime.

Procedure

The following example terminates WinCC runtime:

 

'VBS124

HMIRuntime.Stop

7

Page 8: Học vb trong wincc

Example: Configuring change picture globally

Introduction

VBS can be used to initiate a global picture change and thus, for example, display a picture from a server on a client in a distributed system. To do this, server's server prefix must precede the target picture.

Procedure

Configure the following code for a picture change to a button, for example:

'VBS125

HMIRuntime.BaseScreenName = "Serverprefix::New screen"

Example: Configuring Change Picture Via Property

Introduction

If partitioned pictures are used in the configuration, e.g. in a basic picture title and operating bar for the user interface and an embedded picture window for the actual picture display, configure a picture change using the properties of the picture window.

The property of the "ScreenName" picture window must be changed in order for the other picture to appear. The action and picture window must be configured in the same picture.

Procedure

In the following example, the "test.pdl" picture is displayed in the "ScreenWindow" picture window when executing the action:

'VBS126

Dim objScrWindow

Set objScrWindow = ScreenItems("ScreenWindow")

objScrWindow.ScreenName = "test"

8

Page 9: Học vb trong wincc

Example: Configuring diagnostic output via Trace

Introduction

If a GSC diagnostics window has been inserted in the picture, diagnostic output can be displayed in the diagnostics window in runtime using the Trace command.

GSC Diagnostics issues the Trace methods contained in the actions in the chronological sequence they are called. This also applies to Trace instructions in procedures which are called in actions. The targeted implementation of Trace instructions, e.g. for the output of tag values, enables the progress of actions and the procedures called in them to be traced. The Trace instructions are entered in the form "HMIRuntime.Trace(<output>)".

The GSC Diagnostics displays trace output from C and VBS.

Procedure

The following example writes a text in the diagnostics window:

'VBS127

HMIRuntime.Trace "Customized error message"

Example: Writing tag values

Introduction

Using VBS, it is possible to write a tag value to the PLC, e.g. by clicking the mouse on a button to specify setpoint values, or to set internal tag values to trigger other actions.

Various write variations are mentioned and explained below.

Simple writing

In the following example, a value is written to the "Tag1" tag:

'VBS128

HMIRuntime.Tags("Tag1").Write 6

This is the simplest form of writing since no object reference is generated.

Writing with object reference

In the following example, a local copy of the tag object is created and a value written to "Tag1":

9

Page 10: Học vb trong wincc

'VBS129

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

objTag.Write 7

Referencing offers the advantage of being able to work with the tag object before writing. The tag value can be read, calculations executed and written again:

'VBS130

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

objTag.Read

objTag.Value = objTag.Value + 1

objTag.Write

Synchronous writing

Normally, the value to be written is transferred to the tag management and processing of the action resumed. In some cases, however, it must be ensured that the value has actually been written before processing of the action can be resumed.

This type of writing is realized by specifying the value 1 for the additional, optional parameters:

'VBS131

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

objTag.Write 8,1

or

'VBS132

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

objTag.Value = 8

10

Page 11: Học vb trong wincc

objTag.Write ,1

Note:

Please note that the call takes longer in comparison to the standard call. The duration is also dependent on the channel and AS, amongst other things.

The type of writing complies to the SetTagXXXWait() call in C scripting.

Writing with status handling

In order to ensure that a value has been written successfully, it is necessary to execute an error check or determine the status of the tag, after the writing process.

This is done by checking the value of the "LastError" property after writing. When the test proves successful, i.e. the job has been placed successfully, the tag status is checked.

In the case of a write job, the current status from the process is not determined. To establish this, it is necessary to read the tag. The value specified in the Quality Code property after the read process provides an indication of the tag status and, if necessary, makes reference to a failed AS connection.

In the following example, the "Tag1" tag is written. If an error occurs during writing, the error value and error description appear in the Global Script diagnostics window. Finally, the Quality Code is checked. If the Quality Code is OK (0x80), it is displayed in the diagnostics window.

'VBS133

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

objTag.Write 9

If 0 <> objTag.LastError Then

HMIRuntime.Trace "Error: " & objTag.LastError & vbCrLf & "ErrorDescription: " & objTag.ErrorDescription & vbCrLf

Else

objTag.Read

If &H80 <> objTag.QualityCode Then

HMIRuntime.Trace "QualityCode: 0x" & Hex(objTag.QualityCode) & vbCrLf

End If

11

Page 12: Học vb trong wincc

End If

Note:

After writing a tag, the QualityCode property of the local tag object from "BAD Out of Service" is set because it is not known which Quality Code manages the tag in the process.

The Quality Code cannot be written from VBS.

 

Example: How to Read Tag Values

Introduction

VBS can be used to read and further process a tag value. This makes it possible, for example, to click the mouse on a button to obtain information on the system status or to execute a calculation.

Various read variations are mentioned and explained below.

Simple reading

In the following example, the value of "Tag1" is read and displayed in the Global Script diagnostics window:

'VBS134

HMIRuntime.Trace "Value: " & HMIRuntime.Tags("Tag1").Read & vbCrLf

This is the simplest form of reading since no object reference is generated.

Reading with object reference

In the following example, a local copy of the tag object is created, the tag value read and displayed in the Global Script diagnostics window:

'VBS135

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

HMIRuntime.Trace "Value: " & objTag.Read & vbCrLf

Referencing offers the advantage of being able to work with the tag object. The tag value can be read, calculations executed and written again:

'VBS136

12

Page 13: Học vb trong wincc

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

objTag.Read

objTag.Value = objTag.Value + 1

objTag.Write

Using the Read method, process tags which have been read are added to the image, from this moment on they cyclically requested from the AS. If the tag is already in the image, the value contained in it is returned.

On closing the picture, the tags are logged off again.

Note:

If a tag is requested in a Global Script action, it remains logged on for the entire WinCC runtime period.

Direct reading

Normally, the tag values are read from the tag image. In certain situations, however, it may be necessary to read the value direct from the AS, e.g. to synchronize fast processes.

If the optional parameter is set to 1 for the read process, the tag is not logged in cyclically but the value is requested once from the AS.

'VBS137

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

HMIRuntime.Trace "Value: " & objTag.Read(1) & vbCrLf

Note:

Please note that the call takes longer in comparison to the standard call. The duration is also dependent on the channel and AS, amongst other things.

This type of call must be avoided in the case of cyclic C actions because this is the main reason for performance problems.

This type of read process corresponds to GetTagXXXWait() call from C scripting.

Reading with status handling

13

Page 14: Học vb trong wincc

In order to ensure that a value is valid, a check should be made following reading. This occurs by the fact that the Quality Code is controlled.

In the following example, the "myWord" tag is read and the QualityCode then checked. When the Quality Code does not correspond to OK (0x80) the LastError, ErrorDescription and QualityCode properties are displayed in the Global Script diagnostics window.

'VBS138

Dim objTag

Set objTag = HMIRuntime.Tags("Tag1")

objTag.Read

If &H80 <> objTag.QualityCode Then

HMIRuntime.Trace "Error: " & objTag.LastError & vbCrLf & "ErrorDescription: " & objTag.ErrorDescription & vbCrLf & "QualityCode: 0x" & Hex(objTag.QualityCode) &vbCrLf

Else

HMIRuntime.Trace "Value: " & objTag.Value & vbCrLf

End If

Note:

If an error occurs during reading, QualityCode is set to "BAD Out of Service". Therefore, it is sufficient to check the QualityCode following reading.

Example: How to Write Object Properties

Introduction

VBS enables access to the properties of all Graphics Designer picture objects. Properties can be read out to be modified or changed during runtime.

The following examples illustrate various forms of access.

Simple Setting of a Property

In the following example, the background color of the "Rectangle1" object contained in the picture is set to red:

'VBS139

ScreenItems("Rectangle1").BackColor = RGB(255,0,0)

14

Page 15: Học vb trong wincc

This is the simplest form of writing since no object reference is generated.

Note:

If the work is completed without an object reference, only the standard properties are provided in Intellisense.

Note:

The form of expression used in the example only applies to Graphics Designer. In the case of analog actions in Global Script, address the objects using the HMIRuntime object.

Setting a Property with Object Reference

In the following example, a reference is created to the "Rectangle1" object contained in the picture and the background is set to red using the VBS standard function RGB():

'VBS140

Dim objRectangle

Set objRectangle = ScreenItems("Rectangle1")

objRectangle.BackColor = RGB(255,0,0)

Referencing is useful when several object properties must be changed. When using Intellisense, this process then lists all the object properties.

Note:

The form of expression used in the example only applies to Graphics Designer. In the case of analog actions in Global Script, address the objects using the HMIRuntime object.

Setting Properties via the Picture Window

VBS in Graphics Designer offers two options for cross-picture addressing:

using the screen object of a picture window with "ScreenItems"

starting from the basic picture with "HMIRuntime.Screens"

Referencing the picture window

In the following example, the color of a rectangle is changed in the underlying picture window. The script is executed in the "BaseScreen" picture which contains the picture window "ScreenWindow1". The picture window displays a picture which contains an object of type "Rectangle" with the name "Rectangle1".

15

Page 16: Học vb trong wincc

'VBS199

Sub OnLButtonUp(ByVal Item, ByVal Flags, ByVal x, ByVal y)

Dim objRectangle

Set objRectangle = ScreenItems("ScreenWindow1").Screen.ScreenItems("Rectangle1")

objRectangle.BackColor = RGB(255,0,0)

End Sub

Referencing from the basic picture

You may also reference the picture with the object to be changed through HMIRuntime.Screens. The specification of the picture is defined relative to the basic picture via the following access code:

[<Basic picture name>.]<Picture window name>[:<Picture name>]... .<Picture window name>[:<Picture name>]

In the following example, a reference is created to the "Rectangle1" object contained in the "Screen2" picture and the background color is set to red.

The picture "Screen2", in this case, is in "Screen1". "Screen1" is displayed in the basic picture "BaseScreen".

'VBS141

Dim objRectangle

Set objRectangle = HMIRuntime.Screens("BaseScreen.ScreenWindow1:Screen1.ScreenWindow1:Screen2").ScreenItems("Rectangle1")

objRectangle.BackColor = RGB(255,0,0)

It is not necessary to specify the picture name. It is possible to address a picture uniquely using the picture window name. Therefore, it is sufficient to specify the name of the picture window, as in the following example:

'VBS142

Dim objRectangle

Set objRectangle = HMIRuntime.Screens("ScreenWindow1.ScreenWindow1").ScreenItems("Rectangle1")

16

Page 17: Học vb trong wincc

objRectangle.BackColor = RGB(255,0,0)

This type of addressing enables objects in picture windows to be addressed in different pictures. This is a particularly interesting aspect in respect of the picture module technique.

Making the Property Dynamic Using the Return Value

Actions on properties can not only be triggered by events or cyclically but properties can also be made dynamic directly via an action.

In the following example, the background color of an object is made dynamic via a return value. The value transferred can come from the evaluation of events in the PLC, for example and used for the graphic display of an operating status:

'VBS146

Function BackColor_Trigger(ByVal Item)

BackColor_Trigger = RGB(125,0,0)

End Function

Caution

If you make an object property dynamic with a VBS action via the return value of a script, the value of the object property is written only if it has changed in relation to the last script run. It is not considered if the value had been changed from another location.

Therefore it is illegal to change properties which have been made dynamic by VBS action via the return value from another location (e.g., other C scripts or VBS scripts).

if you do not observe this, wrong values can be the results.

 Example: How to Start an Action on the Server (Logging Object)

Introduction

In multi-user projects, the Logging object presently functions on the server only. The following example shows how to start an action on the server from the client, and how to swap and delete archive segments on client accordingly.

The example shows a global action started with a control tag. The contents of the control tag determine whether the "Restore" method or the "Remove" method is called. At the end of the action, the control tag is set to "0".

A query prevents the action from being started on client computers.

Path and time period are passed on by internal tags.

17

Page 18: Học vb trong wincc

The path information may also contain a network release. Archive segments to be swapped must therefore not be stored locally at the server. It must be warranted, though, that the server may directly access the path.

Note:

The example shows a delete suggestion and may be adjusted as needed.

Procedure

1. In WinCC Explorer, create the following internal tags with project-wide updates:- StartLogging (Unsigned 8-bit value)- SourcePath (Text tag 8-bit character set)- TimeFrom (Text tag 8-bit character set)- TimeTo (Text tag 8-bit character set)- RetVal (Signed 32-bit value)

2. Create a global VBS action and enter the tag ’StartLogging’ as tag trigger with cycle "Upon Change".

3. Copy the following script into the action

 

'VBS180

Dim StartLogging

Dim SourcePath

Dim TimeFrom

Dim TimeTo

Dim RetVal

'Exit when running on client

If (Left(HMIRuntime.ActiveProject.Path, 1) = "\") Then

Exit Function

End If

'read parameters

StartLogging = HMIRuntime.Tags("StartLogging").Read

SourcePath = HMIRuntime.Tags("SourcePath").Read(1)

18

Page 19: Học vb trong wincc

TimeFrom = HMIRuntime.Tags("TimeFrom").Read(1)

TimeTo = HMIRuntime.Tags("TimeTo").Read(1)

'restore or remove depends on the parameter

If (StartLogging = 1) Then

RetVal = HMIRuntime.Logging.Restore(SourcePath, TimeFrom, TimeTo, -1)

HMIRuntime.Tags("RetVal").Write RetVal, 1

HMIRuntime.Tags("StartLogging").Write 0,1

Elseif (StartLogging = 2) Then

RetVal = HMIRuntime.Logging.Remove(TimeFrom, TimeTo, -1)

HMIRuntime.Tags("RetVal").Write RetVal, 1

HMIRuntime.Tags("StartLogging").Write 0,1

End If

The action may be started on a client with the following action, for example. Please note that parameters must be written prior to setting the control tag.  

 

'VBS181

'set parameters

HMIRuntime.Tags("SourcePath").Write "\\client_pc\temp",1

HMIRuntime.Tags("TimeFrom").Write "2004",1

HMIRuntime.Tags("TimeTo").Write "2004",1

'start action

HMIRuntime.Tags("StartLogging").Write 1,1

 

Note:

19

Page 20: Học vb trong wincc

Tags are predominantly written and read in "direct" mode. This will synchronize the sequences. Since this deals with internal tags, this mode may be used without any further concerns.

General examples for VBScript

Introduction

Note:

All objects supplied with the Windows Script Host (WSH) from Microsoft can be integrated in their environment using the standard VBS method CreateObject. However, there is no direct access to the WSH object itself using VBS from WinCC.

Example 1: "FileSystemObject" object for working with the file system

Dim fso, MyFile

Set fso = CreateObject("Scripting.FileSystemObject")

Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)

MyFile.WriteLine("This is a test.")

MyFile.Close

Example 2: "WScript.Shell" object for working with the Windows environment

This section contains examples of the general use of VBScript with regard to the following topics:

Programming Data Connection with VBS

Calling Methods

MS-Using the Automation Interface

Starting External Applications

20

Page 21: Học vb trong wincc

Example: Configuring a Database Connection with VBS

Introduction

The following examples describe the configuration of an Access database link via an ODBC driver.

Example 1 writes a tag value from WinCC in an Access database.

Example 2 reads a value from the database and writes it in a WinCC tag.

The examples do not contain any handling faults.

Procedure, Example 1

1. Create the Access database with the WINCC_DATA table and columns (ID, TagValue) with the ID as the Auto Value.

2. Set up the ODBC data source with the name "SampleDSN", reference to the above Access database.

3. Programming.

Example 1

'VBS108

Dim objConnection

Dim strConnectionString

Dim lngValue

Dim strSQL

Dim objCommand

strConnectionString = "Provider=MSDASQL;DSN=SampleDSN;UID=;PWD=;"

lngValue = HMIRuntime.Tags("Tag1").Read

strSQL = "INSERT INTO WINCC_DATA (TagValue) VALUES (" & lngValue & ");"  

Set objConnection = CreateObject("ADODB.Connection")

objConnection.ConnectionString = strConnectionString

objConnection.Open

21

Page 22: Học vb trong wincc

Set objCommand = CreateObject("ADODB.Command")

With objCommand

    .ActiveConnection = objConnection

    .CommandText = strSQL

End With

objCommand.Execute

Set objCommand = Nothing

objConnection.Close

Set objConnection = Nothing

Procedure, Example 2

1. Create the WinCC tag with the name dbValue.2. Create Access database with WINCC_DATA table and ID, TagValue columns: (ID as

Auto Value).

3. Set up the ODBC data source with the name "SampleDSN", reference to the above Access database.

4. Programming.

Example 2

'VBS108a

Dim objConnection

Dim objCommand

Dim objRecordset

Dim strConnectionString

Dim strSQL

Dim lngValue

Dim lngCount

strConnectionString = "Provider=MSDASQL;DSN=SampleDSN;UID=;PWD=;"

22

Page 23: Học vb trong wincc

strSQL = "select TagValue from WINCC_DATA where ID = 1"

Set objConnection = CreateObject("ADODB.Connection")

objConnection.ConnectionString = strConnectionString

objConnection.Open

Set objRecordset = CreateObject("ADODB.Recordset")

Set objCommand = CreateObject("ADODB.Command")

objCommand.ActiveConnection = objConnection

objCommand.CommandText = strSQL

Set objRecordset = objCommand.Execute

lngCount = objRecordset.Fields.Count

If (lngCount>0) Then

objRecordset.movefirst

lngValue = objRecordset.Fields(0).Value

HMIRuntime.Tags("dbValue").Write lngValue

Else

HMIRuntime.Trace "Selection returned no fields" & vbNewLine

End If

Set objCommand = Nothing

objConnection.Close

Set objRecordset = Nothing

Set objConnection = Nothing

 

There are several ways in which to define the ConnectionString for the connection depending on the provider used:

Microsoft OLE DB provider for ODBC

23

Page 24: Học vb trong wincc

Enables connections to any ODBC data source. The corresponding syntax is:

"[Provider=MSDASQL;]{DSN=name|FileDSN=filename};

[DATABASE=database;]UID=user; PWD=password"

Other Microsoft OLE DB Provider (e.g. MS Jet, MS SQL Server)

It is possible to work without DSN. The corresponding syntax is:

"[Provider=provider;]DRIVER=driver; SERVER=server;

DATABASE=database; UID=user; PWD=password"

 Example: CCalling Methods of an ActiveX Control

Introduction

The following examples illustrate how to call methods and properties of an ActiveX control which is embedded in a WinCC picture.

Example 1: MS Form 2.0 Combobox

This example fills a combobox with the name "ComboBox1" from any point in the picture.

'VBS109

Dim cboComboBox

Set cboComboBox = ScreenItems("ComboBox1")

cboCombobox.AddItem "1_ComboBox_Field"

cboComboBox.AddItem "2_ComboBox_Field"

cboComboBox.AddItem "3_ComboBox_Field"

cboComboBox.FontBold = True

cboComboBox.FontItalic = True

cboComboBox.ListIndex = 2

Example 2: MS Form 2.0 Listbox

This example fills a list box with the name "ListBox1" from any point in the picture.

'VBS110

24

Page 25: Học vb trong wincc

Dim lstListBox

Set lstListBox = ScreenItems("ListBox1")

lstListBox.AddItem "1_ListBox_Field"

lstListBox.AddItem "2_ListBox_Field"

lstListBox.AddItem "3_ListBox_Field"

lstListBox.FontBold = True

Example 3: WinCC Function Trend Control

This example fills the trend control function named "Control1" with the values which describe a parabola.

'VBS111

Dim lngFactor

Dim dblAxisX

Dim dblAxisY

Dim objTrendControl

Set objTrendControl = ScreenItems("Control1")

For lngFactor = -100 To 100

dblAxisX = CDbl(lngFactor * 0.02)

dblAxisY = CDbl(dblAxisX * dblAxisX + 2 * dblAxisX + 1)

objTrendControl.DataX = dblAxisX

objTrendControl.DataY = dblAxisY

objTrendControl.InsertData = True

Next

Example 4: WinCC Function Trend Control with Values Supplied Via Arrays

In this example, a Function Trend Control called "Control1" is supplied with 100 value pairs. In order that the value pair can be transferred correctly, the transfer e.g. in "dblAxisXY" must not occur directly but via an intermediate tag, e.g. "varTemp".

25

Page 26: Học vb trong wincc

'VBS152

Dim lngIndex

Dim dblXY(1)

Dim dblAxisXY(100)

Dim varTemp

Dim objTrendControl

Set objTrendControl = ScreenItems("Control1")

For lngIndex = 0 To 100

 dblXY(0) = CDbl(lngIndex * 0.8)

 dblXY(1) = CDbl(lngIndex)

 dblAxisXY(lngIndex) = dblXY

Next

varTemp = (dblAxisXY)

objTrendControl.DataXY = varTemp

objTrendControl.InsertData = True

Example 5: Microsoft Web Browser

This example controls MS Web Browser.

'VBS112

Dim objWebBrowser

Set objWebBrowser = ScreenItems("WebControl")

objWebBrowser.Navigate "http://www.siemens.de"

...

objWebBrowser.GoBack

...

26

Page 27: Học vb trong wincc

objWebBrowser.GoForward

...

objWebBrowser.Refresh

...

objWebBrowser.GoHome

...

objWebBrowser.GoSearch

...

objWebBrowser.Stop

...

Note:

Insert the instructions, separated by stops, in self-defined procedures. Declaration and assignments must always precede them.

Example: Using the MS Automation interface

Introduction

The following three examples illustrate how to use the MS Automation interface.

Example 1: MS Excel

In this example, an output value from an input field is written in an Excel table.

'VBS113

Dim objExcelApp

Set objExcelApp = CreateObject("Excel.Application")

objExcelApp.Visible = True

'

'ExcelExample.xls is to create before executing this procedure.

27

Page 28: Học vb trong wincc

'Replace <path> with the real path of the file ExcelExample.xls.

objExcelApp.Workbooks.Open "<path>\ExcelExample.xls"

objExcelApp.Cells(4, 3).Value = ScreenItems("IOField1").OutputValue

objExcelApp.ActiveWorkbook.Save

objExcelApp.Workbooks.Close

objExcelApp.Quit

Set objExcelApp = Nothing

Example 2: MS Access

This example opens a report from MS Access.

'VBS114

Dim objAccessApp

Set objAccessApp = CreateObject("Access.Application")

objAccessApp.Visible = True

'

'DbSample.mdb and RPT_WINCC_DATA have to create before executing

'this procedure.

'Replace <path> with the real path of the database DbSample.mdb.

objAccessApp.OpenCurrentDatabase "<path>\DbSample.mdb", False

objAccessApp.DoCmd.OpenReport "RPT_WINCC_DATA", 2

objAccessApp.CloseCurrentDatabase

Set objAccessApp = Nothing

Example 3: MS Internet Explorer

This example opens the MS IE.

'VBS115

28

Page 29: Học vb trong wincc

Dim objIE

Set objIE = CreateObject("InternetExplorer.Application")

objIE.Navigate "http://www.siemens.de"

Do

Loop While objIE.Busy

objIE.Resizable = True

objIE.Width = 500

objIE.Height = 500

objIE.Left = 0

objIE.Top = 0

objIE.Visible = True

 Example: Starting an external application

Introduction

The following two examples illustrate how to start an external application.

Example

'VBS117

Dim objWshShell

Set objWshShell = CreateObject("Wscript.Shell")

objWshShell.Run "Notepad Example.txt", 1

 

29

Page 30: Học vb trong wincc

30