在运行VBA运行时更新Excel图表

时间:2017-09-01 13:01:24

标签: excel vba charts series

这个问题已在不同主题中讨论过,但解决方案并没有帮助我。我正在尝试计算并显示图表的一系列数据。类似“计算y”的东西 - > “更新系列” - >等待100毫秒 - > “重新计算”。程序正在运行,但图表仅在Main-Sub完全完成时更新(而不是在每100毫秒后更新)。

该系列完全基于VBA中的数组,而不是指Cell。

当我在“睡眠”功能之后直接运行带有断点的程序时,图表会更新。

对我来说,DoEvents和chart.Refresh方法并没有给我我想要的结果。有人有想法吗?谢谢你的帮助。

Sub Main()
Dim ws As Worksheet
Dim mychart As Chart
Dim ser As Series
Dim x(1 To 10) As Double
Dim y(1 To 10) As Double
Dim i As Integer

Set ws = ThisWorkbook.Sheets("Sheet1")
Set mychart = ws.ChartObjects("Chart 1").Chart

Call DeletePlot(mychart)

For i = 1 To 10
    x(i) = i
    y(i) = i
Next i


' Plot first data
Set ser = mychart.SeriesCollection.NewSeries
With ser
        .Values = y
        .XValues = x
End With


Dim j As Integer
For j = 2 To 4
    For i = 1 To 10
        y(i) = i ^ j    ' update data
    Next i
    With ser
        .Values = y     ' update series
    End With
    mychart.Refresh     ' Does not work
    DoEvents            ' Does not work
    Sleep (100)
Next j
End Sub

睡眠功能:

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

PlotDelete功能:

  Sub DeletePlot(mychart As Chart)
    Dim ser As Series
    For Each ser In mychart.SeriesCollection
      ser.Delete
    Next ser
  End Sub

1 个答案:

答案 0 :(得分:0)

Application.OnTime或Windows API计时器等计时器,link给了我预期的行为。