0

自从我在 Excel 上使用 VBA 已经有一段时间了。

我想按字母顺序排列工作表上每一列的内容。

这就是我所拥有的:

Range("A1").Select
    Range("A1:A19").Select
    ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Add Key:=Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet2").Sort
        .SetRange Range("A1:A19")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("B1").Select
End Sub

只要范围处于活动状态,我怎样才能使它成为一个持续运行的 for 循环?

4

2 回答 2

1

像这样?

Option Explicit

Sub sample()
    Dim i As Long

    With Sheets("Sheet1")
        For i = 1 To .UsedRange.Columns.Count
            .Columns(i).Sort Key1:=.Cells(1, i), Order1:=xlAscending, _
            Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
        Next i
    End With
End Sub
于 2012-06-15T02:37:25.687 回答
0

干得好。此代码假定您的数据以某种类型的表格格式排列。此外,它假设您希望对整个列进行排序(包括空白等)。如果您想使范围更具体,或者只是使用硬参考设置它,请调整我评论的代码。

Sub sortRange()

Dim wks As Worksheet
Dim loopRange As Range, sortRange As Range

Set wks = Worksheets("Sheet1")

With wks

    'can change the range to be looped, but if you do, only include 1 row of the range
    Set loopRange = Intersect(.UsedRange, .UsedRange.Rows(1))

    For Each cel In loopRange

        Set sortRange = Intersect(cel.EntireColumn, .UsedRange)

        With .Sort
            .SortFields.Clear
            .SortFields.Add Key:=sortRange
            .SetRange sortRange
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With

    Next

End With

End Sub
于 2012-06-14T22:09:54.370 回答