DoEvents 函数DoEvents function

交出执行控制权,以便操作系统能够处理其他事件。Yields execution so that the operating system can process other events.

语法Syntax

DoEvents( )DoEvents( )

备注Remarks

DoEvents 函数返回一个 Integer,它表示独立版本的 Visual Basic(如 Visual Basic Professional Edition)中打开的窗体的数目。The DoEvents function returns an Integer representing the number of open forms in stand-alone versions of Visual Basic, such as Visual Basic, Professional Edition. DoEvents 将在所有其他应用程序中返回 0。DoEvents returns zero in all other applications.

DoEvents 将控制权交给操作系统。DoEvents passes control to the operating system. 控制权将在操作系统处理完其队列中的事件并发送 SendKeys 队列中的所有项后返回。Control is returned after the operating system has finished processing the events in its queue and all keys in the SendKeys queue have been sent.

DoEvents 对于诸如允许用户在过程开始后取消过程(如搜索文件)这样的简单操作最有用。DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. 对于长时间运行的过程,将执行控制权交给处理器要比使用计时器或将任务委派给 ActiveX EXE 组件好得多。For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component. 在后一种情况下, 任务可以完全独立于您的应用程序, 并且操作系统将负责执行多任务和时间切片。In the latter case, the task can continue completely independent of your application, and the operating system takes care of multitasking and time slicing.

只要将控制权临时交给事件过程中的处理器,就请确保在第一个调用返回之前,不会从代码的其他部分重新执行过程;这可能会导致出现意外结果。Any time you temporarily yield the processor within an event procedure, make sure the procedure is not executed again from a different part of your code before the first call returns; this could cause unpredictable results. 此外,如果其他应用程序可以在您已转交控制权的时间段内以无法预料的方式与过程交互,请不要使用 DoEventsIn addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.

示例Example

此示例使用 DoEvents 函数来使得每迭代 1000 次循环就将执行权交给操作系统。This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. DoEvents 返回打开的 Visual Basic 窗体的数目,但此情况仅在主机应用程序为 Visual Basic 时发生。DoEvents returns the number of open Visual Basic forms, but only when the host application is Visual Basic.

' Create a variable to hold number of Visual Basic forms loaded 
' and visible.
Dim I, OpenForms
For I = 1 To 150000    ' Start loop.
    If I Mod 1000 = 0 Then     ' If loop has repeated 1000 times.
        OpenForms = DoEvents    ' Yield to operating system.
    End If
Next I    ' Increment loop counter.


另请参阅See also

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.