我正在尝试在Excel VBA代码中插入一个暂停。以下代码生成编译错误:"无效限定符"。
Pause()函数试图将Application.Wait方法与DoEvents结合起来,以获得两全其美的效果; Excel将继续处理击键和鼠标点击,同时在等待时不占用CPU资源。
背景:
http://www.fmsinc.com/microsoftaccess/modules/examples/avoiddoevents.asp http://www.cpearson.com/excel/WaitFunctions.aspx
http://vbadud.blogspot.com/2008/03/sleep-function-in-excel-vba.html
Public Declare Function GetTickCount Lib "kernel32" () As Long
' A DoEvents loop uses CPU power.
' Application.Wait suspends all keyboard and mouse actions.
' This function is a hybrid to combine the best of both worlds.
Public Sub Pause(Optional Timeout As Single = 5)
Dim EndTime
EndTime = GetEndTick(Timeout)
Do While GetTickCount() <= EndTime
DoEvents
Application.Wait DateAdd("s", 0.1, Now)
Loop
End Sub
' Timeout is in seconds.
Function GetEndTick(Timeout)
GetEndTick = GetTickCount() + Timeout * 1000
End Function
答案 0 :(得分:0)
由于某种原因回答我的问题,无法识别Application对象。我成功地使用了以下解决方法:
Worksheets.Application.Wait DateAdd("s", 0.1, Now)
但是我发现Worksheets.Application.Wait占用了CPU资源,这违背了目的。相反,这是一个有效的暂停功能:
#If VBA7 Then
' Insert PtrSafe for Excel 64 as per http://stackoverflow.com/a/5507370/2529619
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
Private Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long
#Else
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare Function GetTickCount Lib "kernel32" () As Long
#End If
' "Pause" code execution for "Timeout" seconds.
'
' Excel will continue to process the keyboard and mouse clicks at least once a second.
' This Pause function will not take up lots of CPU resources.
' 2015.02.04 -- Chaim Gewirtz
Public Sub Pause(Optional Timeout As Single = 5)
Dim EndTick
' There are 1000 'ticks' in a second.
EndTick = GetTickCount() + Timeout * 1000
Do While GetTickCount() <= EndTick
' Process keyboard and mouse events while waiting.
DoEvents
' If there is at least one more second to pause then...
If EndTick - GetTickCount() > 1000 Then
' "Wait" for one second without using CPU resources.
Sleep 1000
End If
Loop
End Sub
答案 1 :(得分:-1)
Visual Basic - 所有变体 - 使用行尾作为语句标记的结尾。这与C#形成对比,其中分号用作语句终止符,而Delphi用分号作为语句分隔符。
所以,这一行:
Application.Wait DateAdd("s", 0.1, Now)
被视为单个语句,它没有意义。编译器可以做的最好的事情是认为你想要使用Application.Wait
作为限定符,但它不理解它。
将代码更改为:
Application.Wait
DateAdd("s", 0.1, Now)
它应该至少执行。但是,这是一个好的做法是另一个问题。