我正在开发一个项目,该项目具有由空格分隔的不同数据列。我想从最旧的日期到最新的日期对每个数据块进行排序。当我录制宏并做了一些修改时,我没有出错就达到了这一点。
Dim tics As Integer
Dim lastSortRow As Integer
For tics = 0 To 2
lastSortRow = Cells(Rows.Count, tics * 3 + 1).End(xlUp).Row
Range(Cells(6, tics * 3 + 1), Cells(6, tics * 3 + 2)).Select
Range(Selection, Selection.End(xlDown)).Select
hiddenData.Sort.SortFields.Clear
hiddenData.Sort.SortFields.Add Key:=Range(Cells(7, 1), Cells(3715, 1)) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With hiddenData.Sort
.SetRange hiddenData.Range(Cells(6, 1), Cells(3715, 2))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next tics
问题是我想循环遍历所有数据。当我将代码更改为以下内容时,我得到错误1004:排序参考无效。确保它在您要排序的数据中,并且第一个“排序依据”框不相同或为空。
Dim tics As Integer
Dim lastSortRow As Integer
For tics = 0 To 2
lastSortRow = Cells(Rows.Count, tics * 3 + 1).End(xlUp).Row
Range(Cells(6, tics * 3 + 1), Cells(6, tics * 3 + 2)).Select
Range(Selection, Selection.End(xlDown)).Select
hiddenData.Sort.SortFields.Clear
hiddenData.Sort.SortFields.Add Key:=Range(Cells(7, tics * 3 + 1), Cells(lastSortRow, tics * 3 + 1)) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With hiddenData.Sort
.SetRange hiddenData.Range(Cells(6, 1), Cells(3715, 2))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next tics
End Sub
有谁知道为什么把变量放在keyrange和setrange会导致代码出错?