循环宏可以单独处理所有列,而无需编写重复转换的长列表

时间:2017-03-17 21:38:57

标签: excel vba excel-vba

我正在尝试循环此宏(下面)来浏览所有数据列,但需要一些帮助来创建循环或调整当前代码以适用于所有列。

Sub Trial_5()

'
    ActiveCell.Offset(0, -7).Columns("A:A").EntireColumn.Select
    ActiveWorkbook.Worksheets("Sheet6").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet6").Sort.SortFields.Add Key:=ActiveCell, _
        SortOn:=xlSortOnValues, Order:=xlDescending,    DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet6").Sort
        .SetRange ActiveCell.Range("A1:A16395")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        `enter code here`.SortMethod = xlPinYin
       .Apply
    End With
End Sub

我将.columns或activecell.offset调整为总范围??

调整后的脚本

Sub eachcolumndesending()
'
' eachcolumndesending Macro
' descending
'

'
    Columns("A:A").Select
    ActiveWorkbook.Worksheets("Sheet5").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet5").Sort.SortFields.Add Key:=Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlDescending,    DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet5").Sort
        .SetRange Range("A2:A32")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Columns("B:B").Select
    ActiveWorkbook.Worksheets("Sheet5").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet5").Sort.SortFields.Add Key:=Range("B1"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet5").Sort
        .SetRange Range("B1:B33")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

1 个答案:

答案 0 :(得分:2)

我建议您从录制的代码转移到VBA实际需要的单列排序。

Sub sortAllColumns()
    Dim c As Long

    On Error Resume Next  '<~~ may be necessary if a column breaks the sort 
    With Worksheets("Sheet5")
        For c = .UsedRange.Columns.Count To 1 Step -1
            With .Columns(c)
                .Cells.Sort Key1:=.Columns(1), Order1:=xlDescending, _
                            Orientation:=xlTopToBottom, Header:=xlGuess
            End With
        Next c
    End With
End Sub

顺便说一句,你可能不应该在存在标题的情况下使用xlGuess。是否有一个(xlYes)或没有(xlNo),但你知道你的数据比我好。