一段时间内的计数器

Counter over time period

我有一个 VBA 脚本,它以 y 时间步长从 0 计数到 x,并将该值放在一个单元格中。通过使用偏移公式,我可以使用此计数从另一个 sheet 读取数据,然后将其用于动画 xy 散点图。

使用的代码是。

Sub Counter()                     'Name and start of script

For j = 0 To 200 Step 1           'Start of For loop setting j to equal a count from 0 to 2400
    Range("A1").Value = j         'Place the value of j into cell A1
    For c = 1 To 2500000          'Set a new variable called c and count from 0 to a value, this acts to slow down j's count else the animation would not be very long. Increasing this number will slow down the simulation and decreasing will speed it up
    Next                          'Move onto the next event
    DoEvents                      'Tells excel to do the For loop
Next                              'Move onto the next event

End Sub 

为了使动画图形不 运行 快,它会浪费时间。这在很大程度上取决于计算机的速度。 (较旧的计算机计数较少)

我想要实现的是能够在以秒为单位的时间段内进行从零到 x 的计数,因为我的数据通常以 0.1 时间间隔在 0 到 20 秒内生成。

因此动画将 运行 持续与计算数据相同的时间。

在模块顶部:

#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal milliseconds As LongPtr)
#Else  
    Public Declare Sub Sleep Lib "kernel32" (ByVal milliseconds as Long)
#End If

然后:

Sub Counter()
    For j = 0 To 200
        Range("A1").Value = j
        Sleep 100 ' or whatever - in milliseconds
        DoEvents
    Next
End Sub

调整毫秒直到时机正确。