两个进程在VBA中

首先我应该说我在VBA上没有相关经验,但是我非常需要在excel中做一个计时器。 我设法创build了定时器的停止和开始button。 但是我有20个不同的定时器,有开始和停止button。 我想创build一个button,它将自动启动所有定时器,同时让我单独停止一个定时器。

我已经产生了以下代码来启动和停止它们。 但是,当我停止其中一个计时器时,出现以下错误:“运行时错误”1004“:object'_application的方法'onTime'失败。

两个开始和停止button的代码是:

Sub startTimer27() Application.OnTime Now + TimeValue("00:00:01"), "Increment_count27" End Sub Sub Increment_count27() Range("B2").Value = Range("B2") + 1 Range("B11").Value = Range("B11") + 1 Range("B19").Value = Range("B19") + 1 Range("B25").Value = Range("B25") + 1 Range("B33").Value = Range("B33") + 1 startTimer27 End Sub Sub stopTimer27() Application.OnTime Now + TimeValue("00:00:01"), "Increment_count27", Schedule:=False End Sub 

你有没有考虑使用全局variables保存当前的时间值?

 Sub startTimer27() starttime = Now 'MsgBox("The timer is running.") End Sub Sub stopTimer27() timetaken = Now - starttime MsgBox ("The time elapsed is " & Hour(timetaken) & ":" & Minute(timetaken) & ":" & Second(timetaken)) End Sub 

当然,以你的例子来说,它更像是:

 Public starttime(1 To 20) As Date Sub cvbstartTimer27() For i = 1 To 20 starttime(i) = Now Next End Sub 

如果你需要特别的停止它,那么你也必须给它一个布尔值,当定时器运行时是这样,当它停止时是false。 缺less这个值并不意味着你的代码是错误的。