Access and OPC PDF
Access and OPC PDF
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.
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.
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
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.
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
Figure 4
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.
' 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
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.
End Select
Next x
End Sub
Figure 6
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.
' Get the Servers handle for the desired item. The server handles
' were returned in add item subroutine.
SyncItemServerHandles(1) = ItemServerHandles(2)
' 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.
' 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
Figure 10
This code closes the form.
Add the code in Figure 11 to your Project Code window.
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.
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.
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
Figure 14
The final step is releasing the group, and group collection objects, by setting them to nothing.
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.
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
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 [email protected], 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