2012-06-14 91 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代碼不錯。我正在考慮這個,但是當我在代碼中玩時,我遇到了一些添加分類字段的問題。我選擇清除它們然後添加它們。現在我明白了,你甚至不需要這種方法! –