在Excel VBA中创build毫秒循环

由于我刚刚发现Excelmacros,我想尝试模拟移动的对象。 我想在我的项目的每个“框架”上运行一些循环代码。 我可以用Excel代码在Excel VBA中进行无限循环:

Do While True: 'code Loop 

但是,这使Excel崩溃。 有没有办法做一个无限循环运行每十毫秒左右,如下所示:

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

编辑:你的答案是非常好的,但不完全是我在找什么。 我希望能够同时运行其他代码; 有点像Javascript的

 setInterval(function(){}, 200); 

可以同时运行多个function。

您可以使用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/zh-cn/help/983043/compile-error-the-code-in-this-project-must-be-updated-for-use-on-64

您的原始方法是崩溃的Excel,因为它创build一个无退出条件的无限循环。

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

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

 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