EndSub
'---------------------------------------------------------------------
'Sub StopClient()
'Purpose: Release the objects and disconnect from the server
'---------------------------------------------------------------------
SubStopClient()
'-----------Release the Group and Server objects
MyOPCGroupColl.RemoveAll
'-----------Disconnect from the server and clean up
MyOPCServer.Disconnect
SetMyOPCItemColl = Nothing
SetMyOPCGroup = Nothing
SetMyOPCGroupColl = Nothing
SetMyOPCServer = Nothing
EndSub
'---------------------------------------------------------------------
'Sub MyOPCGroup_DataChange()
'ouPru rGproosuep: hTahsi sc heavnegnetd is fired when a value, quality ortimestamp in
'---------------------------------------------------------------------
'-----------If OPC-DA Automation 2.1 is installed, use:
PrivateSub MyOPCGroup_DataChange(ByVal TransactionID As Long, ByVal NumItems As Long,ClientHandles() As Long, ItemValues() As Variant, Qualities() As Long,TimeStamps() As Date)
'-----------Set the spreadsheet cell values to the values read
Range("B2").Value= CStr(ItemValues(1))
Range("C2").Value= Hex(Qualities(1))
Range("D2").Value= CStr(TimeStamps(1))
EndSub
'-------------------------------------------------------------------
'Sub worksheet_change()
'wrPiutrep oas en:e wT hviasl ueev ent is fired when our worksheet changes, so wecan
'---------------------------------------------------------------------
PrivateSub worksheet_change(ByVal Selection As Range)
'-----------Only if cell "B3" changes, write this value
IfSelection <> Range("B3") Then Exit Sub
Values(1)= Selection.Cells.Value
'-----------Write the new value in synchronous mode
MyOPCGroup.SyncWrite1, ServerHandles, Values, Errors
EndSub
7.點擊“保存”,並且選擇“關閉並返回到Microsoft Excel”
2. 在WinCCOPC DA Server中添加用於傳送的變量
1.打開WinCC,創建新的項目,並在TagManagement 的Internaltags下創建一個類型為“Signed16-bit value”的變量“OPC_Excel”。
3. 實現WinCC與Excel的OPC通信,傳送變量
2.在Excel表的A1格中填入本機計算機名,在A2格中填入要連接傳送的變量名“OPC_Excel”。
3.在Excel中點擊“工具”,“宏”,選擇“宏”打開。
4.在出現的“宏”窗口中,選擇“Sheet1.StartClient”宏,點擊“執行”。
4. 實驗結果
1.運行“Sheet1.StartClient”宏後,可以看到,在Excel表的B2格中顯示了運行的WinCC中“I/O域”中變量的值。C2 格中顯示的是OPC“質量代碼”,D2格中顯示的是“時間戳”。
2.在Excel的B3格中輸入更改了的WinCC變量值,可以看到WinCC中的變量值發生了改變。
3.在退出程序時,需要釋放WinCC與Excel之間的OPC連接。具體方法是:在Excel中點擊“工具”,“宏”,選擇打開“宏”。在出現的“宏”窗口中,選擇“Sheet1.StopClient”宏,點擊“執行”。
總結:
本實驗是僅針對通過OPC實現WinCC與MS Excel之間的簡單通信。實驗中的VB代碼有相關的說明,讀者也可以參照此方法通過OPC接口來實現諸多功能,如數據採集與監控,數據存檔,通信等等。在今後的實驗或工作中,還將在其它應用中研究OPC。
閱讀更多 李春穎 的文章