当外部DDE / OPC链接更改单元格值时,我需要执行宏。我已经使用Worksheet_Change函数尝试了几个示例,但这只在用户输入值时才会起作用(即便如此,只能使用一次)。
这是整个代码(在更改为“Calculate”方法之后):
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
答案 0 :(得分:1)
您可以使用计算事件。假设单元格A1通过DDE刷新。在另一个单元格(例如B1)中,输入:
= A1
当A1被刷新时,B1将被重新计算,计算事件将被触发。
编辑#1 :
工作簿打开后立即计算工作簿。这意味着事件宏也会在工作簿打开时被触发。现在,如果B5最初包含文本而不是数字或为空,那么您将收到您看到的错误消息。
例如,从空白工作表开始,在B5中放置一个空格并运行:
Sub dural()
Dim t As Long
t = Range("B5").Value
End Sub
您应该会看到错误13。
编辑#2 :
在您发布的代码中,替换:
trigger = Range("b5").Value
使用:
Dim V As Variant
V = Range("B5").Value
If IsNumeric(V) Then
trigger = CLng(V)
Else
Application.EnableEvents = True
Exit Sub
End If