【发布时间】:2010-04-29 13:32:30
【问题描述】:
我知道我在这里做错了什么。我正在尝试使用 sleep 功能来延迟我的代码,但我收到“未定义子或功能”错误。有什么建议吗?
【问题讨论】:
我知道我在这里做错了什么。我正在尝试使用 sleep 功能来延迟我的代码,但我收到“未定义子或功能”错误。有什么建议吗?
【问题讨论】:
VBA 没有Sleep 函数。
您可以像这样从 Kernel32.dll 导入它:
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
请注意,这将冻结应用程序。
您也可以在While 循环中调用DoEvents,这不会冻结应用程序。
【讨论】:
我尝试过的一切似乎都会挂起应用程序,包括 Application.Wait。不过这似乎可行:
waitTill = Now() + TimeValue("00:15:00")
While Now() < waitTill
DoEvents
Wend
【讨论】:
[Now()]
您也可以使用Application.Wait T 暂停当前宏上下文,这不会阻塞整个过程。
【讨论】:
Excel.Application。其他 Office 应用程序对象模型不存在 Wait 方法。
Application.Wait DateAdd("m", 10, Now) ' Wait for 10 Minutes
Application.Wait DateAdd("s", 10, Now) ' wait for 10 seconds
【讨论】:
暂停应用程序 10 秒。
Application.Wait (Now + TimeValue("0:00:10"))
【讨论】:
使用此代码 Excel 不会冻结且 CPU 使用率低:
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub Delay(s As Single)
Dim TimeOut As Single
TimeOut = Timer + s
Do While Timer < TimeOut
DoEvents
Sleep 1 'With this line the CPU usage is 00 instead of 50 with an absolute error of +1ms and the latency of 1ms.
Loop
End Sub
【讨论】:
以下是与 32 位和 64 位 Windows 计算机交叉兼容所需的条件。延迟以毫秒为单位,因此使用 1000 表示 1 秒延迟。
首先,将它放在模块中的其他子/函数之上。在 64 位计算机上,“#Else”之后的行将突出显示,就好像有错误一样,但这不是问题。代码将编译并运行。
#If VBA7 Then
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
现在你可以像这个例子一样创建一个延迟 1.5 秒的延迟:
Sub ExampleWithDelay()
Msgbox "This is a message before the delay."
Sleep 1500 ' delay of 1,000 milliseconds or 1.5 seconds
Msgbox "This is a message -AFTER- the delay."
End Sub
正如@SLaks 所述,这会冻结应用程序(阻止用户输入),但您也可以在While 循环中调用DoEvents。请参见下面的示例。它运行 10 秒并允许用户交互。
每隔 1/10 秒,它会更新 Excel 状态栏:
活动单元格的地址
倒计时
Sub ExampleWithDelayInLoop() ' for MS Excel
Dim thisMessage As String
Dim countdownText As String
Dim i As Long
Const TOTAL_SECONDS As Byte = 10
For i = 1 To TOTAL_SECONDS * 10
countdownText = Excel.WorksheetFunction.RoundUp(TOTAL_SECONDS - (i / 10), 0)
thisMessage = "You selected " & Excel.ActiveCell.Address & Space$(4) & countdownText & " seconds remaining"
' Show the address of the active cell and a countdown in the Excel status\
' bar.
If Not Excel.Application.StatusBar = thisMessage Then
Excel.Application.StatusBar = thisMessage
End If
' Delay 1/10th of a second.
' Input is allowed in 1/10th second intervals.
Sleep 100
DoEvents
Next i
' Reset the status bar.
Excel.Application.StatusBar = False
End Sub
【讨论】: