Doevents vba excel как использовать

In this Article

  • VBA DoEvents Example
    • DoEvents Dangers
    • When to use DoEvents

This tutorial will discuss how to use the DoEvents command in VBA.

The VBA DoEvents function temporarily pauses a running macro, giving Excel a chance to process key presses, mouse clicks, and other operating system messages.

In long-running macros, Excel can appear to hang and become unresponsive, and the macro may be impossible to interrupt. If DoEvents is included in your code, users can be assured that the macro is still running, and can still interrupt execution if necessary.

VBA DoEvents Example

Consider the following code:

Public Sub Test()
    Dim i As Long

    For i = 1 To 20000
        Range(“A1”).Value = i
    Next i

End Sub

When you try this code, you’ll note that the Excel window can’t be interacted with. However, because it’s not very demanding on the processor, the macro can still be interrupted by pressing ESC or CTRL+BREAK.

If a lot of complex and demanding functions were being performed inside this loop, Excel would take longer to register a key press event – up to several minutes or possibly not at all, especially if the computer is running other programs at the same time.

Now add a single line with DoEvents below the Range assignment:

        Range("A1").Value = i
        DoEvents

If you run this code again, you’ll see that Excel is now responsive – it can be focused and brought to the foreground.  DoEvents is called every time through the loop, which ensures that the macro is always yielding execution so that Excel can process any messages sent to it.  Because this macro runs quickly, it almost seems as though it’s running in the background (though it isn’t) – more operations inside the loop would quickly expose that illusion.

DoEvents Dangers

Take a second look, though. More than simply allowing Excel to be focused, you can actually click around inside cells and even switch tabs while the macro is running (try it – you’ll see some funny behavior).  This shows one of the dangers of DoEvents – it can be the cause unintended consequences if your macro isn’t coded carefully.

Another danger is that DoEvents can serve as a window for other macros to run inside of.  Try this: place an ActiveX CommandButton on the worksheet, double-click it, and add the following code inside the CommandButton1_Click() event:

    Dim c As Range

    For Each c In Range("B3:E8")

        c.Value = c.Value + 1

    Next c

Toggle off Design Mode in Excel, then run the Test() macro you added earlier.  While the Test macro is running, you can click the CommandButton on the worksheet, and its associated macro will run as soon as DoEvents gives the Test() macro a break.

The danger here is if the CommandButton macro altered the data the Test() macro was working on, or triggered the Test() macro again.  You can end up with some extremely messy results if you’re not careful.

Finally, you should be aware that DoEvents will cause your macro to suffer a performance impact when called.  Inside a loop, this impact will add up quickly unless you limit how often DoEvents is called.  Referring to our Test() example, try this:

        If i Mod 1000 = 0 Then DoEvents

This visibly reduces Excel’s responsiveness, but the performance impact will be lessened.

When to use DoEvents

Despite these dangers, DoEvents is a handy function that aids in testing and debugging.  Consider adding DoEvents to long-running loops.

Another reason to include DoEvents is to allow for user feedback. For example, a macro might update a UserForm’s labels with progress indicators. Without DoEvents, Excel may not receive the messages to repaint the UserForm, giving a user the impression that the macro has stopped working – especially if you switch to another program and then try to switch back to Excel. With DoEvents however, the UserForm will continue to be repainted, and updates to the macro’s progress will continue to appear.

For the most part, DoEvents isn’t something you’ll want to include a lot in your code, and can often be omitted.  If responsiveness is something your macro needs though, don’t count it out!

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

  • Функция Excel VBA DoEvents

Функция Excel VBA DoEvents

Когда мы пишем огромные коды, мы всегда попадаем в ловушку VBA. Когда код большой, VBA тратит свое время на завершение запуска и выполнения процесса. Что может занять время от минуты до нескольких минут. Это период времени, когда все раздражаются. И мы не можем больше ничего делать в этот период времени. Но чтобы избежать этого, у нас в VBA есть функция DoEvents. С помощью DoEvents мы можем запускать код в фоновом режиме, и одновременно мы можем делать и другие вещи. Мы можем не только работать с другим инструментом или программным обеспечением, но также можем прерывать код или останавливаться между процессами исполнения.

Как только мы введем DoEvents в коде, кроме VBA, мы также получим контроль над работой, которую мы хотим сделать. Хорошая вещь о DoEvents — у него нет никакого синтаксиса для записи. Мы можем напрямую разместить Doevents там, где мы хотим взять под контроль VBA и выполнять задачи в соответствии с нашими потребностями.

Как использовать функцию DoEvents в Excel VBA?

Ниже приведены различные примеры использования функции DoEvents в Excel с использованием кода VBA.

Вы можете скачать этот шаблон VBA DoEvents Excel здесь — Шаблон VBA DoEvents Excel

Excel VBA DoEvents — Пример № 1

Хотя для выполнения DoEvents нам нужен огромный набор данных, где мы можем видеть, как код прерывается. Итак, мы будем использовать цикл, в котором числа будут применяться до тех пор, пока код не будет завершен. Для этого выполните следующие шаги:

Шаг 1: Откройте модуль в VBA из вкладки меню Вставка, как показано ниже.

Шаг 2: Напишите подпроцедуру VBA DoEvents, или мы можем выбрать любое имя, чтобы определить код в соответствии с нашими потребностями.

Код:

 Sub VBA_DoEvents () End Sub 

Шаг 3: Теперь определите переменную в любом имени с типами данных Long. Цель рассматривать тип данных как Long, потому что мы будем брать любую длину данных, которую мы хотим, что невозможно, если мы рассмотрим Integer.

Код:

 Sub VBA_DoEvents () Dim A As Long End Sub 

Шаг 4: Теперь откройте цикл For-Next, в который мы поместим условия.

Код:

 Sub VBA_DoEvents () Dim A As Long для следующего A End Sub 

Шаг 5: Рассмотрите диапазон числа по вашему выбору, который может быть замечен при реализации. Здесь мы берем диапазон от 1 до 2000 в определенной переменной A.

Код:

 Sub VBA_DoEvents () Dim A As Long для A = 1 до 20000 Next A End Sub 

Шаг 6: Как только мы определим диапазон чисел, мы выберем диапазон ячеек, где мы увидим изменения в числах, которые мы выбрали выше. Допустим, диапазон ячеек от А1 до А5. Это может быть и отдельная клетка.

Код:

 Sub VBA_DoEvents () Dim A As Long для диапазона A = от 1 до 20000 («A1: A5»). Значение = A Next A End Sub 

Шаг 7: Теперь запустите код, нажав кнопку Play, расположенную под строкой меню.

Мы увидим, что код завершился печатью чисел от 1 до 20000, но мы не смогли это остановить.

Шаг 8: Чтобы получить полный контроль над кодом, примените DoEvents после условий цикла, как показано ниже.

Код:

 Sub VBA_DoEvents () Dim A As Long для диапазона A = от 1 до 20000 («A1: A5»). Значение = A DoEvents Next A End Sub 

Шаг 9: Теперь снова запустите код. И в это время мы пытаемся остановить код, нажав кнопку «стоп», и мы заметим, что код будет остановлен между процессами до завершения пробной версии 20000.

Excel VBA DoEvents — Пример № 2

Существует другой тип процесса для реализации DoEvents. Но для этого нам также понадобится огромный код, как показано в примере-1. Для этого выполните следующие шаги:

Шаг 1: Напишите подпроцедуру VBA DoEvents, как показано ниже.

Код:

 Sub VBA_DoEvents2 () End Sub 

Шаг 2: Непосредственно открыть цикл For-next без определения переменной.

Код:

 Sub VBA_DoEvents2 () для следующего конца Sub 

Шаг 3: Выберите диапазон номеров, который будет работать. Пусть диапазон будет от 1 до 20000, как в примере-1.

Код:

 Sub VBA_DoEvents2 () для A = 1 до 20000 Next End Sub 

Шаг 4: Теперь непосредственно поместите любую работу для вывода, скажем, вывод такой, как показано ниже. И диапазон значений будет +1 от фактического значения.

Код:

 Sub VBA_DoEvents2 () Для A = 1 до 20000 Выход = Выход + 1 Следующий конец Sub 

Шаг 5: Теперь выберите диапазон, в котором мы хотим увидеть результат. Пусть клетка будет A1.

Код:

 Sub VBA_DoEvents2 () Для A = от 1 до 20000 Выход = Выход + 1 Диапазон («A1»). Значение = Выход Next End Sub 

Шаг 6: И наконец, мы поставим DoEvents в конце условия цикла For.

Код:

 Sub VBA_DoEvents2 () Для A = от 1 до 20000 Выход = Выход + 1 Диапазон («A1»). Значение = Выход DoEvents Next End Sub 

Шаг 7: Затем запустите код, нажав клавишу F5. Мы увидим, что мы можем делать что угодно, даже когда код работает. Для демонстрации я выбрал ячейки B1 и C1. Цифры достигли только 4348, что намного меньше установленного нами лимита.

Шаг 8: Если мы удалим DoEvents и запустим код, мы не сможем ничего сделать, пока код не завершит свой процесс. Давайте посмотрим это тоже.

Код:

 Sub VBA_DoEvents2 () Для A = от 1 до 20000 Выход = Выход + 1 Диапазон («A1»). Значение = Выход Next End Sub 

Шаг 9: Теперь запустите код снова. Как мы видим, пока мы пытались нажать «Стоп», код не останавливался. И функция воспроизведения все еще была включена.

Плюсы и минусы Excel VBA DoEvents

  • Мы можем работать с любым инструментом или файлом в фоновом режиме, пока код VBA будет работать параллельно.
  • Использование DoEvents не мешает нам делать ту работу, которую мы хотим, когда выполняется код.
  • Он перезаписывает рабочий лист или рабочую книгу, когда мы переключаемся между различными рабочими листами или рабочей книгой.
  • Код останавливается, когда мы пишем или меняем ячейку на мгновение, и мы не получаем уведомление.

То, что нужно запомнить

  • Если мы делаем что-либо без применения DoEvents, то существует большая вероятность того, что код сделает систему и файл заблокированными. И что мы либо возобновим файлы после того, как код будет полностью запущен, либо сломаем файл несколькими щелчками мыши.
  • Мы можем видеть изменения в процессе, одновременно работая над другой работой.
  • После завершения кода сохраните файл в формате Excel с поддержкой макросов, чтобы избежать потери кода.
  • Попробуйте применить код в огромном и большом наборе кодирования, там мы увидим фактическую реализацию и использование.

Рекомендуемые статьи

Это руководство по VBA DoEvents. Здесь мы обсуждаем, как использовать функцию DoEvents в Excel с использованием кода VBA, а также с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Как использовать StrConv в Excel VBA?
  2. Преобразование чисел в текст в Excel (примеры)
  3. Функция VBA ByRef (Примеры с шаблоном Excel)
  4. Excel SUMIFS с датами | Шаблон Excel

Excel VBA DoEvents Function

With the help of VBA DoEvents, we can make the code run in the background and simultaneously allow us to work with excel and other application software. Furthermore, DoEvents allows us to work with other software and interrupt the running of the code.

The DoEvents function passes control to the operating system of the computer we are working on.

Table of contents
  • Excel VBA DoEvents Function
    • How to use DoEvents Function?
      • Interrupt the Code Running
    • Recommended Articles

VBA-DoEvents

How to use DoEvents Function?

A large amount of VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more is required when the requirement is huge. In those cases, Excel hangs and stops for some time, sometimes becoming unresponsive.

You can download this VBA DoEvents Excel Template here – VBA DoEvents Excel Template

For example, look at the below code.

Code:

Sub DoEvents_Example1()

    Dim i As Long

    For i = 1 To 100000

        Range("A1").Value = i

    Next i

End Sub

VBA DoEvents Example 1.1

The above code will insert serial numbers from 1 to 100000. Therefore, executing the task will take more than a minute. During the execution, excel hangs for a considerable time to complete the task. During this time, Excel shows the message “Excel Not RespondingWhen the Excel software hangs or freezes in the middle of a task, the «Excel no responding» message pops. There are multiple reasons which leads to such errors and there are multiple ways to troubleshoot his problem as well.read more.”

VBA DoEvents Example 1.3

Moreover, we cannot access the worksheet we are working on. It is a frustrating thing. So how do we make the Excel worksheet available to work while the code is running behind the screen?

We can achieve it by adding a VBA DoEvents function.

Code:

Sub DoEvents_Example1()

     Dim i As Long

     For i = 1 To 100000

          Range("A1").Value = i
          DoEvents

    Next i

End Sub

Example 1.2

When we add the function DoEvents in the code, we can access the Excel worksheet.

GIF

The above shows that the code is running, but we can access the worksheet.

Interrupt the Code Running

When the code runs behind the screen, we can add rows and columns, delete the same, rename the sheet, and do many other things. The moment we add DoEvents, it makes the VBA code run fast and allows us to feel that the mentioned task is running for itself.

  • One of the dangers of the DoEvents function is when we switch worksheets or workbooks, which overwrites the active sheet values.
  • Another danger is if we enter any value to the cell, the code execution halts, and it doesn’t even notify us.

Note: Despite the above dangers of DoEvents, it is still a handy function. We can use DoEvents as part of the debugging process when we try to fix bugs in the code we have written.

Recommended Articles

This article has been a guide to VBA DoEvents. Here, we learn how and when to use the DoEvents function in Excel VBA with the help of an example and a downloadable Excel sheet. You can learn more from the following articles: –

  • Double Data Type in VBA
  • Declare Array in VBA
  • VBA FreeFile
  • VBA Split

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

DoEvents function (Visual Basic for Applications)

vblr6.chm1014016

vblr6.chm1014016

office

b38afdfe-9f8a-ac15-3e02-47184dae69c5

12/12/2018

medium

Yields execution so that the operating system can process other events.

Syntax

DoEvents( )

Remarks

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 returns zero in all other applications.

DoEvents passes control to the operating system. 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 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. 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. In addition, don’t use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.

Example

This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. 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

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

VBA DoEvents

Excel VBA DoEvents Function

When we write huge codes, we always fall into the trap of VBA. When the code is big, VBA takes its own time to finish the running and executing process. Which may take time from a minute to several minutes. This is the time frame when everyone gets irritated. And we cannot do anything else in this time period. But to avoid this, we have a function in VBA called DoEvents. By the help of DoEvents, we can run the code in the background and simultaneously we can do other kinds of stuff as well. We cannot only work on other tool or software but also we can interrupt the code or stop in between the process of execution.

Once we enter DoEvents in the code, then apart from VBA, we will also be having the control of work we want to do. The good thing about DoEvents is it doesn’t have any kind of syntax to write. We can directly place Doevents where we want to take control of VBA and perform the tasks as per our need.

How to Use DoEvents Function in Excel VBA?

Below are the different examples to use DoEvents function in excel using VBA code.

You can download this VBA DoEvents Excel Template here – VBA DoEvents Excel Template

Excel VBA DoEvents – Example #1

Although to execute DoEvents we need a huge set of data where we can see how the code is getting interrupted. So, we will use a loop, where the numbers will get applied until the code is completed. For this, follow the below steps:

Step 1: Open a module in VBA from Insert menu tab as shown below.

VBA DoEvents Example 1-1

Step 2: Write the subprocedure of VBA DoEvents or we can choose any name to define the code as per our need.

Code:

Sub VBA_DoEvents()

End Sub

VBA DoEvents Example 1-2

Step 3: Now define a variable in any name with data types Long. Purpose of considering the data type as Long is because we will be taking any length of data we want which is not possible if we consider Integer.

Code:

Sub VBA_DoEvents()

Dim A As Long

End Sub

VBA DoEvents Example 1-3

Step 4: Now open a For-Next loop where we will put the conditions.

Code:

Sub VBA_DoEvents()

Dim A As Long

For

Next A

End Sub

VBA DoEvents Example 1-4

Step 5: Consider the range of a number of your choice which can be seen getting implemented. Here we are taking the range 1 to 2000 in defined variable A.

Code:

Sub VBA_DoEvents()

Dim A As Long

For A = 1 To 20000

Next A

End Sub

VBA DoEvents Example 1-5

Step 6: Once we define the range of numbers, we will select the range of cells where we will see the changes in numbers which we chose above. Let’s say the range of cells is A1 to A5. This could be a single cell as well.

Code:

Sub VBA_DoEvents()

Dim A As Long

