excel - 宏运行时突然变慢

标签 excel vba performance optimization

我有一段相同的代码,它在以前的迭代中几乎立即运行,现在运行大约需要 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

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

**

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

**

最佳答案

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

关于excel - 宏运行时突然变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52265175/

相关文章:

vba - Excel VBA : "&" after variable in DIM statement like "name&"

JavaScript:用局部变量替换参数?

Excel VBA代码打开文件

sql-server - 从 MS Access 调用存储过程会导致错误 3146

multithreading - OpenMP:堆数组性能较差(堆栈数组工作正常)

c++ - "real world"我期望的多线程性能改进是多少?

excel - 无法在 Excel 中找到唯一值

node.js - 在 node.js 中,如何评估 excel 中包含对同一工作簿中其他工作表中单元格的引用的公式?

Excel:将 IF 公式与 FREQUENCIES 和 MATCH 相结合

excel - VBA:使用对象变量循环字典中的项目