问题描述
下面是一个用 VBA 编写的 OPC 客户端。它使用 OPC Foundation DA 库。我能够获取项目的当前值(我可以在本地窗口中读取它),但它没有将值分配给 myValue = theItem.Value
在休息期间悬停在 theItem.Value
上也会显示该值。
有什么想法吗?
Public Sub ReadValue()
Dim serverNames As Variant
Dim listServers As Variant
Dim i As Integer
Dim theStates As Variant
Set theServer = New OPCServer
serverNames = theServer.GetoPCServers
theStates = Array("disconnected","Running","Failed","No Configuration","Suspended","In Test")
For i = LBound(serverNames) To UBound(serverNames)
Debug.Print (serverNames(i))
Next i
theServer.Connect ("MyOPCServer")
Debug.Print theServer.vendorInfo
Debug.Print theServer.MajorVersion & "." & theServer.MinorVersion
Debug.Print theStates(theServer.ServerState)
Debug.Print theServer.StartTime
Debug.Print theServer.CurrentTime
Debug.Print theServer.LastUpdateTime
'Groups
Dim theGroup As OPCGroup
Dim theGroups As OPCGroups
If theGroups Is nothing Then
Set theGroups = theServer.OPCGroups
End If
If theGroup Is nothing Then
Set theGroup = theGroups.Add("testing")
txtName = theGroup.name
End If
theGroup.Updaterate = CLng(1000)
theGroup.DeadBand = CLng(1)
theGroup.TimeBias = CLng(0)
theGroup.IsActive = CBool(1)
theGroup.IsSubscribed = CBool(1)
'
Dim theItem As OPCItem
Dim theItem1 As OPCItem
Dim myItems As Variant
Dim myValue As Variant
Dim myWriteValues As Variant
Dim handles(1) As Long
Dim Errors() As Long
Dim CancelID As Long
Dim TransID As Long
myItems = Array("MyPathBlahBlahBlah.CV")
myWriteValues = Array(8,1)
For i = LBound(myItems) To UBound(myItems)
Set theItem = theGroup.OPCItems.AddItem(myItems(i),currentHandle)
myValue = theItem.Value
handles(1) = theGroup.OPCItems.Item(1).ServerHandle
theGroup.OPCItems.Remove 1,handles,Errors
Next i
theServer.disconnect
End Sub
解决方法
审核/故障排除后。
OPCItem 对象提供了读取服务器中项目的当前值并将新值写入项目的方法。我已将这些设施包含在此对话框中。 OPCItem 对象上提供的 read 方法从服务器执行同步读取,并且可以配置为从缓存或设备读取。要从缓存中读取组和项目都应该处于活动状态,但直接从设备同步读取操作不依赖于组或项目的活动状态。
添加以下代码允许我分配给变量。
Dim source As OPCDataSource
Dim myValue As Variant
source = OPCDevice
theItem.Read source,myValue