使用VBA(excel)在excel 2010中创建倒数计时器

时间:2016-05-11 20:49:21

标签: excel excel-vba vba

我正在使用Excel 2010,并希望在Excel中创建倒数计时器。将使用附加了宏的按钮启动和停止代码。当" start"按钮被按下。上面的代码使用Cell" B1"作为输入点,因为我只是试图让它工作,但每次我尝试,它总是会说:     "无法运行宏。宏可能在此工作簿中不可用,或者所有宏都可能被禁用"。

是的,我把所有的宏都放到这里之前启用了它。我希望能够接受用户输入,并使计时器开始的时间,而不是仅仅使用单元格" 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

1 个答案:

答案 0 :(得分:1)

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

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()都运行正常。