在Excel VBA中迭代

时间:2012-06-14 21:46:25

标签: excel vba excel-vba excel-2007

自从我在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循环呢?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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