首先申明OPC对象:
Option Base 1
Dim WithEvents ServerObj As OPCServer 'OPC Server对象,连接OPC服务器
Dim GroupsObj As OPCGroups 'OPC Groups对象,添加OPC组
Dim WithEvents GroupObj As OPCGroup 'OPC Group对象
Dim ItemsObj As OPCItems 'OPC Item集合
Dim ServerHandles() As Long '服务器端OPC Item的句柄
Dim ClientHandles() as Long '客户端OPC Item的句柄
Dim ItemId(2) As String
Dim Errors() As Long
接下来,生成各个对象:
If ServerObj Is Nothing Then Set ServerObj = New OPCServer
'连接OPC服务器
If ServerObj.ServerState = OPCDisconnected Then
ServerObj.Connect ("OPC.SimaticNET") '假设OPC服务器运行在本机
End If
If GroupsObj Is Nothing Then Set GroupsObj = ServerObj.OPCGroups
If GroupObj Is Nothing Then Set GroupObj = GroupsObj.Add
If ItemsObj Is Nothing Then Set ItemsObj = GroupObj.OPCItems
GroupObj.IsActive = True '设置组为活动状态
'假设有两个数据源,一个是8位开关量输入,一个是8位开关量输出
ItemId(1) = "S7:[S7 connection_1]IB0"
ItemId(2) = "S7:[S7 connection_1]QB0"
ClientHandles(1) = 1
ClientHandles(2) = 2
'添加组项目,ServerHandles数组的值为各个OPC Item的服务器句柄,
' ClientHandles数组的值为各个OPC Item的客户端句柄,由应用程序设定
Call ItemsObj.AddItems(2, ItemId, ClientHandles, ServerHandles, Errors)
你参考一下,我这边写的一个VB的例子程序,希望对你有帮助,