【发布时间】:2019-02-09 03:55:47
【问题描述】:
我遇到了一个问题,我创建了一个从指定时间倒计时到零的 VBA 计时器。这个宏运行了一段时间,因此,当我尝试打开另一个工作簿时没有任何反应,就像宏阻止另一个工作簿打开一样?
我的计时器子
Private Sub Timer15_main(play As Boolean)
Dim UserInput As String
If play Then
UserInput = TextBox1.Value 'this is what the user inputs and how long the timer should run
Else
timer_15_pause_button = False
UserInput = "00:15:00" 'this is what the user inputs and how long the timer should run
End If
'validate userinput und ensure hh:mm:ss format
Select Case Len(UserInput) - Len(Replace$(UserInput, ":", ""))
Case 2 'input format is hh:mm:ss
Case 1 'input format is mm:ss
UserInput = "00:" & UserInput
Case 0 'input format is ss
UserInput = "00:00:" & UserInput
Case Else
MsgBox "invalid input"
Exit Sub
End Select
'we need to convert the string UserInput into a double and
'convert it into seconds (Timer uses seconds!)
Dim SecondsToRun As Long
SecondsToRun = CDbl(TimeValue(UserInput)) * 24 * 60 * 60
TextBox4.Value = Format$((SecondsToRun / 24 / 60 / 60) + Time(), "hh:mm:ss")
Dim TimerStart As Double
TimerStart = Timer 'remember when timer starts
Do
If SecondsToRun - (Timer - TimerStart) < 10 Then
TextBox1.BackColor = RGB(255, 0, 0)
End If
TextBox1.Value = Format$((SecondsToRun - (Timer - TimerStart)) / 24 / 60 / 60, "hh:mm:ss")
'count backwards from 01:15 format as hh:mm:ss
DoEvents
If timer_15_pause_button = True Then
Exit Sub
End If
Loop While TimerStart + SecondsToRun > Timer 'run until SecondsToRun are over
TextBox1.BackColor = RGB(255, 255, 255)
'TextBox4.Value = ""
End Sub
【问题讨论】:
-
请在您的问题中包含您的计时器的 VBA,否则我们将无法提供太多帮助。
-
很难在没有看到任何代码的情况下判断。我猜你的计时器涉及某种循环和
DoEvents? -
请edit您的帖子包含有问题的“计时器循环”。
-
如果没有看到您的代码,我们只能说 VBA 代码正在 UI/主线程上运行,并且只要该线程忙于运行您的循环,它就不会做任何其他事情。您需要进入异步范例,以便 UI 线程不会被垄断。在循环体中有
DoEvents不是一个好的解决方案;查看Application.OnTime -
取决于表单的显示方式。请附上您的代码。