繁体   English   中英

通过DDE / OPC链接更改单元格值时自动执行宏

[英]Automatically execute a macro when a cell value is changed by a DDE/OPC link

当单元值由外部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

您可以使用Calculate事件。 说单元格A1通过DDE刷新。 在另一个单元格中(例如B1),输入:

= A1

当刷新A1时,B1将重新计算,并且Calculate事件将被触发。

编辑#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM