+ Reply to Thread
Results 1 to 7 of 7

Generic sort macro for varying lengths

Hybrid View

  1. #1
    Registered User
    Join Date
    10-10-2013
    Location
    California
    MS-Off Ver
    2010
    Posts
    21

    Generic sort macro for varying lengths

    Hello,

    I am fairly new when it comes to VBA/macros. I recorded a macro with me manually selecting rows 3:3000, then sorting alphabetically. Then I edited the code with what I picked up from the forums, trying to convert said macro into a generic sort macro that will work any active workbook, active worksheet. This macro would ignore rows 1&2 as these are header rows for my company.

    Here is what I have so far:
     Sub testsort2()
    '
    ' testsort2 Macro
    '
    
    '
    Dim LastRow As Long
        LastRow = ActiveSheet.UsedRange.Rows.Count
    
        Rows("3:LastRow").Select
        ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
        ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A3"), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.ActiveSheet.Sort
            .SetRange Range("A3:LastRow")
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End Sub
    When I run said macro, I get an error and debugger takes me to the line
     Rows("3:LastRow").Select
    Before I altered it it read Rows("3:3000").Select. Did I define LastRow properly? Do I need to change the format of the Rows function as it is now using a variable versus two integers? Getting ahead of myself, the code also used to read ActiveWorkbook.Sheet*name* something of that sort, and I changed it to Active.Sheet. Is that going to error out or did I convert it properly? I'm sure the code may be riddled with quite a few more bugs, as I did wing it and hope for the best...

    Thanks for taking the time to read my problem. I will appreciate any help that can come my way,

    -S

  2. #2
    Forum Expert Alf's Avatar
    Join Date
    03-13-2004
    Location
    Gothenburg/Mullsjoe, Sweden
    MS-Off Ver
    Excel 2019 and not sure I like it
    Posts
    4,784

    Re: Generic sort macro for varying lengths

    Be aware of a small problem that may pop up using

    LastRow = ActiveSheet.UsedRange.Rows.Count
    If your data starts at row 3 i.e. row 1 and 2 are empty and goes down to row 41 the above expression will define LastRow as 39 becuse this is the number of used rows.

    If you do whish to know the number of the last row i.e. 41 try something like this

    Sub NyTst()
    Dim r As Long
    
    With ActiveSheet.UsedRange
        r = .Rows(.Rows.Count).Row
    End With
    
    End Sub
    Don't know if you solved your problem as thread is marked "Solved" if not you could try

    Rows("3:" & LastRow).Select

    Alf

  3. #3
    Registered User
    Join Date
    10-10-2013
    Location
    California
    MS-Off Ver
    2010
    Posts
    21

    Re: Generic sort macro for varying lengths

    Hi again Alf,

    It was a weird bug, as I initially posted the forum as unsolved. I had to mark this "solved" post as solved, then unsolved again before it registered properly on the forums...

    Anyway, good catch, as I do want it to count possible blank rows preceding the last row. Implementing your suggestions in the code, I have:
    Sub testsort2()
    '
    ' testsort2 Macro
    '
    
    '
    Dim LastRow As Long
        With ActiveSheet.UsedRange
        LastRow = .Rows(.Rows.Count).Row
        End With
    
        Rows("3:" & LastRow).Select
        ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
        ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A3"), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.ActiveSheet.Sort
            .SetRange Range("A3:" & LastRow)
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End Sub
    Now when I run I get "Runtime error '1004': Method 'Range' of object '_Global' failed" and it takes me to line
    .SetRange Range("A3:" & LastRow)
    As I figured earlier, I must be using the variable LastRow improperly with Range. What would be the correct syntax for this line?

    Thank you,

    -S
    Last edited by s0o0y; 10-23-2013 at 04:06 PM.

  4. #4
    Forum Expert Alf's Avatar
    Join Date
    03-13-2004
    Location
    Gothenburg/Mullsjoe, Sweden
    MS-Off Ver
    Excel 2019 and not sure I like it
    Posts
    4,784

    Re: Generic sort macro for varying lengths

    You are setting a range so since "LastRow" is a number (for instance 47) "Range("A3:" & 47) does not make sense to "Excel"

    If on he other hand the expression was

    .Range("A3:A" & LastRow)
    this would correspond to a range "A3:A47" and now it makes sense to "Excel"

    Alf

  5. #5
    Registered User
    Join Date
    10-10-2013
    Location
    California
    MS-Off Ver
    2010
    Posts
    21

    Re: Generic sort macro for varying lengths

    That makes sense.

    I'm seeing now that my selection line must be redundant, as before the sorting is called in order it clears the sort fields and then defines it.. This is causing a problem as I noticed the sort is now working, but only sorting column A, without the other columns following the data in col A that they should correspond to.

    Again, this is me wigging it and missing a crucial element, but this is how I attempted to fix my range issue:

            .SetRange Range("A3:LastCol" & LastRow)
    where I defined LastCol earlier with:
    With ActiveSheet.UsedRange
    LastCol = .Columns(.Columns.Count).Column
    End With
    I figure this code would work as I intended if LastCol was a letter versus a number, but I know from my other posts that excel can recognize a column by a numerical representation as well. I tried using Cell(LastRow, LastCol) in the range field, but again I'm missing a factor. I know that is telling Excel to look at that Cell for a 'property,' but I'm not sure how to ask it look there for the cell "address" and return that to put in the second half of my range... Can you help clear this up for me?

    -S
    Last edited by s0o0y; 10-24-2013 at 04:51 PM. Reason: typos

  6. #6
    Forum Expert Alf's Avatar
    Join Date
    03-13-2004
    Location
    Gothenburg/Mullsjoe, Sweden
    MS-Off Ver
    Excel 2019 and not sure I like it
    Posts
    4,784

    Re: Generic sort macro for varying lengths

    As LastCol and LastRow both are numbers how about trying to use the cell properties?

    Range(Cells(3, 1), Cellls(LastRow, LastCol))
    where "Cells(3, 1)" is cell in row 3, column 1 i.e. A3.

    Since you also know the upper left corner of your data cell A3 and if you data is coherent you could test the "CurrentRegion" command to see if this could be used as well. Something like this perhaps. Don't forget to dim rng as range.

    Set rng = Range("A3").CurrentRegion
    Alf

  7. #7
    Registered User
    Join Date
    10-10-2013
    Location
    California
    MS-Off Ver
    2010
    Posts
    21

    Re: Generic sort macro for varying lengths

    Oh, I was using the CELL function as mentioned here, confusing myself, hah. I used your range example with Cells() function now as I already defined LastCol.

    The macro now works as intended. Here is the final code for anyone else who may want to reference the working generic sort macro:

    Sub GenericSort3ThruX()
    '
    ' GenericSort3ThruX Macro
    '
    
    '
    Dim LastRow As Long
        With ActiveSheet.UsedRange
        LastRow = .Rows(.Rows.Count).Row
        LastCol = .Columns(.Columns.Count).Column
        End With
        
        ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
        ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A3"), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.ActiveSheet.Sort
            .SetRange Range(Cells(3, 1), Cells(LastRow, LastCol))
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End Sub
    Again, this code ignores the first two rows, which I use as headers on my sheets. If you would want to use this code and start on a different row, you could simply change the range lines to where you please, those lines being
    ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A3"), _
    .SetRange Range(Cells(3, 1), Cells(LastRow, LastCol))
    Once again you walked me through one of my issues, Alf. Thank you for the help, I appreciate it =).

    -S
    Last edited by s0o0y; 10-24-2013 at 05:19 PM.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Concatenate with varying lengths and data
    By Unident in forum Excel Formulas & Functions
    Replies: 4
    Last Post: 05-21-2013, 04:39 PM
  2. Best way to store lists of varying lengths
    By jik_ff in forum Access Tables & Databases
    Replies: 5
    Last Post: 04-17-2013, 08:54 AM
  3. Combining Data of varying lengths
    By jaj8372 in forum Excel General
    Replies: 14
    Last Post: 06-08-2010, 03:47 PM
  4. Apply Macro to varying row lengths
    By izza56 in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 12-08-2006, 10:36 AM
  5. Generic Page Setup Macro applied to multiple workbooks with varying number of sheets
    By sowetoddid in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 04-22-2005, 11:45 AM

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1