2013-07-19 27 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列。