运行macros时更新dynamic图表 – Excel中的animationgraphics

我有一个dynamic图表根据单元格值更新每小时数据。 该单元格由滚动button控制或在另一个单元格中手动inputdate。 看看下面的gif的洞察力;

我想要做的就是使用VBA更新图表,使其像animation一样。 下面有这个(伪)代码;

Option Explicit #If VBA7 And Win64 Then '64 bit Excel Public Declare PtrSafe Sub Sleep Lib "kernel32" ( _ ByVal dwMilliseconds As Long) #Else '32 bit Excel Public Declare Sub Sleep Lib "kernel32" ( _ ByVal dwMilliseconds As Long) #End If Sub Animate() On Error GoTo Error ErrorHandler Dim wsh As Worksheet Dim i As Integer Set wsh = ThisWorkbook.Worksheets("AChart") Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic For i = 1 to 3000 Sleep 50 wsh.Range("K4").Value = i DoEvents Application.Wait Now() + TimeSerial(0, 0, 1) Next i Exit Sub ErrorHandler: MsgBox Err.Description & " Procedure Animated Graph" End Sub 

这(特别是DoEvents )不会在屏幕上更新图表。 我想知道是否有办法来实现这一点。

Application.OnTime可以用于这个目的。 其他的东西,如DoEventsSleep仍然有macros运行,并阻止图表更新(在屏幕上)。

如何制作dynamicgraphics?

首先,为了完成,这是如何制作dynamic图表的链接:

dynamicExcel图表

在这里,您将学习引用单元格并使用偏移量(或类似方法)来更改图表上显示的数据。

如何自动更改图表?

下面的代码是我自动更新图表数据(所谓的“animation”)的早期尝试之一。 StartFinish是表单中的两个Command Buttons ,用户可以通过它们控制“dynamic图”。 你可以随意玩, Pause ,等等,但是这会给你一个关于如何实现这个想法的想法:

 Public laststop As Boolean Public i As Integer Sub start() laststop = True 'This controls schedule in Application.Ontime i = 1 'Reset the date to the first entry each time you press start Call Animate 'calls the main sub End Sub Sub finish() laststop = False 'Set the schedule to false to stop the macro End Sub 'XXXXXXXXXXXXXXXXXXXX 'XXX MAIN PROGRAM XXX 'XXXXXXXXXXXXXXXXXXXX Sub Animate() On Error GoTo ErrorHandler Application.OnTime Now() + TimeSerial(0, 0, 2), "Animate", Schedule:=laststop If Not laststop Then GoTo nextline Dim wsh As Worksheet Set wsh = ThisWorkbook.Worksheets("Dynamic_Graph") Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic wsh.Range("I34").Value = i + 1 DoEvents i = i + 1 If i > 200 Then laststop = False 'last data entry Exit Sub ErrorHandler: 'Sometimes after running the finish macro these errors are happening that _ 'we don't want users to see them as they don't affect the process If Err.Description = "The specified dimension is not valid for the current chart type" _ Or Err.Description = "Method 'OnTime' of object '_Application' failed" _ Then GoTo nextline MsgBox Err.Description & " #Procedure: Animated Graph" nextline: laststop = False End Sub 

感谢@ASH提示OnTime