Option Explicit
Option Base 1
Const ServerName = “OPCServer.WinCC”
Dim WithEvents MyOPCServer As OpcServer
Dim WithEvents MyOPCGroup As OPCGroup
Dim MyOPCGroupColl As OPCGroups
Dim MyOPCItemColl As OPCItems
Dim MyOPCItems As OPCItems
Dim MyOPCItem As OPCItem
Dim ClientHandles(1) As Long
Dim ServerHandles() As Long
Dim Values(1) As Variant
Dim Errors() As Long
Dim ItemIDs(1) As String
Dim GroupName As String
Dim NodeName As String
‘———————————————————————
’ Sub StartClient()
’ 目的:连接至OPC_server,创建组并且添加条目
‘———————————————————————
Sub StartClient()
’ On Error GoTo ErrorHandler
‘———– 可以自由选择ClientHandle和GroupName
ClientHandles(1) = 1
GroupName = “MyGroup”
‘———– 从单元“A1”中得到ItemID
NodeName = Range(“A1”).Value
ItemIDs(1) = Range(“A2”).Value
‘———– 得到OPC服务器的实例
Set MyOPCServer = New OpcServer
MyOPCServer.Connect ServerName, NodeName
Set MyOPCGroupColl = MyOPCServer.OPCGroups
‘———– 为添加组设置缺省的激活状态
MyOPCGroupColl.DefaultGroupIsActive = True
‘———– 添加组至收集
Set MyOPCGroup = MyOPCGroupColl.Add(GroupName)
Set MyOPCItemColl = MyOPCGroup.OPCItems
‘———– 添加一个条目、返回ServerHandles
MyOPCItemColl.AddItems 1, ItemIDs, ClientHandles, ServerHandles, Errors
‘———– 用于接受不同的信息的组
MyOPCGroup.IsSubscribed = True
Exit Sub
ErrorHandler:
MsgBox “Error: ” & Err.Des cription, vbCritical, “ERROR”
End Sub
‘———————————————————————
’ Sub StopClient()
’ 目的:从服务器释放对象并且断开连接
‘———————————————————————
Sub StopClient()
‘———– 释放组和服务器对象
MyOPCGroupColl.RemoveAll
‘———– 从服务器断开连接并且清除
MyOPCServer.Disconnect
Set MyOPCItemColl = Nothing
Set MyOPCGroup = Nothing
Set MyOPCGroupColl = Nothing
Set MyOPCServer = Nothing
End Sub
‘———————————————————————
’ Sub MyOPCGroup_DataChange()
’ 目的:组中的数值、质量或时间标志改变时,该事件激活
‘———————————————————————
‘———– 如果OPC-DA Automation 2.0被安装,使用:
Private Sub MyOPCGroup_DataChange(ByVal NumItems As Long, ClientHandles() As Long, ItemValues() As Variant, Qualities() As Long, TimeStamps() As Date)
‘———– 设置数据表单元值为数值读
Range(“B2”).Value = CStr(ItemValues(1))
Range(“C2”).Value = Hex(Qualities(1))
Range(“D2”).Value = CStr(TimeStamps(1))
End Sub
‘———————————————————————
’ Sub worksheet_change()
’ 目的:工作表改变时,该事件激活,因此可以写一个新的数值
‘———————————————————————
Private Sub worksheet_change(ByVal Selection As Range)
‘———– 仅在单元“B3”改变时,写该值
If Selection <> Range(“B3”) Then Exit Sub
Values(1) = Selection.Cells.Value
‘———– 以不同的模式写新的数值
MyOPCGroup.SyncWrite 1, ServerHandles, Values, Errors
End Sub
OPC Automation 2.0