You are on page 1of 12

Access and OPC

All versions of Kepware OPC Servers and Access 2003


04/05/05 v. 1.02

Introduction
This document is intended to show the basic steps required to connect Access forms to an OPC server using
VBA. It is not a resource for teaching novice programmers how to create OPC based applications, or how to
program in VB or VBA. The programming styles used in the following examples are the preferred styles of the
document writer, and may not follow standard programming practices.

Recommendations
It is recommended that you possess intermediate VB Programming skills, and an understanding of Object
Oriented processing when doing this type of VB or VBA programming. We recommend reading the OPC
Automation Interface Specification manual that is provided in the KEPServerEX installation before proceeding.

About OPC
Unlike DDE, which requires a connection to the server for each control in your project, OPC is a group of
related interfaces that all the client application broader interface capacity then DDE does. The interface from
VB is comprised of 4 objects, and 2 object collections.

Figure 1
You can learn more about the structure of OPC and how it works from the KEPServerEX help file, or the OPC
Foundation web page at www.opcfoundation.org.

KTAN-90034 Page 1 of 12
Using the least number of code calls necessary, we will demonstrate how to connect and recieve data from an
OPC server.

Creating the Access VBA Application


Install KEPServerEX
The first step is install KEPServerEX on your PC. We recommend that you install it on the same PC that you
intend to create the application on. A KEPServerEX license is not required. Demo mode may be used for this
procedure, however it requires a restart every 2 hours. In this example we use the Simulator driver and the
default server project, (SimDemo.opf), which is installed by default with the server.

Start Microsoft Access.


Next start Microsoft Access. Our examples were created using Access 2002/2003. Create a new Access project,
and name it.

Create a Form
In this example no tables are defined, so we are creating an unbound form. This example will work with any
Access form.

Adding Objects to the Form


We will add four objects to the form in this example.

The first object is a text box. We named the text box txtData1. The text box will display the value of the item
we are reading form the server.

The second object is a label. We named the label lblCommError. This label is used to display the device
communication status.

The third object we are adding is a command button. We named the button btnToggle. This button will be used
to graphically display the value of a bit, and toggle that bit on and off.

The fourth object is a command button. We named the button ExitExample. Use Exit as the caption on the
button by typing E&xit in the Captions property. This button is used to properly close a server connection.

Figure 2

Referencing the OPC Automation Wrapper


It is not possible for Access to directly access the server via OPC, so a DLL must be included in your projects
VBA code that will provide the software hooks you need. This file is installed by default with the server, and is

Page 2 of 12 KTAN-90034
located in the system32 folder of the Operating Systems root directory. The file is named OPCDAAUTO.dll.
As part of the foundation, we provide the OPC Automation Wrapper. The interface is a standard set by the OPC
foundation, so it should be capable of connecting to any manufacturers OPC Server.

Next, select the form and click on the Properties button in the Access main menu. This opens the properties
window for the form.

Figure 3
In the properties window for the form select the Event tab. Go to the On Load event and select [Event
Procedure] from the menu, and then click the button. This will open the VB editor and create a blank form
named Load Subroutine.

Next, create a reference to the OPC DA Automation Wrapper. In the VB Editor click Tools|References. Scroll
down through the available libraries until you find OPC DA Automation 2.0. Click the check box and then OK.

Adding the Code


Begin adding code to the project to allow data access from the server. In this example you will use a Server
Object, a Group Collection Object, a Group Object, an Item Collection Object and several Item Objects. The
code used here is similar to the code used in the Very Simple, or Gorilla OPC, example that is found in the
support center.

Project Declarations Code


The next step is to declare the global objects and variables that will be used in the project. First, force the
declaration of all variables by using the Option Explicit statement. Next, set the lower bounds for all form
arrays to 1 with the Option Base statement.

The remaining declarations are related to the OPC connection. Next you will create a Server Object, a Group
Collection Object, a Group Object, and an Item Object Collection. Notice that two are created using the With
Events option. This allows the server to call back the client project and inform it of data changes. This is often
referred to as a callback event, or exception event. This option prevents the server from sending unchanged data
to the client application, which allows more clients to connect to the server application and minimizing the
impact on system and network resources.

Lastly, we have created several variables, which are used as parameters by various objects.

In your project, assuming you still have the VB Editor Open, go to the top of the code window and add the code
in Figure 4 to the General Declarations portion of the code window.

KTAN-90034 Page 3 of 12
Option Compare Database
Option Explicit
Option Base 1

'Define the Server and Group Objects


Dim WithEvents ConnectedOPCServer As OPCServer
Dim ConnectedServerGroups As OPCGroups
Dim WithEvents ConnectedGroup As OPCGroup

' OPC Item related data


