Trier suivant une colonne nominative

Bonjour,

j'ai un fichier avec plusieurs colonnes comportant un titre:

10test-t.xlsm (17.22 Ko)

Je souhaite trier ce fichier suivant la colonne d'un certain titre.

Debutant, j'ai essaye de synthetiser ce que j'ai pu voir sur divers forum, mais au moment du tri j'ai une erreur, et je ne comprends pas pourquoi la variable rng ne convient pas dans le Range:

Sub toto1()
Dim ws As Worksheet
Dim titre As String
Dim r As Range, rng As Range
Dim lcol As Long

    Set ws = Worksheets("k1")

    titre = Application.InputBox("Entrer le nom de la colonne:", "", "ColB", Type:=2)

    With ws
       With .Cells
          Set r = .Find(what:=titre, LookIn:=xlValues, lookat:=xlWhole)
          If r Is Nothing Then Exit Sub
          lcol = r.Column
       End With
       Set rng = .Cells(2, lcol).Resize(.Cells(.Rows.Count, lcol).End(xlUp).Row - 1)
    End With

    ws.Sort.SortFields.Clear
'    ws.Sort.SortFields.Add Key:=Range("B5"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    ActiveWorkbook.Worksheets(ws).Sort.SortFields.Add Key:=Range(rng), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

End Sub

Merci pour votre aide, cordialement, Philippe.

Bonjour,

Un essai qui trie seulement la colonne indiquée ... pas la plage.

Sub toto1()
Dim ws As Worksheet
Dim titre As String
Dim r As Range, rng As Range
Dim lcol As Long

    Set ws = Worksheets("k1")
    titre = Application.InputBox("Entrer le nom de la colonne:", "", "ColB", Type:=2)

    With ws.Cells
          Set r = .Find(what:=titre, LookIn:=xlValues, lookat:=xlWhole)
          If r Is Nothing Then Exit Sub
          lcol = r.Column
    End With
    Set rng = ws.Cells(1, lcol).Resize(ws.Cells(Rows.Count, lcol).End(xlUp).Row)
    ws.Sort.SortFields.Clear
    ws.Sort.SortFields.Add Key:=rng, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("k1").Sort
        .SetRange rng
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

ric

Merci beaucoup pour cette reponse, je m'y penche demain a l'aube!

Si ca marche je clos le sujet.

Bon soiree, Philippe.

Cela marche parfaitement, merci beaucoup!

Rechercher des sujets similaires à "trier suivant colonne nominative"