0% found this document useful (0 votes)
3K views

VBA Basic Application For FactoryTalk View Site Edition

This document describes using VBA in FactoryTalk View SE to access tags in a PLC and write/read their values, as well as process historical data. It discusses creating a VBA application to toggle a tag's value by reading it and writing the opposite value. It also covers connecting to a SQL database using ADO, writing tag values and timestamps to a table on a button press, and displaying the stored data. Finally, it proposes recording the state of traffic light tags in a PLC demo program over time, storing it in SQL Server, and extracting the data into Excel for analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views

VBA Basic Application For FactoryTalk View Site Edition

This document describes using VBA in FactoryTalk View SE to access tags in a PLC and write/read their values, as well as process historical data. It discusses creating a VBA application to toggle a tag's value by reading it and writing the opposite value. It also covers connecting to a SQL database using ADO, writing tag values and timestamps to a table on a button press, and displaying the stored data. Finally, it proposes recording the state of traffic light tags in a PLC demo program over time, storing it in SQL Server, and extracting the data into Excel for analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

VBA Basic Application for FactoryTalk View Site Edition

The first section reads and writes tags in VBA


The goal in this case is to access the lower label in the PLC through the VBA at FactoryTalk View Site Edition
(hereinafter referred to as SE) and to read and write the tag.
Prepare for work
1. Open the SE, select the application type (in this case is Site Edition Network), the new application (this
example name: test), then under the test in the new area (in this case name: area1), in the area under the new
HMI Server ( This example named: HMI1), following the screenshot after completion:

Start RSLogix Emulate 5000 and add the emulation CPU. Start the RSLogix 5000 programming software,
create a new project, establish communication with the simulation PLC (Topic: TestTopic), and write a simple
test program and download to the simulation PLC.
Create a new OPC Data Server in SE

Create a new screen (named: TestDispaly) and draw a circle and a normal button
Right-click the button, click the Property Panel, the property box appears, the Name item to TestBtn,
ExposeToVBA entry to VBA Control as shown in Figure:
2. Write code and test
Right click on the button, click VBA Code (or press Alt + F11) to pop up the Visual Basic editor, as shown in
the figure

Add the following code:


On Error Resume Next
Dim TgGObj As TagGroup 'tag group object
Dim TagObj As Tag 'tag object
Set TgGObj = CreateTagGroup (Me.AreaName) 'Create a label group instance
TgGObj.Add ("[TestTopic] Tag1") Add labels to the label group
Set TagObj = TgGObj.Item ("[TestTopic] Tag1") 'Create a tag instance
If TagObj.Value = 1 Then 'reads the value of the label if the value of the label is 1
TagObj.Value = 0 'will write 0 to the label,
Else 'will write 1 to the label
TagObj.Value = 1
End If
Set TagObj = Nothing
Set TgGObj = Nothing
A tag group is a collection of labels. In SE VBA, we want to refer to the label, you need to create a label group,
and then the local label or remote label to join the label group, and then through the collection of access to the
label group label. It is worth noting that the tag type in SE is not a variable but an object, that is, we need to
refer to a single label in the label group with a label object rather than a normal variable.
Test screen, you can see the click button, round fill color will change, while in the RSLogix 5000 can also be
observed in the label state changes. Figure:
In SE:

Click the button


to turn green and
click the button
again to turn red

In RSLogix 5000:
Section II uses VBA to simply process the run history data
The operation of this example is to create a new local memory tag (tag name: TestTag) in SE, so that its value
increases with time (seconds), after each press the next storage button, real-time tag value and the
corresponding timestamp will be written Into the database, and then we can view the results in the database.
Prepare for work
In the SE in the new memory (memory) tag TestTag, type analog.
Create a new screen in the test application in the previous section and name it TestSimpleData and draw two
strings to display the controls and three buttons. Figure:

Attribute correspondence:
table 2.1
Whether it is exposed to
Types of Control name Tagged title
VBA
Create Tag
Button CreateTag Yes
Object
Button DropTag Yes Drop Tag Object
Button SaveData Yes Save
String
StringDisplay1 Yes System\DateAndTimeString
display
String
StringDisplay2 no TestTag
display
In the MS SQL Server in the new test database, after the test under the new simple table. The attributes of the
columns are as follows:
Table 2.2
Column name type of data description
Time Char(20) Time string
Value Smallint Tag value
2. Connect to the database and operate
ADO is a COM component provided by Microsoft for accessing data sources. It provides a middle tier of OLE
DB for programming languages and unified data access methods, allowing developers to write code to access
data without worrying about how the database is implemented, but only to the database. This example will use
ADO to implement database-related operations.
Select the reference after selecting the tool in the VBA editor

The following dialog box pops up


In the list on the left, locate Microsoft ActiveX Data Objects *. * (Where *. * Represents the version
number and the latest version is selected). So that we can refer to the ADO object in later programming.
3. Write code and test
Enter the following code in the VBA editor:
Private OTag As Tag
Private OtagG As TagGroup
Private Conn As New ADODB.Connection 'Creates an instance of Connection for ADO
Private Rs As New ADODB.Recordset 'Creates a Recordset instance of ADO

Private Sub CreateTag_Released ()


Set OtagG = CreateTagGroup (Me.AreaName)
OtagG.Add ("TestTag")
Set OTag = OtagG.Item (1)
Conn.ConnectionString = "provider = sqloledb;" & _
"Data Source = 127.0.0.1; Initial Catalog = test;" & _ "Specifies the database host address, database name
"User Id = sa; Password = 0;" 'Specifies the user name, password
Conn.Open 'to connect to the database
Rs.CursorLocation = adUseServer
Rs.CursorType = adOpenStatic
Rs.LockType = adLockOptimistic
Rs.Open "select * from simple", Conn 'returns the dataset from the database
End Sub

Private Sub SaveData_Released ()


Rs.AddNew 'to insert a record in the set
Rs.Fields.Item (0) .Value = Date $ & "" & Time $
Rs.Fields.Item (1) .Value = OTag.Value
Rs.Update 'writes data to the database
End Sub
Private Sub StringDisplay1_Change ()
On Error Resume Next
If Not OtagG Is Nothing Then _
OTag.Value = OTag.Value + 1 'When StringDisplay1 changes, TestTag is incremented by 1
End Sub

Private Sub DropTag_Released ()


Rs.Close
Conn.Close
OTag.Value = 0
Set OtagG = Nothing
End Sub

Test run. First press the Create Tag Object button to create the object for the next operation to prepare, and then
randomly press the Save button several times the different time TestTag value together with the time to write to
the database, and then press the Drop Tag Object button to close the object to release the connection and
memory space. The following figure shows the program running screenshots:

The figure below shows the results in the simple table in the database. You can see that the run data has been
successfully written to the data table。
Section 3 has a universal history of data processing
This example in the RSLogix 5000 prepared a simple traffic lights demonstration program. We want to achieve
the purpose of the traffic lights in the process of each lamp lights off the situation recorded, stored in MS SQL
Server, and through Excel to extract the data stored in MS SQL Server.
Prepare for work
Create a Topic in RSLinx with the name "TL" to point to the simulation PLC.
The label provided in this subordinate process and related description:

