本文介绍了为什么将用户窗体显示为模态停止代码执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下VBA代码在Me.Show处停止.根据我的测试,即使代码位于UserForm中,似乎Me.Show也会停止所有代码执行.

The following VBA code stops at Me.Show. From my tests, it seems that Me.Show stops all code execution, even if the code is inside the UserForm.

此部分不在用户窗体中:

Public Sub TestProgress()
    Dim objProgress As New UserForm1
    objProgress.ShowProgress
    Unload objProgress
End Sub

此部分位于用户窗体中:

Private Sub ShowProgress()
    Me.Show vbModal
    Dim intSecond As Integer
    For intSecond = 1 To 5
        Application.Wait Now + TimeValue("0:00:01")
        Me.ProgressBar1.Value = intSecond / 5 * 100
    Next intSecond
    Me.Hide
End Sub

显示用户窗体后,代码在Me.Show处停止.没有错误,只是停止执行代码.似乎在VBA中的模式UserForm中执行代码的唯一方法是将其包含在UserForm_Activate过程中,如下所示:

The code stops at Me.Show, after the UserForm is displayed. There is no error, it just discontinues executing code. It seems that the only way to execute code inside a modal UserForm in VBA is to include it in the UserForm_Activate procedure like this:

此部分不在用户窗体中:

Public Sub TestProgress()
    Dim objProgress As New UserForm1
    Load objProgress
    Unload objProgress
End Sub

此部分位于用户窗体中:

Private Sub UserForm_Initialize()
    Me.Show vbModal
End Sub

Private Sub UserForm_Activate()
    Dim intSecond As Integer
    For intSecond = 1 To 5
        Application.Wait Now + TimeValue("0:00:01")
        Me.ProgressBar1.Value = intSecond / 5 * 100
    Next intSecond
    Me.Hide
End Sub

当然,我不能将Me.Show放在UserForm_Activate中,因为该过程仅在UserForm Show事件之后才触发.

Of course, I can't put Me.Show inside UserForm_Activate because that procedure only fires after the UserForm Show event.

UserForm.ShowModal的文档说:"当用户窗体为模态时,用户必须在使用应用程序的任何其他部分之前提供信息或关闭用户窗体.在隐藏或卸载用户窗体之前,不会执行任何后续代码. ."

我正在尝试将模式UseForm用作进度条,以防止用户在进程运行时与应用程序进行交互.但是,如果我所有的代码都必须位于UserForm_Activate过程中,那么将很难实现.

I am trying to use a modal UseForm as a progress bar to prevent the user from interacting with the application while a process runs. But this will be difficult to accomplish if all my code has to be within the UserForm_Activate procedure.

我在这里错过了什么吗?为什么所有代码​​执行都在Me.Show处停止?

Am I missing something here? Why does all code execution stop at Me.Show?

推荐答案

我想我明白了.

Me.Show之后,将触发UserForm_Activate事件.如果UserForm_Activate过程中没有代码,则不会发生任何事情,因为VBA正在等待Me.Hide.

After Me.Show the UserForm_Activate event fires. If there is no code in the UserForm_Activate procedure nothing will happen because VBA is waiting for Me.Hide.

所以事件的顺序是:Me.Show> UserForm_Activate> Me.Hide

So the order of events is: Me.Show > UserForm_Activate > Me.Hide

我要运行的任何代码都必须在UserForm_Activate过程中,并且必须在之前 Me.Hide.

Any code that I want to run must be in the UserForm_Activate procedure and must be before Me.Hide.

该结构非常严格,但我也许可以利用该结构以取得优势.

The structure is very strict, but I may be able to use that structure to my advantage.

这篇关于为什么将用户窗体显示为模态停止代码执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 19:42