Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code in VBA loops and never ends. How to fix this?

Tags:

excel

vba

I run this code to delete rows which have have > -100. However it keeps looping and never stops.

What am I missing here?

For i = 2 To 500
If Worksheets("Sales").Cells(i, 3).Value > -100 Then
   Worksheets("Sales").Cells(i, 3).EntireRow.Delete
   i = i - 1
End If
Next i
like image 357
EnexoOnoma Avatar asked Nov 16 '15 20:11

EnexoOnoma


People also ask

How do you stop an endless loop in Excel VBA?

Option 1: Hold the Esc key down for more than a few seconds. Option 2: Press CTRL+BREAK. Option 3: CTRL + ALT + DEL to end process & have Auto recover when you re-open.

How do I stop a Macro being stuck in a loop?

If the Macro is simply in a continuous loop or is running for too long you can use one of these keyboard shortcuts to kill it: Esc hit the Escape key. Ctrl + Break hit Ctrl key and then the break key, which is also the pause key.

How do you end a while loop in VBA?

We can exit any Do loop by using the Exit Do statement.


1 Answers

Maybe you could union the rows and delete them at once? Something like this (untested).

Dim myRow As Range
Dim toDelete As Range

For i = 2 To 500
    If Worksheets("Sales").Cells(i, 3).Value > -100 Then
       Set myRow = Worksheets("Sales").Rows(i)
       If toDelete Is Nothing Then
            Set toDelete = myRow
        Else
            Set toDelete = Union(toDelete, myRow)
        End If
    End If
Next i

If Not toDelete Is Nothing Then _
    toDelete.Delete
like image 108
Daniel Dušek Avatar answered Sep 23 '22 15:09

Daniel Dušek