内存分配的VBA中的sortingfunction

我最近完成了一些循环遍历Excel中所有表单的代码,然后根据特定的列和列中的值对它们进行sorting

代码如下所示:

Sub sortingByLooping() Dim rngName As Range Dim sht As Worksheet Dim LastRow As Long Application.ScreenUpdating = False Application.Calculation = xlCalculationManual For Each sht In ActiveWorkbook.Worksheets sht.Activate Set rngName = sht.Range("1:1").Find(What:="SOMENAME", MatchCase:=False) If Not rngName Is Nothing Then LastRow = sht.Cells(sht.Rows.Count, rngName.Column).End(xlUp).Row On Error Resume Next Set emptyDates = sht.Range(rngDate, sht.Cells(LastRow, rngDate.Column)).SpecialCells(xlCellTypeBlanks) On Error GoTo 0 End If sht.Sort.SortFields.Clear If Not rngName Is Nothing Then sht.Sort.SortFields.Add Key:=rngName, _ SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal End If sht.Sort.SetRange sht.Cells sht.Sort.Header = xlYes sht.Sort.MatchCase = False sht.Sort.Orientation = xlTopToBottom sht.Sort.SortMethod = xlPinYin sht.Sort.Apply Next sht Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub 

这个代码很好地工作(我理解整个“用”和“结束”块,但我这样做,因为我觉得它在视觉上更容易阅读)。

但是我尝试了这样做之前:

sht.Sort.SetRange(sht.Cells)

当我设置范围和我被打了一个“内存不足”错误时,我把括号括在了sht.cells。 我很快把它改回到没有括号来纠正这个问题。

但是现在我想知道为什么当我将括号括在sht.cells中时为什么会出现这个错误,并且为什么当我没有在sht.cells周围放置括号时我没有得到这个错误? 围绕这个问题的内存问题是什么,还有什么其他的风险,我应该知道涉及这个特定的代码行?

谢谢

(sht.Cells)周围的圆括号将评估整个表格,以产生整个内容的二维数组(所有一百万奇数行×16k列)。 这不是你想要在这里发生的。

尝试在表单上使用更具体的范围,然后删除括号。