我有一个长度不断变化的范围。我需要在每次更改时重新定义命名范围,然后对其进行排序。
到目前为止,我有这个:
Sub Macro2()
'
' Name and Sort
'
Range("A3").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
ActiveWorkbook.Names.Add Name:="data4", RefersToR1C1:= _
"='Data Storage'!R3C1:R25C18"
ActiveWorkbook.Names("data4").Comment = ""
Application.Goto Reference:="data4"
ActiveWorkbook.Worksheets("Data Storage").sort.SortFields.Clear
ActiveWorkbook.Worksheets("Data Storage").sort.SortFields.Add Key:=Range( _
"D3:D25"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Data Storage").sort
.SetRange Range("A3:R25")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
但是下一次更改范围时,它只对前一个范围进行排序。我认为它与R3C1:R25C18参考有关,但我不知道每次改变范围时如何改变它。
感谢您的帮助。
答案 0 :(得分:0)
此代码检查包含数据的最后一行,命名范围,并对命名范围进行排序
Dim lngRowLast As Long
'Find last row
lngRowLast = Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Your range goes here
Range(cells(3,1),cells(lngRowLast,18)).Name = "data4"
Range("data4").Sort Key1:=Cells(3, 1), Order1:=xlAscending, _
Header:=xlYes