vba Excel VBA中的定时警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4876300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:37:15  来源:igfitidea点击:

Timed Alarm in Excel VBA

excelvbaexcel-vbatimerexcel-2003

提问by Diego Castro

I made a calendar to track tasks and similar items in Excel 2003. What I need to be able to do is to set a timer via VBA. Something like this:

我制作了一个日历来跟踪 Excel 2003 中的任务和类似项目。我需要做的是通过 VBA 设置一个计时器。像这样的东西:

run_in_x_secs ( timetowait, function to exec)

Is there a way to do that in excel vba, or should I try and find an alarm to run via the command line and run that from VBA.

有没有办法在excel vba中做到这一点,或者我应该尝试找到一个警报来通过命令行运行并从VBA运行它。

How would you do it?

你会怎么做?

采纳答案by Simon Cowen

This should do the trick:

这应该可以解决问题:

Public Sub RunSubInXSeconds(secondsToWait As Long, nameOfFunction As String)
    Application.OnTime Now + secondsToWait/(24# * 60# * 60#), nameOfFunction 
End Sub

Although you do have to be a little careful with OnTime, especially if you're going to be setting it to wait for a long period of time... E.g. if you close the workbook before the timer expires and the Sub executes, then you can end up with your workbook opening itself to run it. Confusing if you don't expect it!

尽管您必须对 OnTime 小心一点,特别是如果您要将其设置为等待很长时间...例如,如果您在计时器到期并且 Sub 执行之前关闭工作簿,那么您最终可能会打开您的工作簿以运行它。如果您不期望它会令人困惑!

回答by Dr. belisarius

Public Sub tt()

timerset = TimeValue("01:00:00") 'the time you want
Application.OnTime timerset, "myfun"

End Sub

Sub myfun()
 'do whatever you want
End Sub

回答by Tomamais

two more options:

还有两个选择:

'Option 1
Declare Sub Sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)

Sub Sleep()
 Sleep 1000   'whait 1 second
End Sub

'Option 2
Sub MyWaitMacro()
  newHour = Hour(Now())
  newMinute = Minute(Now())
  newSecond = Second(Now()) + 3
  waitTime = TimeSerial(newHour, newMinute, newSecond)
  Application.Wait waitTime
End Sub