For A = 1 To 20000
  Range("A1:A5").Value = A
Next A

End Sub

VBA DoEvents Example 1-6

Step 7: Now run the code by clicking on the Play button located below the menu bar.

VBA DoEvents Example 1-7

We will see, the code has completed by printing the numbers from 1 to 20000 but we couldn’t stop it.

Step 8: To get full control of the code, apply DoEvents after the loop conditions as shown below.

Code:

Sub VBA_DoEvents()

Dim A As Long

For A = 1 To 20000
  Range("A1:A5").Value = A
  DoEvents
Next A

End Sub

VBA DoEvents Example 1-8

Step 9: Now again run the code. And at this time we try to stop the code by clicking the stop button, we will notice that code will get stopped between the processes before completing the trial of 20000.

VBA DoEvents Example 1-9

Excel VBA DoEvents – Example #2

There is another type of process for implementing DoEvents. But for this also we will need huge code as seen in example-1. For this, follow the below steps:

Step 1: Write the subprocedure of VBA DoEvents as shown below.

Code:

Sub VBA_DoEvents2()

End Sub

VBA DoEvents Example 2-1

Step 2: Directly open a For-next loop without defining a variable.

Code:

Sub VBA_DoEvents2()

For

Next

End Sub

VBA DoEvents Example 2-2

Step 3: Choose a number range we will see running. Let the range be 1 to 20000 same as example-1.

Code:

Sub VBA_DoEvents2()

For A = 1 To 20000

Next

End Sub

VBA DoEvents Example 2-3

Step 4: Now directly put any work for output, let’s say the output is as shown below. And the value range will be +1 of actual value.

Code:

Sub VBA_DoEvents2()

For A = 1 To 20000
Output = Output + 1

Next

End Sub

VBA DoEvents Example 2-4

Step 5: Now select the range where we want to see the output. Let the cell be A1.

Code:

Sub VBA_DoEvents2()

For A = 1 To 20000
Output = Output + 1
Range("A1").Value = Output
Next

End Sub

VBA DoEvents Example 2-5

Step 6: And at last we will put DoEvents at the end of For loop condition.

Code:

Sub VBA_DoEvents2()

For A = 1 To 20000
Output = Output + 1
Range("A1").Value = Output
DoEvents
Next

End Sub

VBA DoEvents Example 2-6

Step 7: And then run the code by pressing F5 key. We will see, we can do anything even when the code is running. For demonstration, I have selected the cells B1 and C1. The numbers reached at 4348 only which is quite less than the limit we set.

VBA DoEvents Example 2-7

Step 8: If we remove the DoEvents and run the code, we will be not able to do anything until the code gets completes its process. Let’s see that also.

Code:

Sub VBA_DoEvents2()

For A = 1 To 20000
Output = Output + 1
Range("A1").Value = Output
Next

End Sub

VBA DoEvents Example 2-8

Step 9: Now run the code again. As we can see, while we tried to click on Stop, the code didn’t stop. And the Play feature was still ON.

VBA DoEvents Example 2-9

Pros and Cons of Excel VBA DoEvents

  • We can work on any tool or file in the background while the VBA code will be running in parallel.
  • Using DoEvents doesn’t stop us doing the work we want when the code is running.
  • It overwrites the worksheet or workbook when we switch between the different worksheets or workbook.
  • The code stops when we write or change the cell for a moment and we don’t get notified.

Things to Remember

  • If we do anything without applying DoEvents, then there is a major possibility that the code makes the system and file freezed. And that we will either resume the files once the code is completely run or crash the file on multiple clicks.
  • We can see the change in the process while working on the other work simultaneously.
  • Once we complete the code, save the file in macro-enabled excel format to avoid losing code.
  • Try applying the code in a huge and big set of coding, there we will see the actual implementation and use.

Recommended Articles

This is a guide to VBA DoEvents. Here we discuss how to use DoEvents function in Excel using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA StrConv
  2. VBA ByRef
  3. VBA RGB
  4. VBA XML

Понравилась статья? Поделить с друзьями:
  • Doesn know the meaning of the word
  • Doesn keep his word
  • Does word suggest mean
  • Does word peoples exist
  • Does word have a spreadsheet