VB和WinCC的OPC变量交换 分别在VB和WinCC内部变量中定义了3个变量,16位Word型。
编程时,VB中的 Text1、2、3分别对应于wincc中的aa、bb、cc,
但是,当按下“写按钮”时,却是将 Text1正确写入了bb,其他没变化。 当按下“读按钮”时,却是Text2、3正确读入了aa、bb。Text1变成了空白,如附图所示。 是哪儿错了? Option Explicit
Dim OpcSvr As OPCServer Dim OpcGrps As OPCGroups Dim OpcGrp As OPCGroup Dim OpcItms As OPCItems Dim ItemSvrHdls() As Long
Dim NumItem As Long Dim Errors() As Long Dim ItemIDs(3) As String
Dim DataType(1000) As Integer Dim accPath(1000) As String Dim CltHdls(3) As Long
Private Sub Form_Load() Set OpcSvr = New OPCServer OpcSvr.Connect "OPCServer.WinCC", 20160623 - 2027 '连接服务器 MsgBox "CONNECT SUCCESSFUL" Set OpcGrps = OpcSvr.OPCGroups Set OpcGrp = OpcGrps.Add("VBOPC")
ItemIDs(1) = "aa" ItemIDs(2) = "bb" ItemIDs(3) = "cc" CltHdls(1) = 1 CltHdls(2) = 2 CltHdls(3) = 3 DataType(1) = vbVString
DataType(2) = vbVString DataType(3) = vbVString accPath(1) = ""
accPath(2) = "" accPath(3) = "" Set OpcItms = OpcGrp.OPCItems OpcItms.AddItems 3, ItemIDs, CltHdls, ItemSvrHdls, Errors, DataType, accPath End Sub
Private Sub Command3_Click() '读WinCC 中变量 Dim plcVal() As Variant OpcGrp.SyncRead OPCCache, 3, ItemSvrHdls, plcVal, Errors Text1.Text = plcVal(1) Text2.Text = plcVal(2) Text3.Text = plcVal(3) End Sub
Private Sub Command4_Click() '写入WinCC 中 Dim plcVal(3) As Variant
plcVal(1) = Text1.Text plcVal(2) = Text2.Text plcVal(3) = Text3.Text OpcGrp.SyncWrite 3, ItemSvrHdls, plcVal, Errors
------Option explicit option base 1'''''''少了这行 少了一行语句,估计定义变量读写顺序的吧?加上后正常了。
--------数组下标默认是从0开始,加了option base 1就从1开始。
-------Private Sub Command1_Click() Dim prtrun
Dim tag0
Dim WinCC As Object '定义wincc为对象
Set WinCC = CreateObject("WinCC-Runtime-Project")
prtrun = WinCC.SetValue("NewTag_1", Text1(0).Text)
prtrun = WinCC.SetValue("NewTag_2", Text1(1).Text)
prtrun = WinCC.SetValue("NewTag_3", Text1(2).Text)
prtrun = WinCC.SetValue("NewTag_4", Text1(3).Text)
prtrun = WinCC.SetValue("NewTag_5", Text1(4).Text)
prtrun = WinCC.SetValue("NewTag_6", Text1(5).Text)
prtrun = WinCC.SetValue("NewTag_7", Text1(6).Text)
prtrun = WinCC.SetValue("NewTag_8", Text1(7).Text)
'先写入一个值,再读回它,判断有没有写进去,由此来判断WINCC是不是在运行之中
prtrun = WinCC.GetValue("NewTag_1") If prtrun = 111 Then
MsgBox ("与WinCC通讯成功!")
Set WinCC = Nothing
Else
MsgBox ("与WinCC通讯失败!请将WinCC设置为运行状态!")
Set WinCC = Nothing
End If
End Sub 感觉VB这样读写WINCC变量比较简单 代码来自http://blog.sina.com.cn/s/blog_669692a60101a7n7.html
|