' These arrays are dimensioned for one item.
' If you are doing more then one you would a increase the size.
Dim OPCItemCollection As OPCItems
Dim ItemCount As Long Number of items that will be added to the project.
Dim OPCItemIDs(3) As String
Dim ItemServerHandles() As Long
Dim ItemServerErrors() As Long
Dim ClientHandles(3) As Long
Dim ToggleValue As Boolean current value of the register that is used for the toggle button.

Figure 4

Form Load Code


Now that we have defined the Objects it is time to start building the project. We are attempting to keep the
example of connecting an OPC Server and displaying data on the screen as simple as possible. To do that, we
will execute all the code needed to connect the OPC Server and establish the data polling in the Form Load Sub
Routine of the form.

Go to the blank form, Load Sub, which was created earlier.


Note: A quick note about the naming conventions that we are using for the Objects and
variables. These are standards, however you can use any names you wish. The names
selected for this document were intended to provide a description of what they are used for.

In this section we create the server, by using the Set command. Notice we named the server
ConnectedOPCServer. Now, use the server objects Connect method to connect to the server. Notice that we
pass the ProgramID for KEPServerEX, which is Kepware.KEPServerEX.V4.
Note: If you read the OPC Automation Interface Manual you will notice that we are only using
one connection parameter. The NodeName parameter is optional and is not needed when
connecting to a Server running on the same PC as the project.

Next create a group collection under the Server object, and add a named Group to the group collection. We
named our Group Test1. Now set the Group update and subscription properties. We chose a fairly slow
update rate of 1000 milliseconds, and set the subscription property to True.
Note: The group is the key to getting data. In OPC the client dictates the rate at which the
server will poll a device. When using Ethernet communications a lot of data can be
transferred very quickly. To optimize this performance, OPC specifies data reporting by
exception; the exception being a data change. This is beneficial, because a large portion of
data contained in PLCs I/O and memory is Configuration and Set Point information, which
changes very rarely. This helps prevent wasted resources caused by updating the client
application with the same data on every poll cycle. By subscribing a group, the client is
asking the server to send updates only when data changes.

Next, set the parameters needed to add an item to the group, so we can recieve data updates. Set the ItemCount
parameter to 3. We will only be adding 3 items in this example. You can add several items to the group now, or
add them later as needed. We recommend adding them in the beginning of the process, because adding items
later may cause the server to pause its polling. Next, define the items being added. KEPServerEX requires
using the complete identifier when defining items. The identifier consists of the Channel Name, Device Name,
and Item Name, or Address, separated by periods. Our example item "Channel_1.Device_1.Tag_1", is pointing to a

Page 4 of 12 KTAN-90034
tag located in the Simdemo project mentioned earlier. Also we used, "Channel_1.Device_1.k0.1", which is a bit in
a constant register, and "Channel_1.Device_1._system._Error", which is the communication error flag for the deivce. Notice
the item naming convention lets the server know exactly where to request the data from.

Next we are going to create an Item collection for our group, and set its IsActive property to True, so the
items added will be actively polled. The only step remaining is adding the item to the Item collection.

Note: In our example we do not have an error handling section, however for live projects we
recommend adding error handling. Error messages are generated for successful, and failed
attempts to add items to the server. The error codes in these messages may indicate why the
Add Item function failed. Reference the Simple VB Example code that ships with the server
for more information.

Add the code in Figure 5 to your Project Code window.

' General startup initialization


Private Sub Form_Load()
'Create a new OPC Server object
Set ConnectedOPCServer = New OPCServer
ConnectedOPCServer.Connect "Kepware.KEPServerEX.V4"

' Add the group and set its update rate


Set ConnectedServerGroups = ConnectedOPCServer.OPCGroups
Set ConnectedGroup = ConnectedServerGroups.Add("Test1")

' Set the update rate for the group


ConnectedGroup.UpdateRate = 1000
' Subscribe the group so that you will be able to get the data change
' callbacks from the server
ConnectedGroup.IsSubscribed = True
'Next we will add 3 items. When adding more then 1 item, make sure that you increase
'the OPCItemIDs and Client Handles Arrays to the number of items you will be adding.
'You will also need to increase the item count to correspond to the number of items'
'that you are adding.
'
ItemCount = 3
' Add simulator project Tag_1. This is a static tag.
OPCItemIDs(1) = "Channel_1.Device_1.Tag_1"
ClientHandles(1) = 1
' Add dynamic Boolean tag. This is a dynmaic tag.
OPCItemIDs(2) = "Channel_1.Device_1.k0.1"
ClientHandles(2) = 2
' Add Comm Error monitoring tag. This is a device System Tag.
OPCItemIDs(3) = "Channel_1.Device_1._system._Error"
ClientHandles(3) = 3

' Establish a connection to the OPC item interface of the connected group
Set OPCItemCollection = ConnectedGroup.OPCItems
OPCItemCollection.DefaultIsActive = True
OPCItemCollection.AddItems ItemCount, OPCItemIDs, ClientHandles, ItemServerHandles, ItemServerErrors

End Sub

Figure 5

Group Data Change Event Code


When we defined the group object, we did so with Events. One event is the Group Data Change event. This
event occurs when the OPC Server detects data changes for items in the group asked for in the Item Collection.
Three important events must occur when the client application connects to the server in order for this to happen.

KTAN-90034 Page 5 of 12
First, the Group had to be made active. The default state is active. Second, the group had to be subscribed.
Third, the item, or item collection, has to be made active. If these three events are satisfied you should recieve
data change events when they occur.
Note: The first item in the Simdemo project is designed to increment every time it is polled.
Once you complete the following code, you should see this happen about every second.

You must manually add the Sub from Figure 6 to your Project Code window. We were reading multiple items
so we have to step through the ClientHandle array that is sent by the server so that you could update the proper
item object properties.
Add the code in Figure 6 to the Project Code window.

Sub ConnectedGroup_DataChange(ByVal TransactionID As Long, ByVal NumItems As Long, ClientHandles() As Long,


ItemValues() As Variant, Qualities() As Long, TimeStamps() As Date)
' We don't have error handling here since this is an event called from the OPC interface You can use the 'Clienthandles'
' array returned by the server to pull out the index number of the control to update and load the value. Since we
' only have one we do not worry about that. If you were doing more then one item you might use the following code:
Dim x As Integer
For x = 1 To NumItems
' Check the Qualties for each item retured here. The actual contents of the quality field can contain bit field data
' which can provide specific error conditions. Normally if everything is OK then the quality will contain the 0xC0.

Select Case ClientHandles(x)


Case 1 'Datachange for the Item "Channel_1.Device_1.Tag_1"
Me!txtData1.Value = ItemValues(x)
If Not Qualities(x) And &HC0 Then
MsgBox "Bad Data Quality on Tag_1"
End If

Case 2 'Datachange for the Item "Channel_1.Device_1.K0.1"


If ItemValues(x) = True Then
btnToggle.ForeColor = vbGreen
ToggleValue = True
Else
btnToggle.ForeColor = vbRed
ToggleValue = False
End If

If Not Qualities(x) And &HC0 Then


MsgBox "Bad Data Quality on Toggle Bit"
End If

Case 3 'Datachange for the Item "Channel_1.Device_1._System._Error"


If ItemValues(x) = True Then
lblCommError.Caption = "Device Not Talking"
lblCommError.ForeColor = vbRed
Else
lblCommError.Caption = "Device Talking"
lblCommError.ForeColor = vbGreen
End If

End Select

Next x
End Sub

Figure 6

Toggle the Bit with a Write


We added a button to the form which will allow us to toggle a bit on and off. We need to open the buttons
properties window and create an event procedure for the On Click event, as we did for the form load.

Page 6 of 12 KTAN-90034
Figure 7
We will perform a Synchronous write to the device using the global ToggleValue variable from an IfThen
Else statement. If the current value is True(1), then we write False(0), and vice versa. The color of the button
will change with the value when we read the new value in the DataChange event.

Add the code from Figure 8 to your Project Code window.

Private Sub btnToggle_Click()


'Set error handling for OPC Function
On Error GoTo ShowOPCSyncWriteError

' Write only 1 item


ItemCount = 1
' Create some local scope variables to hold the value to be sent.
' These arrays could just as easily contain all of the item we have added.
Dim SyncItemValues(1) As Variant
Dim SyncItemServerHandles(1) As Long
Dim SyncItemServerErrors() As Long

' Get the Servers handle for the desired item. The server handles
' were returned in add item subroutine.
SyncItemServerHandles(1) = ItemServerHandles(2)

' Load the value to be written


'SyncItemValues(1) = Val(OPCItemValueToWrite(Index).Text)
If ToggleValue = True Then
SyncItemValues(1) = 0
Else
SyncItemValues(1) = 1
End If

' Invoke the SyncWrite operation. Remember this call will wait until completion
ConnectedGroup.SyncWrite ItemCount, SyncItemServerHandles, SyncItemValues, SyncItemServerErrors

GoTo SkipOPCSyncWriteError

ShowOPCSyncWriteError:
Call DisplayOPC_COM_ErrorValue("OPC Sync Write", Err.Number)
SkipOPCSyncWriteError:

End Sub

Figure 8

KTAN-90034 Page 7 of 12
Handle OPC Errors
Next, set up a subroutine to handle errors that are recieved. Notice we made calls to this routine in some of the
previous code. You will need to manually add the entire routine.

Add the code from Figure 9 to your Project Code window.

