当外部 DDE/OPC 链接更改单元格值时,我需要执行宏。我已经尝试了几个使用 Worksheet_Change 函数的示例,但这似乎只在用户输入值时才有效(即使那样,也只能工作一次)。
这是整个代码(更改为“计算”方法后):
Private Sub Worksheet_Calculate() 'Calculate command will execute the macro when any value change the spreadsheet to recalculate
Dim ctr As Integer, n1 As String, v1 As Single, trigger As Long
'Application.EnableEvents = False
'Workbooks("Data Save.xls").Select
Sheets("Sheet1").Select
trigger = Range("b5").Value 'data save trigger cell linked to PLC
If trigger = 1 Then
Dim fn1 As String
fn1 = "C:\11047 RR\" & Range("B4") & ".csv" 'build a filename
Open fn1 For Output As 1
Print #1, Range("a1"); ","; Range("B1") 'batch number
Print #1, Range("a2"); ","; Range("B2") 'part number
Print #1, Range("a3"); ","; Range("B3") 'pass number
Print #1, Range("a4"); ","; Range("B4") 'filename
Print #1, "Date & Time:,"; Date$; ","; Time$
For ctr = 7 To 69
n1 = Sheets("Sheet1").Cells(ctr, 2).Value
v1 = Sheets("Sheet1").Cells(ctr, 3).Value
Print #1, ctr; ","; n1; ","; v1
Next ctr
Close 1
Sheets("Sheet1").Cells(5, 4) = 0 'put a zero into cell D5 in the spreadsheet
RSIchan = DDEInitiate("RSLinx", "Upsetter_11047")
DDEPoke RSIchan, "DataSaveFlag", Range("D5") 'write cell D5 out to the trigger word
DDETerminate (RSIchan)
MsgBox "Data saved"
Application.EnableEvents = True
End If
End Sub