在Excel 2010中使用VBA(excel)创build一个倒数计时器

我正在使用Excel 2010,并希望在Excel中创build一个倒数计时器。 代码将通过使用附加macros的button来启动和停止。 按下“开始”button时会出现问题。 上面的代码是利用单元格“B1”作为input点,因为我只是试图让它工作,但每次我尝试,总是会说:“不能运行macros。macros可能不可用在这个工作簿或所有macros可能被禁用“。

是的,我把这个放在这里之前启用了所有的macros。 我希望能够进行用户input,并使定时器开始的时间,而不是只使用单元格“B1”。

'Macro for Starting the timer (attached to the start button) Sub startTimer() Application.OnTime Now + TimeValue("00:00:01"), "nextTick" End Sub 'Macro for next second Sub nextTick() Sheet1.Range("B1").Value = Sheet1.Range("B1").Value - TimeValue("00:00:01") startTimer End Sub 'Macro for stopping the timer (attached to the end button) Sub stopTimer() Application.OnTime Now - TimeValue("00:00:01"), "nextTick", , False End Sub 

我稍微修改了你的代码,并把它放在一个标准模块中:

 Public Future As Double Sub StartTimer() Future = Now + TimeSerial(0, 0, 1) Application.OnTime earliestTime:=Future, procedure:="nextTime", _ schedule:=True End Sub Sub nextTime() Sheet1.Range("B1").Value = Sheet1.Range("B1").Value - TimeValue("00:00:01") StartTimer End Sub Sub StopTimer() On Error Resume Next Application.OnTime earliestTime:=Future, _ procedure:="nextTime", schedule:=False End Sub 

StartTimer()StopTimer()都运行得很好。