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

假设您在第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) ,我find了最后一列和最后一行的编号。

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

我决定遵循@Davesexcel的出色build议做一些时间实验:

 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 

其中表面优势被翻转。 我已经尝试了许多不同的参数select,我无法获得清晰的信号。

如果我尝试运行time_test 5000, 25000, 50000 (这是你所问的),Excel会崩溃,出现关于Excel缺less资源来完成任务的错误消息 – 甚至在它到达计时阶段之前。

总结 – 任何差异似乎都很小,可能取决于实际使用的列数和行数。 如果您处于可能会有所作为的情况下,那么您可能会针对Excel内存限制运行,在这种情况下, xlDownxlUp之间的差异可能是您最担心的问题。