Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

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

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...