加快Excel中列的删除

时间:2018-10-19 07:32:17

标签: excel vba excel-vba

我正在使用此公式删除工作表中的空列。但是删除它们大约需要15-20分钟。我可以以某种方式加快处理速度吗?这么长的时间很奇怪,我只处理100列。

For j = 1 To 5
    For i = 40 To 146
        If Sheet8.cells(4, i) = "" Then
            Columns(i).EntireColumn.Delete
        End If
    Next i
Next j

4 个答案:

答案 0 :(得分:6)

  

如果您有真实银行单元格,请使用SpecialCells(xlCellTypeBlanks)@Patrick Honorez answer ,这会更快。

但是,如果您没有没有真正的空白单元格(例如,公式显示为""),则可以使用以下方法:

Dim DeleteRange As Range

With sheet8
    Dim i As Long
    For i = 40 To 146
        If .Cells(4, i).Value = vbNullString Then 'vbNullString = ""
            If DeleteRange Is Nothing Then
                Set DeleteRange = .Columns(i)
            Else
                Set DeleteRange = Union(DeleteRange, .Columns(i))
            End If
        End If
    Next i
End With

If Not DeleteRange Is Nothing Then 'check if there is something to delete
    DeleteRange.EntireColumn.Delete
End If

它将收集您要在DeleteRange中删除的所有列,然后立即将其删除。这比单独删除每个列要快,因为每个删除操作都需要时间(这里只有一个删除操作)。

请注意,在这里我们不需要向后循环,因为我们只收集循环中的列,但是删除操作会在循环之后 出现,因此它根本不会影响循环计数。

答案 1 :(得分:3)

尝试:

For i = 146 To 40 step -1
    If Sheet8.cells(4, i) = "" Then
        Columns(i).EntireColumn.Delete
    End If
Next i

答案 2 :(得分:3)

尝试根据您的需要进行调整。我认为没有什么可以更快:-)

Sub test()
    Range("C3:j17").SpecialCells(xlCellTypeBlanks).EntireColumn.Delete
End Sub

答案 3 :(得分:2)

我建议那样做。

Option Explicit

Private Sub TurnOffFunctionality()
    Application.Calculation = xlCalculationManual
    Application.DisplayStatusBar = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False
End Sub
Private Sub TurnOnFunctionality()
    Application.Calculation = xlCalculationAutomatic
    Application.DisplayStatusBar = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

Sub TestIt()

Dim i As Long

    TurnOffFunctionality

    For i = 146 To 40 Step -1
        If Sheet8.Cells(4, i) = "" Then
            Columns(i).EntireColumn.Delete
        End If
    Next i

    TurnOnFunctionality

End Sub

特别关闭重新计算将确保不会在每次删除循环中的单个列时触发重新计算。这可能是长时间运行的原因。