2017-08-11 2 views
1

Je suis un peu une recrue dans vba et je suis bloqué sur quelque chose qui devrait être relativement facile: J'ai un marco en spécifiant le numéro de colonne des noms d'en-têtes:VBA, codant une plage dynamique (colonne) pour le tri des données

Dim onomata As Integer 
'find column named Name of ship 
Set acell = rows(1).Find(What:="Name of ship", LookIn:=xlValues, _ 
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False) 

If Not acell Is Nothing Then 
    onomata = acell.Column 
End If 

maintenant, je veux trier mes données en fonction de cette colonne:

Cells.Select 
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear 
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range(*this is where I want to introduce the column*), _ 
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _ 
    xlSortTextAsNumbers 
With ActiveWorkbook.ActiveSheet.Sort 
    .SetRange Range("A1:AR100000") 
    .Header = xlYes 
    .MatchCase = False 
    .Orientation = xlTopToBottom 
    .SortMethod = xlPinYin 
    .Apply 
End With 

Cependant, ma variable est un entier alors que les demandes de commande d'une valeur de plage. Quelqu'un peut-il m'aider dans la façon de le coder?

Répondre

0

Déclarant ActiveSheet est suffisant, il n'y a pas de sens à l'utilisation ActiveWorkbook.ActiveSheet.

Utilisez le code ci-dessous pour trier les annonces en utilisant les chiffres qui vous intéressent onomata.

With ActiveSheet 
    .Sort.SortFields.Clear 
    .Sort.SortFields.Add Key:=Columns(onomata), SortOn:=xlSortOnValues, _ 
        Order:=xlAscending, DataOption:=xlSortTextAsNumbers 
End With 
+0

Merci beaucoup! Cela fonctionne parfaitement! –

+0

@ e-gnacio vous êtes les bienvenus –

+0

Et si je veux trier par plus de 1 critère? comme premier tri par colonne A puis par colonne B ??? –

0
ActiveSheet.Sort.SortFields.Add Key:= ActiveSheet.Cells(onomata).EntireColumn 
1

Vous avez seulement besoin de cette ...

Dim acell As Range 

'find column named Name of ship 
Set acell = Rows(1).Find(What:="Name of ship", LookIn:=xlValues, _ 
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False) 

If Not acell Is Nothing Then   
    ActiveSheet.Sort.SortFields.Clear 
    ActiveSheet.Range("A1").Sort key1:=acell.Offset(1, 0), order1:=xlAscending, Header:=xlYes 
End If 
+1

'ActiveWorkbook.ActiveSheet' ??? –

+0

@ShaiRado Oui, cela n'a aucun sens. Je ne l'ai pas regardé de près et j'ai copié le code d'OP. Lol Merci de l'avoir signalé. :) – sktneer