2009-09-20 82 views
3

我使用VBA對Excel 2003中的列進行排序。我需要按第5列升序排序,然後第3列使用自定義順序排序,然後按第4列升序排序。我很難得到這樣的工作,我不完全理解OrderCustom是如何應用的。使用VBA多列排序

任何指針在正確的方向將不勝感激:)我的代碼如下。

With wsData 
    lastrow = .Cells(Rows.Count, 1).End(xlUp).Row + 1 
    lastCol = .Cells(4, Columns.Count).End(xlToLeft).Column 

    Dim n As Long 
    Application.AddCustomList ListArray:=Array("LOW", "MEDIUM OR HIGH", "HIGH ONLY") 
    n = Application.GetCustomListNum(Array("LOW", "MEDIUM OR HIGH", "HIGH ONLY")) + 1 

    Dim strSortOrder As String 
    .Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _ 
     Key1:=.Range(.Cells(2, 5), .Cells(lastrow, lastCol)), Order1:=xlAscending, _ 
     Key2:=.Range(.Cells(2, 3), .Cells(lastrow, lastCol)), Order2:=xlDescending, _ 
     Key3:=.Range(.Cells(2, 4), .Cells(lastrow, lastCol)), Order3:=xlDescending, _ 
     OrderCustom:=n, _ 
     MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes 
End With 

回答

3

嘗試分裂您的排序爲3個獨立的步驟,只是使用自定義排序次序第二個,即

.Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _ 
     Key1:=.Range(.Cells(2, 4), .Cells(lastrow, lastCol)), Order1:=xlDescending, _ 
     MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes 

.Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _ 
     Key1:=.Range(.Cells(2, 3), .Cells(lastrow, lastCol)), Order1:=xlDescending, _ 
     OrderCustom:=n, _ 
     MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes 

.Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _ 
     Key1:=.Range(.Cells(2, 5), .Cells(lastrow, lastCol)), Order1:=xlAscending, _ 
     MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes 

請注意,我已經扭轉了這些種類在比較執行順序以及它們在原始聲明中的聲明。

+0

啊,歡呼聲。所以OrderCustom是每種。 – Echilon 2009-09-20 13:06:42