Why Do Do Until Loops Take So Long Excel Vba

The reason why Do Until loops can take a long time in Excel VBA is because they continue iterating until a certain condition is met. This means that if the condition is not being met or is being met very late in the loop, the loop can continue for a long time.

Here is an example to illustrate this:

    
      Dim i As Long
      i = 1
      
      Do Until i > 10
          ' Some code here
          
          i = i + 1
      Loop
    
  

In the above example, the loop continues until the value of i becomes greater than 10. If the code within the loop is not changing the value of i in a way that it becomes greater than 10, the loop will continue indefinitely.

To avoid such scenarios, it’s important to include code within the loop that modifies the condition being checked. Here’s an updated example:

    
      Dim i As Long
      i = 1
      
      Do Until i > 10
          ' Some code here
          
          ' Increment or modify i in a way that the condition will be met
          i = i + 2
      Loop
    
  

In the modified example, the value of i is incremented by 2 within the loop. This ensures that the condition i > 10 will eventually be met and the loop will exit.

It’s important to carefully design and test your Do Until loops to ensure they don’t run indefinitely, and to optimize the code within the loop to avoid unnecessary iterations.

Read more interesting post

Leave a comment