2012-06-14 62 views
0

自从我在Excel上使用VBA以来已经有一段时间了。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循环只要在范围内活动时不断走向何方?

回答

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 
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 
+0

+1代码不错。我正在考虑这个,但是当我在代码中玩时,我遇到了一些添加分类字段的问题。我选择清除它们然后添加它们。现在我明白了,你甚至不需要这种方法! –