' Handles displaying any OPC/COM/VB errors that are caught by the exception handler
Sub DisplayOPC_COM_ErrorValue(OPC_Function As String, ErrorCode As Long)
Dim Response
Dim ErrorDisplay As String
ErrorDisplay = "The OPC function '" + OPC_Function + "' has returned an error of " + Str(ErrorCode) + " or
Hex 0x" + Hex(ErrorCode)
Response = MsgBox(ErrorDisplay, vbOKOnly, "OPC Function Error")
End Sub

Figure 9

Form Unload or Exit Code


When finished processing it is important to remove all items, and disconnect from the server. This allows the
server to properly allocate system resources. Access projects require you to unload the form. This is done by
clicking the Form Close button, if it is available, or it can be performed using a command button. We will do
both. First create the code for the exit button that was added to the form earlier. Select the button, then open the
properties, and create a click event.

Figure 10
This code closes the form.
Add the code in Figure 11 to your Project Code window.

Private Sub ExitExample_Click()


'Closes the form and triggers the form unload event. The unload event removes the tags and disconnects from the server.
On Error GoTo Err_ExitExample_Click
DoCmd.Close acDefault, "OPC_DATA", acSaveNo
Exit_ExitExample_Click:
Exit Sub
Err_ExitExample_Click:
MsgBox Err.Description
Resume Exit_ExitExample_Click

End Sub

Figure 11
Next we need to handle the form unload. Select the form and create an Unload event.

Page 8 of 12 KTAN-90034
Figure 12
This code will call 3 subroutines. They are: Remove_Items, Remove_Group, and Disconnect_Server. After
these Subs complete, we will end the process and the form will close.

Add the code from Figure 13 to your Project Code window.

Private Sub Form_Unload(Cancel As Integer)


'When you unlodad or close the form it is time to remove the Items, Group, and Server Connection
Call Remove_Items
Call Remove_Group
Call Disconnect_Server
End
End Sub

Figure 13

KTAN-90034 Page 9 of 12
Remove Items Code
When closing a server project the first step is to remove the items from the project. This is accomplished using
the remove method of the Item collection object. It is essentially the reverse of the add item function. Start by
defining variables and set their values as needed. Execute the remove method.
Note: There are two methods for removing items; one is Remove, and the other is RemoveAll.
The Remove method is cleaner to use even though it may require more code.

The last thing we do is release the item by setting it to nothing.

Add the code from Figure 14 to your Project Code window.

Sub Remove_Items()
Dim RemoveItemServerHandles(100) As Long
Dim RemoveItemServerErrors() As Long
Dim RemoveCount As Integer
Dim r As Integer

'When you unlodad or close the form it is time to remove the Items, Group, and Server Connection
RemoveCount = OPCItemCollection.Count

'Build the Item Array for items to be removed.


For r = 1 To RemoveCount
RemoveItemServerHandles(r) = ItemServerHandles(r)
Next r
'Remove the items
OPCItemCollection.Remove RemoveCount, RemoveItemServerHandles, RemoveItemServerErrors
'Release the item interface and all the resources to be freed
Set OPCItemCollection = Nothing
End Sub

Figure 14

Remove Groups Code


Once the items have been removed, remove the group using the Group collections Remove method.

The final step is releasing the group, and group collection objects, by setting them to nothing.

Add the code from Figure 15 to your Project Code window.

Sub Remove_Group()
'Remove the group
ConnectedServerGroups.Remove ("Test1")
' Release the group interface and allow the server to cleanup the resources used
Set ConnectedGroup = Nothing
Set ConnectedServerGroups = Nothing

End Sub

Figure 15

Page 10 of 12 KTAN-90034
Disconnect Server Code
Use the Server Objects Disconnect method to disconnect from the server. Next, release the object by setting it to
nothing.

Add the code from Figure 16 to your Project Code window.

Sub Disconnect_Server()
'Remove/Disconnect the server connecton
ConnectedOPCServer.Disconnect
' Release the old instance of the OPC Server object and allow the resources to be freed
Set ConnectedOPCServer = Nothing
End Sub

Figure 16

Run the Project


If you entered the code properly you should be able to run the VB project, and see the data change in your text
box. If you receive errors you will need to debug them and try again. Figure 17 shows our project running with
live data, and the bit is turned off. If you click the button you will see the text color change to green, indicating
the bit is turned on, as in Figure 18.

Figure 17

Figure 18

KTAN-90034 Page 11 of 12
Summary
You should now have a basic understanding of how to create a VB Project that communicates with an OPC
server. A copy of the code for this project is included with the download, so you can compare it to your code.
For more examples look at the Simple and Complex VB projects that we install with our server.

If you have questions about the OPC portion of this VB project then please contact Kepware Technical support
via e-mail at Technical.Support@kepware.com, via our Technical Support Feedback form on our website at
www.kepware.com, or via phone at 1-207-775-1660 x211.

Page 12 of 12 KTAN-90034

You might also like