【问题标题】:DoEvents doesn't do the events... Why?DoEvents 不执行事件...为什么?
【发布时间】:2010-10-05 12:36:18
【问题描述】:

我正在使用DoEvents 来强制更新状态栏(或工作表中的某些单元格)中的进度指示器,如下面的示例代码所示。但是屏幕不刷新,或者在某些时候停止刷新。任务最终完成,但进度条无用。

DoEvents 为什么不“做事件”?我还能做些什么来强制屏幕更新?

编辑:我在 Windows XP 上使用 Excel 2003。

这是对earlier question 的跟进;感谢Robert Mearns 他的回答和下面的示例代码。

Sub ProgressMeter()

Dim booStatusBarState As Boolean
Dim iMax As Integer
Dim i As Integer

iMax = 100

    Application.ScreenUpdating = False
''//Turn off screen updating

    booStatusBarState = Application.DisplayStatusBar
''//Get the statusbar display setting

    Application.DisplayStatusBar = True
''//Make sure that the statusbar is visible

    For i = 1 To iMax ''// imax is usually 30 or so
        fractionDone = CDbl(i) / CDbl(iMax)
        Application.StatusBar = Format(fractionDone, "0%") & " done..."
        ''// or, alternatively:
        ''// statusRange.value = Format(fractionDone, "0%") & " done..."

        ''// Some code.......

        DoEvents
        ''//Yield Control

    Next i

    Application.DisplayStatusBar = booStatusBarState
''//Reset Status bar display setting

    Application.StatusBar = False
''//Return control of the Status bar to Excel

    Application.ScreenUpdating = True
''//Turn on screen updating

End Sub

【问题讨论】:

  • 你试过没有Application.ScreenUpdating = False吗?
  • 很好奇......它在我的机器上运行正常(添加一个内部循环以花费一些时间)......
  • 请发布 Excel 和操作系统版本

标签: vba excel


【解决方案1】:

我发现 DoEvents 并不总是完全可靠的。我建议尝试两种不同的方法。

首先,尝试在状态栏更新后立即调用 DoEvents(即,在您的 Some code .... 行之前)。

如果这不起作用,我发现在某些情况下使用睡眠 API 是一种更可靠的方法来产生处理器时间。如果 DoEvents 没有按我的意愿工作,这通常是我尝试的第一件事。您需要在模块顶部(函数外部)添加以下行:

    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

然后添加这一行来代替DoEvents

    Sleep 1   'This will pause execution of your program for 1 ms

如果 1 毫秒不起作用,您可以尝试使用 sleep 增加暂停程序的时间长度。

【讨论】:

    【解决方案2】:

    我发现在更新状态栏之前而不是之后调用 DoEvents 会产生更可预测/理想的结果。

    上面的代码 sn-p 是:

        fractionDone = CDbl(i) / CDbl(iMax)
        DoEvents
        Application.StatusBar = Format(fractionDone, "0%") & " done..."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 2017-07-08
      • 2023-02-21
      相关资源
      最近更新 更多