Create Millisecond Loops in Excel VBA

时间:2017-07-17 15:31:18

标签: excel vba excel-vba loops infinite-loop

Since I just found out about Excel Macros, I want to try to simulate moving objects. I would like to run some looped code every 'frame' of my project. I can make an infinite loop in Excel VBA with this code:

Do While True:
    'code
Loop

However, this crashes Excel. Is there a way to make an infinite loop that runs every ten milliseconds or so, something like this:

Dim timer as Timer
If timer = 10 Then
    'code
    timer = 0
End If

EDIT: Your answers are very good, but not exactly what I'm looking for. I want to be able to run other code at the same time; a bit like Javascript's

setInterval(function(){}, 200);

which can run multiple functions simultaneously.

2 个答案:

答案 0 :(得分:1)

您可以使用API​​调用和睡眠。

将它放在模块的顶部:

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

然后你可以用这样的程序调用它:

Do While True:

Sleep 10    'wait 0.01 seconds

Loop

如果代码是64位操作系统,则需要使用PtrSafe。见https://support.microsoft.com/en-us/help/983043/compile-error-the-code-in-this-project-must-be-updated-for-use-on-64

答案 1 :(得分:0)

您的原始方法正在崩溃Excel,因为它正在创建一个没有退出条件的无限循环。

第二种方法不起作用,因为您的系统时钟时间(由Timer给出)永远不会是10,如果您在立即窗口中使用debug.Print(Timer),您将会看到它的价值。

以下是一些注释代码,用于根据计时器执行某些操作。请请确保你保留runtime条件退出while循环,无限循环是恶魔,你真的应该在这里有一些其他的退出代码!

Sub timeloop()
    Dim start As Double: start = Timer     ' Use Timer to get current time
    Dim t As Double: t = start             ' Set current time "t" equal to start
    Dim interval As Double: interval = 1   ' Interval for loop update (seconds)
    Dim nIntervals As Long: nIntervals = 0 ' Number of intervals passed

    ' Use this While loop to avoid an infinite duration! Only runs for "runtime" seconds
    Dim runtime As Double: runtime = 10
    Do While t < start + runtime
        ' Check if a full interval has passed
        If (t - start) / interval > nIntervals Then
            nIntervals = nIntervals + 1
            ' Do stuff here ---
            Debug.Print (t)
            ' -----------------
        End If
        t = Timer ' Update current time
    Loop
End Sub