我有一个选定的范围,在该范围内我希望按特定列排序,以便每行保持相同,即排序函数只根据我选择排序的列重新排序整行。 / p>
到目前为止,我的代码是:
Sub CustomSortAscendingExcel(ByVal control As IRibbonControl, ByRef cancelDefault As Variant)
Dim selRange As range
Dim usedRange As range
Dim checkRange As range
Dim shtData As Worksheet
Set shtData = Worksheets("Data")
shtData.Activate
shtData.Unprotect
Set selRange = Selection
Set usedRange = returnUsedRange
Set checkRange = Intersect(usedRange, selRange)
If Not Application.Intersect(usedRange, selRange) Is Nothing Then
With ActiveSheet
usedRange.Sort Key1:=selRange, Order1:=xlAscending, DataOption1:=xlSortNormal, MatchCase:=False, SortMethod:=xlPinYin, _
Header:=xlNo, Orientation:=xlSortColumns
.Sort.Apply
End With
类似于排序降序。这适用于column1。我的问题是,对于第2,3,4列,它只适用于那些在column1中具有值而不是任何不具有值的行。例如,在下面的图像中,按列3排序正确地重新排序前9行而不是最后两行。
有人可以建议一种解决方法吗?谢谢!
答案 0 :(得分:4)
我录制了一个选择范围的简单宏(“A1:D5”),应用过滤器,然后根据第3列(C)按升序排序
看看这个:
Range("A1:D5").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add Key:=Range _
("C1:C5"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
现在,您无需做太多事情来解决问题:)