Consulting

Results 1 to 3 of 3

Thread: Solved: Excel Sorting Help

  1. #1

    Solved: Excel Sorting Help

    I'm trying to sort Excel data in a different sheet that's displayed. 'DISPLAY' is the sheet I want to view while the macro is running. 'DataBase' is the sheet that sorting should happen. Here is the macro I recorded....

    [VBA]
    Sheets("DataBase").Select
    Range("J3:S100").Select
    Selection.Sort Key1:=Range("N3"), Order1:=xlAscending, Key2:=Range("M3") _
    , Order2:=xlAscending, Key3:=Range("R3"), Order3:=xlDescending, Header _
    :=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom _
    , DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, DataOption3:= _
    xlSortNormal
    Sheets("DISPLAY").Select
    [/VBA]

    If I use this macro, the program quickly switches over to 'DataBase' and then back to 'DISPLAY'. So logically, I figured this code would work instead...

    [VBA]
    Sheets("DataBase").Range("J3:S100").Sort Key1:=Range("N3"), Order1:=xlAscending, Key2:=Range("M3") _
    , Order2:=xlAscending, Key3:=Range("R3"), Order3:=xlDescending, Header _
    :=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom _
    , DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, DataOption3:= _
    xlSortNormal
    [/VBA]

    However, it doesn't. I'm getting "RUN-TIME ERROR 1004. The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort by isn't the same, or blank"

    Why would one work, but not the other? Please help me figure out the proper code so I don't see 'DataBase' sheet flicker in and out.

    Thanks!
    Kaela

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Hi Kaela,
    You need to tie your Key ranges to the sheet
    [VBA]Sub Sorts()
    With Sheets("DataBase")
    .Range("J3:S100").Sort Key1:=.Range("N3"), Order1:=xlAscending, Key2:=.Range("M3") _
    , Order2:=xlAscending, Key3:=.Range("R3"), Order3:=xlDescending, Header _
    :=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
    End With
    End Sub

    [/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    Nicely done, thank you MD!!


Posting Permissions

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