0

随附的 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
4

3 回答 3

1

每次第一次点击都对我有用。尝试卸载可能在容器应用程序内运行的任何加载项或任何其他代码,看看是否有帮助。

于 2010-01-30T17:07:59.530 回答
1

如果人们仍然需要答案,那么我研究并破解了它!

对于单击取消按钮,代码应该是;

Private Sub CommandButton1_Click()

Unload Me

'this bit ends all macros

End

End Sub
于 2012-02-08T12:14:24.257 回答
0

答案是对进度条使用模态用户窗体,以便可以触发按钮单击事件,而不会被调用过程中的处理所掩盖。

于 2010-02-20T18:06:58.177 回答