Excel 图表的动态更新有延迟

Dynamic Update of Excel Chart with Delays

我使用 Excel VBA 从仪器读取数据线。 我想在读取数据后立即在 Excel 活动图表上动态绘制数据。 我需要等待并每 5 秒读取一次数据,与此同时,我 "sleep",或者通过 VBA Application.Wait 命令,或者通过 Kernel32 Sleep 命令。 在任何一种情况下,活动图表都不会更新。完整的情节仅在 LAST "sleep" 之后显示。 任何建议将不胜感激。

这里是简化代码

Sub New_Data(indx)
Dim x As Integer

While True

    x = Read_Instrument(1)
    y = Read_Instrument(2)
    Cells(indx, 1) = x
    Cells(indx, 2) = y

    ActiveSheet.ChartObjects.Item(1).Activate
    ActiveChart.FullSeriesCollection(1).XValues = "=Sheet1!$A:$A$" & indx
    ActiveChart.FullSeriesCollection(1).Values = "=Sheet1!$B:$B$" & indx

    indx = indx + 1
    Sleep 5000  'Use the KERNEL32 Sleep function for 5000 milliseconds
Wend
End Sub

WaitSleep将保持VBA运行,所以屏幕不会更新。 尝试使用 Application.OnTime,按照这些行(在标准代码模块中,即 Module1)。

Sub refreshMyChart()
   Dim indx as long: indx = sheet1.Cells(Rows.Count, 1).End(xlUp).offset(1)

   Cells(indx, 1) = Read_Instrument(1)
   Cells(indx, 2) = Read_Instrument(2)

   With Sheet1.ChartObjects(1).FullSeriesCollection(1)
     .XValues = "=Sheet1!$A:$A$" & indx
     .Values = "=Sheet1!$B:$B$" & indx
  End With

  ''''' Now Schedule the same routine for 5 seconds later''''''''''
  Application.OnTime Now + TimeSerial(0,0,5), "refreshMyChart"
  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End Sub

p.s.: 请注意,此数据不能无限增长。您应该定义一些方法来停止或删除旧行,以保持显示的数据行数合理。

太棒了!非常感谢你。 我不知道 .OnTime 结构 Application.OnTime 现在 + TimeSerial(0, 0, 5), "refreshMyChart" 以及 VBA 允许递归例程的事实。 至于结束循环,里面有代码,我没有post因为和问题无关。这里是 如果 Int(current_index / nmeasure) * nmeasure > finalval 那么 消息框 ("End of Measurement") 退出子 结束如果

再次感谢。