2009-09-20 10 views
3

J'utilise VBA pour trier les colonnes dans Excel 2003. Je dois trier par colonne 5 ascendant, puis la colonne 3 en utilisant un ordre personnalisé, puis par la colonne 4 ascendant. J'ai de la difficulté à faire fonctionner le tri et je ne comprends pas totalement comment OrderCustom s'applique.Tri multi-colonnes avec VBA

Tout pointeur dans la bonne direction serait apprécié :) Mon code est ci-dessous.

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 

Répondre

3

Essayez diviser votre tri en 3 étapes séparées, avec seulement le second en utilisant votre ordre de tri personnalisé, à savoir

.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 

Notez que j'ai inversé l'ordre dans lequel ces sortes sont effectuées par rapport avec comment ils sont déclarés dans la déclaration originale.

+0

Ah, bravo. Donc l'OrderCustom est par type. – Echilon