注意:計算機-->屬性中的計算機名稱要與本計算機名稱一致
在VB中建立一頁面,用按鈕來改變text1,text2,text3的值,如果通訊成功,Vb與WINCC中值同步。
2 文件,打開文件,工具-->宏-->VB編輯器
3 在VB編輯器裏,工具-->引用,在彈出窗口中,找Siemens OPC DAAutomation 2.0,勾上
4 加入以下代碼
Option Explicit
Option Base 1
Const ServerName = "OPCServer.WinCC"
Const nodename = "computer"
Private objServer As OPCServer //定義OPC服務器
Private objGroup As OPCGroup //定義OPC 服務器中的組
Private objGroups As OPCGroups
Private objItems As OPCItems //定義OPC 服務器中的項目名
Dim StrItemIDs(10) As String
Dim ClientHandles(6) As Long
Dim Serverhandles() As Long
Dim i As Integer
Dim DataType(1000) As Integer
Dim errors() As Long
Dim accpath(1000) As String
Private Sub Form_Load() //VB初始頁面程序
Set objServer = New OPCServer
objServer.Connect ServerName, nodename //連接服務器,設定OPC 服務器的地址
Set objGroups = objServer.OPCGroups
Set objGroup = objGroups.Add("huangjie") //連接組
Dim i As Integer
For i = 1 To 3
StrItemIDs(i) = Text1(i).Text //連接變量
ClientHandles(i) = i
Next
DataType(1) = vbVString
DataType(2) = vbVString
DataType(3) = vbVString
accpath(1) = ""
accpath(2) = ""
accpath(3) = ""
Set objItems = objGroup.OPCItems
objItems.AddItems 3, StrItemIDs, ClientHandles, Serverhandles, errors, DataType, accpath
MsgBox "ok"
End Sub
Private Sub Command1_Click() //讀WinCC 中變量 讀按鈕
Dim plcVal() As Variant
Call objGroup.SyncRead(OPCCache, 3, Serverhandles, plcVal, errors)
Text1(0).Text = plcVal(1)
Text2.Text = plcVal(2)
Text3.Text = plcVal(3)
End Sub
Private Sub Command2_Click() // //寫WinCC 中變量 寫按鈕
Dim plcVal(3) As Variant
plcVal(1) = Text1(0).Text
plcVal(2) = Text2.Text
plcVal(3) = Text3.Text
objGroup.SyncWrite 3, Serverhandles, plcVal, errors
End Sub
如有交流,請致信QQ:1625785563