使用vba/vb做client可以使opc的访问变得简单,以下是基于excel的简单opc client代码:
Option Explicit Public WithEvents MyOPCSvr As OPCAutomation.OPCServer Public WithEvents MyOPCGroup As OPCAutomation.OPCGroup Private Sub CommandButton1_Click() On Error GoTo error ' 利用OPC自动化接口连接;建立组;加入/读写项 Set MyOPCSvr = New OPCServer MyOPCSvr.Connect Me.TextBox1.Text Set MyOPCGroup = MyOPCSvr.OPCGroups.Add("testMyOPCGroup") Dim item As OPCItem Set item = MyOPCGroup.OPCItems.AddItem("_system" + Chr(26) + "Now", 1000) MyOPCGroup.IsSubscribed = True 'item.Read (OPCCache) 'item.Write (12345) 'MsgBox item.Value Exit Sub error: MsgBox Err.Description CommandButton2_Click End Sub Private Sub CommandButton2_Click() ' 断开连接 If Not MyOPCSvr Is Nothing Then MyOPCSvr.Disconnect Set MyOPCSvr = Nothing End If End Sub Private Sub MyOPCGroup_DataChange(ByVal TransactionID As Long, ByVal NumItems As Long, ClientHandles() As Long, ItemValues() As Variant, Qualities() As Long, TimeStamps() As Date) ' 数值改变时。。。 Worksheets("Sheet1").Range("A1").Value = ItemValues(1) End Sub Private Sub MyOPCSvr_ServerShutDown(ByVal Reason As String) ' 服务器断开 MsgBox Reason End Sub
图: