首页 > 解决方案 > 宏运行时突然变慢

问题描述

我有一段相同的代码,它在以前的迭代中几乎立即运行,现在运行大约需要 5 分钟。我编辑了代码的其他部分,但是每当我在 5 分钟的时间内破坏代码时,它都会通过这个子部分工作。

Sub cleanup()

For i = 2 To 100000

'exits loop when it reaches a blank cell
If IsEmpty(Cells(i, 1)) = True Then Exit For

' formats for blanks
If Cells(i, 1) = Cells(i - 1, 1) Then
    For j = 4 To 15
        If IsEmpty(Cells(i - 1, j)) = True Then
        Cells(i - 1, j) = Cells(i, j)
        End If
    Next j
    Rows(i).Delete
    i = i - 1
End If

Next i

End Sub

我试过禁用事件和屏幕更新等,但无法弄清楚。请记住,这曾经是立即运行的,并且自从这些更改以来,我只更改了代码中的其他功能。不知道该怎么办。谢谢!

**

另一个非常奇怪的部分是当我再次运行宏时(在所有行都被删除之后)它仍然需要很长时间。在上面的宏中,第二次通过它甚至不应该进入第一个条件,但仍然需要很长时间。

**

标签: excelvbaperformanceoptimization

解决方案


Sub cleanup()

For i = Range("A" & Rows.Count).End(xlUp).Row + To 2 step -1

    If Cells(i, 1) = Cells(i - 1, 1) Then
        For j = 4 To 15
            If IsEmpty(Cells(i - 1, j)) Then Cells(i - 1, j) = Cells(i, j)
        Next j
        If CellArray Is Nothing Then
            Set CellArray = Rows(i)
        Else
            Set CellArray = Union(CellArray, Rows(i))
        End If
    End If
Next i

CellArray.Delete

End Sub

推荐阅读