我想在Excel中编写一个VB脚本,它基本上将所有列放在(或包含)活动单元格的右侧,并在第1行从左到右排序。
目前,我已经:
ActiveCell.CurrentRegion.Select
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:=ActiveCell.CurrentRegion, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveSheet.Sort
.SetRange ActiveCell.CurrentRegion
.Header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
End Sub
现在,至少有两个问题:1)我知道currentregion并没有给我我想要的东西,但更重要的是,这给了我一个错误,排序参考无效
答案 0 :(得分:1)
请参阅以下代码,了解根据您的需求进行排序的示例。注意:代码将排序范围设置为INCLUDE activecell列。
如果您需要其他帮助以及您可能遇到的任何其他问题,请告知我们。
Sub SortBasedOnActiveCell()
Dim sActive As Worksheet
Dim rActive As Range
Dim rLastCell As Range
Dim rSortRange As Range
Set sActive = ActiveSheet
Set rActive = ActiveCell
'Below will work if the sheet is laid out "normally"
'with contiguous rows and columns. If not, then consider building
'in different business logic to determine the end of your sort range
Set rLastCell = sActive.Cells.SpecialCells(xlCellTypeLastCell)
Set rSortRange = Range(sActive.Cells(1, rActive.Column), rLastCell)
sActive.Sort.SortFields.Clear
sActive.Sort.SortFields.Add Key:=Intersect(sActive.Rows(1), rSortRange), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With sActive.Sort
.SetRange rSortRange
.Header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
End Sub