随附的 VBA 程序适用于进度条用户窗体。一切都按预期工作,除了取消按钮间歇性无响应。
我断断续续地说,因为 95% 的时间我必须在程序停止之前多次单击取消按钮。我可以看到按钮单击事件被动画化,但该过程没有被中断。在按钮按下事件发生之前,似乎有什么东西正在从取消按钮中窃取焦点。
退出和窗口关闭按钮按预期响应一键。
我需要做什么才能使取消按钮正确响应?谢谢!
更新:我注意到,当我单击并按住取消按钮时,它会被踢回,而不是按钮保持“向下”。所以显然有些东西正在将按钮状态重置为向上,速度足够快,以至于该过程没有捕捉到向下状态以触发点击事件。
这是用户表单模块(名为 UserForm1)中的代码:
Private mbooUserCancel As Boolean
Public Property Get UserCancel() As Boolean
UserCancel = mbooUserCancel
End Property
Private Property Let UserCancel(ByVal booUserCancel As Boolean)
mbooUserCancel = booUserCancel
End Property
Public Sub UpdateProgress(CountTotal As Long, CountProgress As Long)
On Error GoTo Error_Handler
ProgressBar1.Value = CountProgress / CountTotal * 100
DoEvents
Error_Handler:
If Err.Number = 18 Then CommandButton1_Click
End Sub
Private Sub CommandButton1_Click()
Hide
UserCancel = True
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Cancel = True
CommandButton1_Click
End Sub
Private Sub UserForm_Activate()
With Application
.Interactive = False
.EnableCancelKey = xlErrorHandler
End With
End Sub
Private Sub UserForm_Terminate()
Application.Interactive = True
End Sub
下面是调用 UserForm1 的模块(名为 Module1)的代码:
Sub TestProgress()
On Error GoTo Error_Handler
Dim objUserForm As New UserForm1
Dim lngCounter As Long
Dim lngSubCounter As Long
With objUserForm
.Show vbModeless
DoEvents
For lngCounter = 1 To 5
If .UserCancel Then GoTo Exit_Sub
For lngSubCounter = 1 To 100000000
Next lngSubCounter
.UpdateProgress 5, lngCounter
Next lngCounter
Application.Wait Now + TimeValue("0:00:02")
.Hide
End With
Exit_Sub:
If objUserForm.UserCancel Then
MsgBox "User Cancelled from UserForm1"
End If
Exit Sub
Error_Handler:
If Err.Number = 18 Then
Unload objUserForm
MsgBox "User Cancelled from Module1"
End If
End Sub