Form 3.1
Tag name (boolean type) description
GreenLight1Range North-south traffic light green light long range
GreenLight2Range East to west traffic light green light long range
GreenLight1FlashRange North-South traffic lights flashing green light range
GreenLight2FlashRange East to west traffic light green light flashing range
GreenLight North-south traffic light green light long state, associated with
the upper graphics
GreenLight2 East to west traffic light green light long state, associated with
the upper graphics
YellowLight North-south traffic lights yellow light long bright state,
associated with the upper graphics
YellowLight2 East to west traffic light yellow light long state, associated with
the upper graphics
RedLight North-south traffic lights red light long bright state, associated
with the upper graphics
RedLight2 East to west traffic light red light long state, associated with the
upper graphics
DataUpdate Data write trigger
Note: In order to reduce the network load pressure of the upper Ethernet, the program is designed to collect data
in real time, but every time a long period of time, to the database to write data rather than real-time write.
In the MS SQL Server test database in the new data table tutorial, where the column attributes are as follows:
table 3.2
Column name type of data description
ID SmallInt Self added
Time DateTime Timestamp
GreenLight1 Char
GreenLight2 Char
YellowLight1 Char
YellowLight2 Char
RedLight1 Char
RedLight2 Char
Create a new screen in the test application in the first section and name it TestDatabase. Draw the graphs
according to the following figure:

Referring to Table 1, the circle representing the traffic lights corresponds to the corresponding lower label.
In the Property Panel, change the Name of the Start Scan button to StartScBtn and ExposeToVBA to VBA
Control; change the Stop Scan button to StopScBtn and ExposeToVBA to VBA Control.
As the next time the next time the label changes every second, in order to make the upper screen display normal,
we need the upper screen refresh rate (default 1 second) to speed up. Right-click on the screen space, select
Display Settings on the pop-up drop-down menu, and change the Maximum Tag Update Rate to less than 1, for
example, 0.25。
2. Event-driven
We know that Visual Basic is an event-driven programming mechanism, where controls are run event tags by
event triggering. In SE VBA, event support for tag objects and tag group objects is provided. Let's start with a
simple experiment.
Create a new screen named VBA_Event. Draw two buttons and a text control (text) and set their ExposeToVBA
property to VBA Control. Figure:
Then open the VBA editor and add the following code

Private WithEvents OTagG As TagGroup 'Declares the label group object and enables the event of the object
Private OTag As Tag
Private Sub Button1_Released ()
Set OTagG = CreateTagGroup (Me.AreaName)
OTagG.Add ("system \ DateAndTimeString")
Set OTag = OTagG.Item ("system \ DateAndTimeString")
OTagG.Active = True 'Turns on event monitoring for tag group objects
End Sub

Private Sub OTagG_Change (ByVal TagNames As IGOMStringList)


Text1.Caption = OTag.Value 'The value of the label in the label group is changed when the process is called
End Sub
Private Sub Button2_Released ()
OTagG.Active = False
Set OTagG = Nothing
End Sub

Test run, you can see that when you click the On Scan button, the Text control will display the current date and
time, and it is dynamically changing. This is because the change in the time date triggers the change event of the
label group object and calls the corresponding procedure to update the displayed value of the Text control so
that we observe that the Text control displays the date and time in real time。
3. Write code and test
In the RSLogix 5000 in the preparation of the next bit of the program, then download the program to the
simulation PLC.
Open the VBA editor in SE, reference Microsoft ActiveX Data Objects, and then add the following code:
Private WithEvents TgG As TagGroup
Private WithEvents TgG2 As TagGroup
Private Conn As New ADODB.Connection
Private Rs As New ADODB.Recordset
Private TempStr(6) As String

Private Sub StartScBtn_Released()


Conn.ConnectionString = "provider=sqloledb;" & _
"Data Source=127.0.0.1;Initial Catalog=test;" & _
"User Id=sa;Password=0;"
Conn.Open
Rs.CursorLocation = adUseServer
Rs.CursorType = adOpenStatic
Rs.LockType = adLockBatchOptimistic
Rs.Open Source:="tutorial", ActiveConnection:=Conn, options:=adCmdTable
Set TgG = CreateTagGroup(Me.AreaName)
Set TgG2 = CreateTagGroup(Me.AreaName)
TgG.Add ("[TL]GreenLight1Range")
TgG.Add ("[TL]GreenLight2Range")
TgG.Add ("[TL]GreenLight1FlashRange")
TgG.Add ("[TL]GreenLight2FlashRange")
TgG.Add ("[TL]YellowLight")
TgG.Add ("[TL]YellowLight2")
TgG.Add ("[TL]RedLight")
TgG.Add ("[TL]RedLight2")
TgG2.Add ("[TL]DataUpdate")
TgG.Active = True
TgG2.Active = True
End Sub

