0

当外部 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
4

1 回答 1

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
于 2013-11-06T14:49:47.170 回答