Consulting

Results 1 to 3 of 3

Thread: Data sort a dynamic range?

  1. #1

    Data sort a dynamic range?

    I'm trying to write a macro which will data sort a dynamic range. The number of columns will always be the same (A:N) but the number of rows will change.

    So I want to start at row 4 and sort all data from here down, based on the contents of column N. I don't have any headers.

    Here is what I managed to record but I'm not sure how this should be changed to fit my range?

    Sub TestMacro()
    
    
        Rows("4:274").Select
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("N4:N274") _
            , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SetRange Range("A4:N274")
            .Header = xlGuess
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End Sub
    Many thanks in advance

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Sub TestMacro()
    Dim lastrow As Long
    
        With ActiveWorkbook.Worksheets("Sheet3")
        
        
            lastrow = .Cells(.Rows.Count, "N").End(xlUp).Row
            .Sort.SortFields.Clear
    
            .Sort.SortFields.Add Key:=.Range("N4").Resize(lastrow - 3), _
                                 SortOn:=xlSortOnValues, _
                                 Order:=xlAscending, _
                                 DataOption:=xlSortNormal
            .Sort.SetRange .Range("A4:N4").Resize(lastrow - 3)
            .Sort.Header = xlNo
            .Sort.MatchCase = False
            .Sort.Orientation = xlTopToBottom
            .Sort.SortMethod = xlPinYin
            .Sort.Apply
        End With
    End Sub
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  3. #3
    Perfect, thank you!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •