2013-07-19 56 views
1

我有一個excel工作表,每列的標題在第3行。
我想知道(通過excel vba)如何重新排列列(列D - Z)根據標題名稱按字母順序排列。
感謝您的指導。按字母順序重新排列工作表中特定列的範圍

例如。在安排之前

. . . . . column D | column E | column F | column G | ... 
row 1 
row 2 
row 3 zebra | car | monkey | balloon | ... 

例如。經過重新安排

. . . . . column D | column E | column F | column G | ... 
row 1 
row 2 
row 3 balloon | car | monkey | zebra | ... 

回答

1

你需要的任何排序算法,並將其應用到列(而不是行)

這裏有一個快速&葷一(確定它不是一個超快速分揀,只是出於我的記憶但...):

Sub HorSort(SortRange As Range, SortRow As Long) 
Dim Idx As Long, Jdx As Long, Kdx As Long, Tmp As Variant 

    For Idx = 1 To (SortRange.Columns.Count - 1) 
     For Jdx = 1 To (SortRange.Columns.Count - 1) 

     ' compare values in row to be sorted 
      If SortRange(SortRow, Jdx) > SortRange(SortRow, Jdx + 1) Then 

      ' swap all cells in column with the one to the right 
       For Kdx = 1 To SortRange.Rows.Count 
        Tmp = SortRange(Kdx, Jdx) 
        SortRange(Kdx, Jdx) = SortRange(Kdx, Jdx + 1) 
        SortRange(Kdx, Jdx + 1) = Tmp 
       Next Kdx 
      End If 
     Next Jdx 
    Next Idx 
End Sub 

Sub Test() 
    HorSort Selection, 1 
End Sub 

輸入在A1

5 2 4 1 3 
A D B E C 
1 2 3 4 5 

SEL以下數據ECT A1..E3和運行每個的

HorSort Selection, 1 
HorSort Selection, 2 
HorSort Selection, 3 

Sub Test()。你當然不限於5列。