删除行VBA宏需要花费大量时间

时间:2015-07-13 18:17:30

标签: excel excel-vba time lines vba

我有一个宏,它根据列中的某个值删除行,然后对它们进行排序。它工作正常。但是,工作表以大约4000行开始,宏最终会删除大约2000行,并且需要1分25秒才能完成。我想知道我能做些什么会让它花费更少的时间。这是代码:

    function sortAscending(data_A, data_B)
{
    return (data_A - data_B);
}
var array =[ 9, 10, 21, 46, 19, 11]
array.sort(sortAscending) 
alert(array);

2 个答案:

答案 0 :(得分:2)

在开头添加:

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

最后添加:

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

此外,而不是

If (Cells(i, 2).Value <> 0.04 And Cells(i, 2).Value <> 0.045 And Cells(i, 2).Value <> 0.05 And Cells(i, 2).Value <> 0.056 And Cells(i, 2).Value <> 0.063 And Cells(i, 2).Value <> 0.071 And Cells(i, 2).Value <> 0.08 And Cells(i, 2).Value <> 0.09 Or Cells(i, 3).Value <= 0) Then

    ActiveSheet.Rows(i).EntireRow.Delete

End If

使用

Select Case Cells(i, 2)
Case 0.4, 0.045, 0.05, 0.056, 0.063, 0.071, 0.08, 0.09, Is < 0
    'Do nothing
Case Else
    ActiveSheet.Rows(i).EntireRow.Delete
End Select

答案 1 :(得分:0)

我更喜欢构建一个要删除的行字符串,然后执行一次删除操作。这是我昨天在这里为另一篇文章整理的一个例子:

Sub DeleteRows()
Dim i As Long, DelRange As String
For i = 1 To Cells(Rows.Count, 6).End(xlUp).Row 'Doesn't matter which way you go when you delete in one go
    If Left(Cells(i, 6), 3) = "314" Then DelRange = DelRange & "," & i & ":" & i 'Change the "314" as you see fit
Next i
Range(Right(DelRange, Len(DelRange) - 1)).Delete
End Sub

当您只执行一次删除时,也无需担心关闭计算或屏幕更新等