.End(xlDown)与.End(xlUp)的性能影响

时间:2015-12-26 14:13:49

标签: excel vba excel-vba

假设您在第1列到第5,000列中有25,000到50,000行数据,每列可能有不同的行数。所有数据都是连续的,即列中没有空行而没有空列。

考虑以下代码

Dim i As Long
Dim Ws1 As Worksheet
Set Ws1 = ThisWorkbook.Worksheets(1)
Dim LastColumn As Long
Dim LastRow As Long

With Ws1
    LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
    For i = 1 To LastColumn
        LastRow = .Cells(.Rows.Count, i).End(xlUp).Row
        ThisWorkbook.Worksheets(2).Cells(i,1).Value = "Column: " & i & "has " & LastRow & "rows."
    Next i
End With

在这段代码中,我通过使用.End(xlToLeft).End(xlUp)找到了最后一列和最后一行的编号,它从工作表的末尾回到数据所在的位置。

我的问题是,如果你的数据是连续的,那么使用.End(xlToRight).End(xlDown)或者这个差异可以忽略不计?

1 个答案:

答案 0 :(得分:2)

我决定按照@Davesexcel的优秀建议做一些时间的实验:

Sub time_test(m As Long, n As Long, k As Long)
    Dim i As Long, r As Long, sum As Long, lastrow As Long
    Dim start As Double, elapsed As Double

    Application.ScreenUpdating = False

    lastrow = Range("A:A").Rows.Count
    Range(Cells(1, 1), Cells(lastrow, m)).ClearContents
    For i = 1 To m
        r = Application.WorksheetFunction.RandBetween(n, k)
        Cells(1, i).EntireColumn.ClearContents
        Range(Cells(1, i), Cells(r, i)).Value = 1
    Next i
    Debug.Print m & " columns initialized with " & n & " to " & k & " rows of data in each"
    Debug.Print "testing xlDown..."

    start = Timer
    For i = 1 To m
        sum = sum + Cells(1, i).End(xlDown).Value
    Next i
    elapsed = Timer - start
    Debug.Print sum & " columns processed in " & elapsed & " seconds"

    sum = 0

    Debug.Print "testing xlUp..."
    start = Timer
    For i = 1 To m
        sum = sum + Cells(lastrow, i).End(xlUp).Value
    Next i
    elapsed = Timer - start
    Debug.Print sum & " columns processed in " & elapsed & " seconds"
    Application.ScreenUpdating = True

End Sub

像这样使用:

Sub test()
    time_test 1000, 5000, 10000
End Sub

这会产生输出:

1000 columns initialized with 5000 to 10000 rows of data in each
testing xlDown...
1000 columns processed in 0.1796875 seconds
testing xlUp...
1000 columns processed in 0.0625 seconds

表明使用xlUp会更好。

另一方面,如果我运行time_test 5000, 500, 1000

我得到了输出:

5000 columns initialized with 500 to 1000 rows of data in each
testing xlDown...
5000 columns processed in 0.08984375 seconds
testing xlUp...
5000 columns processed in 0.84375 seconds

其中明显的优势被翻转。我已经尝试了许多不同的参数选择,但无法获得明确的信号。

如果我尝试运行time_test 5000, 25000, 50000(这就是您所询问的内容),Excel崩溃时会显示一条错误消息,指出Excel缺少资源来完成任务 - 在它到达计时阶段之前。

总结一下 - 任何差异似乎都很小,可能取决于实际使用的列数和行数。如果您处于可能产生影响的情况,那么您可能正在运行Excel内存限制,在这种情况下,xlDownxlUp之间的差异可能是您最不担心的。