Private Sub StopScBtn_Released()


Set TgG = Nothing
Set TgG2 = Nothing
Rs.Close
Conn.Close
End Sub

Private Sub TgG_Change(ByVal TagNames As IGOMStringList)


On Error Resume Next
TempStr(0) = Date$ & " " & Time$
If TgG.Item(1).Value = 1 Then
TempStr(1) = "On"
ElseIf TgG.Item(3).Value = 1 Then
TempStr(1) = "Flash"
ElseIf TgG.Item(1).Value = 0 And TgG.Item(3).Value = 0 Then
TempStr(1) = "Off"
End If
If TgG.Item(2).Value = 1 Then
TempStr(2) = "On"
ElseIf TgG.Item(4).Value = 1 Then
TempStr(2) = "Flash"
ElseIf TgG.Item(2).Value = 0 And TgG.Item(4).Value = 0 Then
TempStr(2) = "Off"
End If
Dim i As Integer
For i = 5 To TgG.Count
If TgG.Item(i).Value = 1 Then
TempStr(i - 2) = "On"
Else
TempStr(i - 2) = "Off"
End If
Next
Rs.AddNew
For i = 0 To 6
Rs.Fields(i + 1).Value = TempStr(i)
Next
End Sub
Private Sub TgG2_Change(ByVal TagNames As IGOMStringList)
Rs.UpdateBatch
End Sub

Note: Only one tag [TL] DataUpdate is referenced in the TgG2 collection. This tag group changes (that is, [TL]
DataUpdate changes) that causes the operation of the data to be written to the database. In the lower position the
label is designed to be flipped every 30 seconds. That is to say 30 seconds for the cycle, in this 30 seconds in the
light of the changes will be temporarily recorded in the local, when a cycle at the end of these temporary records
will be sent back to the database, update the data table, complete True write action.
Run the Start Scan button, the real-time data will be collected and written to the database. Stop the data
acquisition when you click the Stop Scan button.
The following figure shows the runtime screenshots:
4. Data extraction
The data stored in the database can be extracted in a number of ways. For the sake of data processing and ease
of use, we will introduce the method of extracting data through Excel.
Create a new Excel blank document and open, and then select the "new database query", as shown below

In the pop-up "Select Data Source" dialog box, select "New data source", click OK。
In the "Create a new database" dialog box, enter the appropriate information, click "Connect"

In the "SQL Server login" dialog box, enter the appropriate information click OK. Note: The following
parameters need to fill in the actual situation

Select the table tutorial in the Select Default Table for Data Source dialog box in the Create New Data Source
dialog box. Click OK。
And then click OK

In the pop-up "Query Wizard" dialog box, select tutorial, then click ">", click Next。

The next step


The next step

The next step

Select the start of the data table import and click OK. After a few minutes the data is imported。
The following figure shows the screenshot after the import is complete. Where the first row of the data table
column name, the rest for the table records. Where the symbol "On" represents light, "Off" means off, "Flash"
means flashing。

We through the table of data records can be noted that the first 10 lines of data is not accurate, which is
recorded in the data, the program data acquisition part of the code is being caused by the initialization. In
addition, we can clearly see the light work orderly, obvious rules, the state is completely normal.
Through the above steps, the data has been collected to the database, and was extracted to Excel, but when the
SE runtime, real-time data is constantly being collected into the database, if we want to see the latest data on the
need to update the results of Excel. In this case, do the following: Select "Data" and select "Refresh Data".
Figure
Each time you perform this operation, the data records in Excel are updated.
Data is extracted to Excel, it becomes very convenient to deal with. We can sort data in Excel, filter, subtotal,
generate a variety of statistical charts, etc., the specific method please refer to the Microsoft Office Excel related
manual, here is no longer detailed。

You might also like