VBA按columssorting区域

我想在Excel中编写一个VB脚本,基本上将所有列都放在(或包含)活动单元格的右侧,并在第1行上将它们从左到右sorting。

目前,我有:

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 

现在,至less有两个问题:1)我知道,currentregion不给我我想要的,但更重要的是,这给了我一个错误,sorting引用是无效的

请参阅下面的代码,根据您的需要进行sorting。 注意:代码将sorting范围设置为INCLUDE活动单元的列。

让我们知道是否需要额外的帮助来适应它,或者您可能有其他任何问题。

 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