代码运行时间太长,有时会崩溃

时间:2015-08-17 05:23:14

标签: excel vba excel-vba

您好,我有这个代码运行成功,但只是片刻之后。有时甚至会停止响应,然后再次正常运行。需要帮助才能更快地运行它而不会崩溃。这是代码

System.Transactions.Transaction.Current

1 个答案:

答案 0 :(得分:1)

您正在循环中删除单元格,这会使其变得非常慢。这是你在尝试什么?这应该非常快......(未经测试

Sub DeleteCells()
    Dim rng As Range, rngError As Range, delRange As Range
    Dim i As Long, j As Long

    On Error Resume Next
    Set rng = Application.InputBox("Select cells To be deleted", Type:=8)
    On Error GoTo 0

    If rng Is Nothing Then Exit Sub Else rng.Delete

    With Sheets("Sheet3")
        For i = 1 To 7 '<~~ Loop trough columns A to G
            '~~> Check if that column has any errors
            On Error Resume Next
            Set rngError = .Columns(i).SpecialCells(xlCellTypeFormulas, xlErrors)
            On Error GoTo 0

            If Not rngError Is Nothing Then
                For j = 1 To 100 '<~~ Loop Through rows 1 to 100
                    If .Cells(j, i).Text = "#REF!" Then
                        '~~> Store The range to be deleted
                        If delRange Is Nothing Then
                            Set delRange = .Columns(i)
                            Exit For
                        Else
                            Set delRange = Union(delRange, .Columns(i))
                        End If
                    End If
                Next
            End If
        Next
    End With

    '~~> Delete the range in one go
    If Not delRange Is Nothing Then delRange.Delete
End Sub