计算一段时间

时间:2017-04-06 04:25:35

标签: excel vba counter offset

我有一个VBA脚本,在y时间步长中从0到x计数,并将此值放在一个单元格中。通过使用偏移公式,我可以使用此计数从另一个工作表中读取数据,然后用于为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秒内生成。

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

1 个答案:

答案 0 :(得分:0)

在模块顶部:

#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

调整毫秒直到时机正确。