ExcelRibbon.Tips.Net ExcelTips (Ribbon Interface)

Automatically Sorting as You Enter Information

Please Note: This article is written for users of the following Microsoft Excel versions: 2007 and 2010. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Automatically Sorting as You Enter Information.

Pat wonders if there is a way to automatically sort every time she adds new data to a worksheet. Pat thinks it would be great, for instance, that when she adds a new name to a list of names that the names are automatically sorted to always be in order.

The only way that this can be done is by using a macro that is triggered whenever something new is entered in the worksheet. You can, for instance, add a macro to the code for a worksheet that is triggered when something in the worksheet changes. (You can view the code window by right-clicking the worksheet tab and choosing View Code from the resulting Context menu.) The following is an example of one such simple macro:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    Range("A1").Sort Key1:=Range("A2"), _
      Order1:=xlAscending, Header:=xlYes, _
      OrderCustom:=1, MatchCase:=False, _
End Sub

The macro assumes that you want to sort on the data in column A and that there is a header in cell A1. If the names are in a different column, just change the cell A2 reference to a different column, such as B2, C2, etc.

Of course, sorting anytime that any change is made can be bothersome. You might want to limit when the sorting is done so that it only occurs when changes are made to a specific portion of your data. The following version of the macro sorts the data only when a change is made in column A.

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("A:A")) Is Nothing Then
        Range("A1").Sort Key1:=Range("A2"), _
          Order1:=xlAscending, Header:=xlYes, _
          OrderCustom:=1, MatchCase:=False, _
    End If
End Sub

There are some drawbacks to using a macro to automatically sort your data. First, since you are using a macro to sort, the operation is essentially "final." In other words, after the sorting you can't use Ctrl+Z to undo the operation.

A second drawback is that data entry might become a bit disconcerting. For instance, if you use any of the above macros and you start to put names into the worksheet, they will be sorted as soon as you finish what is in column A. If your data uses five columns and you start your entry in row 15, as soon as you get done entering the name into column A (and before you enter data into columns B through E), your data is sorted into the proper order. This means that you will need to find where it was moved in the sort, select the proper cell in column B, and then enter the rest of the data for the record. Of course, the way around this is to add your data in an unnatural order—simply make sure that the name in column A is the very last thing you enter for the record.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (9006) applies to Microsoft Excel 2007 and 2010. You can find a version of this tip for the older menu interface of Excel here: Automatically Sorting as You Enter Information.

Related Tips:

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!


Leave your own comment:

  Notify me about new comments ONLY FOR THIS TIP
Notify me about new comments ANYWHERE ON THIS SITE
Hide my email address
*What is 5+3 (To prevent automated submissions and spam.)
           Commenting Terms

Comments for this tip:

Willy Vanhaelen    06 Jul 2016, 13:46

This can only be realised if your data table is the entire columns F to W, has headers and columns E and X are entirely empty. Then this macro can do the job:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column <> 7 Or Target.Columns.Count > 1 Then Exit Sub
    Dim tmp As Variant
    tmp = Cells(Target.Row, 8).Formula 'save contents
    On Error GoTo Enable_Events
    Application.EnableEvents = False
    Cells(Target.Row, 8) = "#"
    Range("F1").Sort Order1:=xlAscending, Key1:=Range("F1"), Key2:=Range("G1"), Header:=xlYes
    Cells(Application.Match("#", Columns(8), 0), Selection.Column).Select
    Cells(Selection.Row, 8) = tmp 'restore contents
    Application.EnableEvents = True
End Sub

The macro has also the advantage that the cellpointer follows the record to it's new position after the sort.
Pramodkumar    06 Jul 2016, 03:13
I have datas in sheet1 ranging.F10:W28 The column(F10:F28) reffesrs to date and column(G10:28)for bill Numbers. Can I have a single vba to sort dates first and then the bill nos?
Ie.In case of same dates, sort data based on bill Nos
Thanks a a lot
Michelle    14 Jun 2016, 11:09
RE: Auto Sorting Linked Sheets:
Master data sheet (sht) has 7 other shts linked to it. Each sht displays that section's related data from the Master sht.

Need to auto sort only the linked shts by last name, then first name (which I thought should have been easy), but still need to keep all associated line data.
I have done conditional format for blank rows to be "zz" and used white font to hide. The data formulas linking to the master sht go to 301 lines, so potential of a lot of blank lines in-between rows of data. I have worked out all my formulas and links to each sections' sht, but having issue getting the auto sort working and what mechanism to use to trigger auto sort within the linked sheets (not using name since it is first data cells keyed, would like to use Section ID). I have been reading your message board, which has a wealth of information, but I have not been successful in getting auto sort working.
**Using Excel 2013 version.
Master Sht: only 7 key-able fields (columns), rest are all formulas (13 columns).
Linked Sht: only 13 columns of data displayed/linked from Master Sht.
(Project: Employee Yrs of Service Awards/Recognition. Spreadsheet for determining when employee is eligible for Yrs of Svc award broken down by each section.)
Your assistance and patience is very much appreciated. TY.. M
Mark Watson    22 May 2016, 09:38
I am new at code and need help on automatically sorting from [row 20 down to row 590, columns A:L] by dates (older to newer) that i enter in column A20:A590 after entering whatever data i choose to enter in that row.
Note: rows 1 through 20 must remain unaltered.
Can someone please help me.
Kashish Shah    30 Apr 2016, 02:53
You are God. Thank you so much for helping.
nnd    03 Apr 2016, 07:04
i have spreadsheet which contain type of product for which different cost is to be mentioned i have prepared to columns with product and cost now i want to pick up the cost for product when i enter the product name
Graham    02 Mar 2016, 10:29
I see two approaches described here.
1. Use VBA with an appropriate event-driven trigger. Fine. Not for those that don't enjoy VBA.
2. Use the function Large(). Also fine, but it only works if the data is only a single field.

There is another way using
Rank() (applied to the input data)
Match() (just once, looking for the nth rank)
Index() (once for each desired field from the database)

This works fast, is efficient, works for any number of fields with the data in columns or rows.

Easy enough. Details left to the reader.
Willy Vanhaelen    21 Aug 2015, 12:40

With some adjustments, the macro I posted 17 November 2013 will do the job:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column <> 2 Or Target.Columns.Count > 1 Then Exit Sub
    Dim tmp As Variant
    tmp = Cells(Target.Row, 1).Formula 'save contents
    On Error GoTo Enable_Events
    Application.EnableEvents = False
    Cells(Target.Row, 1) = "#"
    Range("A5").Sort Key1:=Range("B5"), Order1:=xlAscending, Header:=xlNo
    Cells(Application.Match("#", Columns(1), 0), 2).Select
    Cells(Selection.Row, 1) = tmp 'restore contents
    Application.EnableEvents = True
End Sub

For the macro to work correctly cells A4, B4 and column C must be blank.

The macro has also the advantage that the cellpointer follows the record to it's new position after the sort.
Katie    19 Aug 2015, 08:03

I need someone to write out the code for me please! basically for colum B from 5 so (B5) to around B50 I want that colum to be decending so the oldest date first (the dates are people birthdays and I need the oldest person at the top) and also there names before them in colum A from A5 to move with them. And this sheet to automatically move them when a new name and d.o.b is added!
Please could someone help ive tried changing other peoples posted codes and I just cant get it to work :/ thanks in advanced!
Amber    30 Jul 2015, 11:18
I would like to automatically sort by date in column G and the information next to it on both sides to stay with it. I would also only like to sort a portion. For instance I would like to sort G2-G54 by date and then be able to sort G56-G87 the same way. I do not want to lose the data to the left and right of column G. I want it to move with column G based on the sort location.
Ryan Margerison    31 May 2015, 12:35
Hello there I have an excel workbook which is a football league table system, I want it so that every new result input auto sorts the new league table based on the results and the league table has combined if statements to count the wins and I have formulas for calculating points etc. I just need to sort it out so that the table auto sorts in one sheet based on new results in the other? Can anybody help me with this?
Dani    04 May 2015, 23:38
Hi i just started using macro and i'm hoping to sort my data by color this is the command i'm using but it doesn't seen to be working can somebody guide me as to what i'm doing wrong

Private Sub Worksheet_Change(ByVal Target As Range)

    ActiveWorkbook.Worksheets("Plans").Sort.SortFields.Add(Range("M3:M1125"), _
    xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(253, _
        233, 21)
    ActiveWorkbook.Worksheets("Plans").Sort.SortFields.Add(Range("M3:M1125"), _
    xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(242, _
        220, 219)
    ActiveWorkbook.Worksheets("Plans").Sort.SortFields.Add(Range("M3:M1125"), _
    xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(228, _
        223, 236)
    ActiveWorkbook.Worksheets("Plans").Sort.SortFields.Add(Range("M3:M1125"), _
    xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(197, _
        217, 241)
    ActiveWorkbook.Worksheets("Plans").Sort.SortFields.Add(Range("M3:M1125"), _
    xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(217, _
        217, 217)
    With ActiveWorkbook.Worksheets("Plans").Sort
        .SetRange Range("M3:M1125")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
    End With

End Sub
Yaw Asante    26 Apr 2015, 11:40
please show me how I can enter sudent ID number in a cell and return the nane that bears the name of the ID to bring student exams record from a stdent sammary exam record. thank.
Babulal Gandhi    31 Mar 2015, 03:14
Hi Friends

I Have Phone Numbers Like This To Sort By Rows

66-66970877, 22-34567, 8764576890, 333-7465 (Column A1,Column B1,Column C1,Column D1)

These Are Phone Numbers Which I Have To Short For Small To Large Or Large To Small

Sorting Data In Row P1 To S1
22-34567, 333-7465, 66-66970877, 8764576890 (Column P1,Column Q1,Column R1,Column S1)

Column P1 = small($a1:$d1,1)
Column Q1 = small($a1:$d1,2)
Column R1 = small($a1:$d1,3)
Column S1 = small($a1:$d1,4)

These Formula Works Great On Without (-) Numbers.

I Need Formula To Ignore (-)

Numbers Before (-) Is Area Codes. If I Remove (-) With Find & Replace. I Will Get Confuse In Future As I Can't Differentiate Area Code And Phone Number.

If There Is Solution In Macro

I Want To Short Telephone Numbers In Three Rows After Mobile Numbers In Other Three Rows.

P1-Telephone Number, Q1-Telephone Number, R1-Telephone Number, S1-Mobile Number, T1-Mobile Number, U1-Mobile Number

I Need A Macro
1. Ignores The (-) Value In All Phone Numbers
2. Check First Digit Of Phone Numbers.
3. If First Digit Start's With Nine(9). If There Is Any Single Phone Number In A1, B1, C1, D1 Starting With Nine(9)(It's Mobile Number) Put Into S1. Else If There's Two Numbers Starting With Nine (9) Place It In Row S1 And T1 In Ascending Or Descending Order
4. If First Digit Start's With Eight (8). If There Is Any Single Phone Number In A1, B1, C1, D1 Starting With Eight (8) Put Into Q1. Else If There's Two Numbers Starting With Eight (8) Place It In Row Q1 And R1 In Ascending Or Descending Order

Like Wise For Other Digits Too

Thanks & Regards
Babulal Gandhi

Kenneth    05 Mar 2015, 19:03
#1 Salads 1234
Barrens, Alicia 2222
jackson, Peewee 1515
Johnson, Aaron 4242
Pooty, Tang 3456
Shields, Derick 7689
Shields, Ruby 9870
Spencer, Kenneth 9999
Zebra 6767
Obama, Barack 1111
Andersson, Paul 1236

This is sample data. I want to be able to automatically resort the data alpabetcally when new data is added. If I add a new Name and ID I want to resort automatically. There is no column heading and I AM A NOVICE, a complete NOVICE to VisualBasic. Can someone help me pleaseeeee??? Thanks in advance, Ken
OptimusPrime    01 Mar 2015, 07:36

If you want the values of result in column C of Step 7 to be sorted
do the following:

Step 8: Write S.NO. in cell E1
Step 9: Write numbers from 1 to 9 in cell E2 to E10
Step 10: Write SORTED NON-DUPLICATES in cell F1
Step 11: Write =IFERROR(LARGE($C$2:$C$9,E2),"") in cell F2 and drag it to F9

observe values in Column F
OptimusPrime    01 Mar 2015, 07:19

Follow the instructions :

Step1: Write HELPER in cell A1
Step2: Write 1 in cell A2
Step3: Write VALUES in cell B1
Step4: Write all desired values including duplicate values in cells from B2 to B10
Step5: Write NON-DUPLICATES in cell C1
Step6: Write =IF(COUNTIF($B$2:B3,B3)=1,A2+1,A2) in cell A3 and drag it till A10
Step7: Write =IFERROR(VLOOKUP(ROW()-1,$A$2:$B$12,2,FALSE),"") in cell C2 and drag it till C10

Observe values in Column C

revert back if any problem exists.
Miro    28 Feb 2015, 07:41
@ Willy Vanhaelen

I dont think this is what i wanted. I want actual data to be sorted out and non duplicates to be listed in that other sheet. As bellow example :
1 348 27.80 351
2 348 27.80 351
3 351 27.80 348
4 351 27.80 342
5 351 27.80 342
6 348 27.80 342

Values in column A and C are repeating them self's , i need formula to get each of ( unique ) value in some third column ( or sheet ) so result should be :


We manage to solve this with below formula , another problem a rise i cannot adjust formula to take both columns ( A & D ) when checking , only works when one column is in question .

Thank you everyone for help.
=IFERROR(INDEX(N$4:N$136,MATCH(0,INDEX(COUNTIF($B$3:$B5,$N$4:$N$136), 0))),"")
Willy Vanhaelen    27 Feb 2015, 06:15
@Rhys W
- Select the cell you want to delete and press [Ctrl]+[-] (minus key).
- In the Delete dialog that pops up, check 'Shift cell up' and click [OK].

- Copy your data in column A to column D.
- With you data still highlighted in column D click 'Remove Duplicates' in the 'Data Tools' section in the Data tab of the ribbon and click OK.
Miro    26 Feb 2015, 10:20
I need help with this one. I have one column lets say A1 : A38 that have some values / text . Those values can repeat themselves through A1 : A38 many times . I would like to get in another row or even sheet only one of each of those values or records.
For Example : A1 have TB231 ; A2 TB236 ; A3 TB555 ; A4 TB555 ; A5 TB231 etc , now in separate sheet or row i should get only one of those , it dosent matter how much it has same records i just need that i get value of all different in separate sheet or row.
Results of example should be : D1 TB231 ; D2 TB236 ; D3 TB555 , i tried with IF function but for 38 or more rows would be huge so maybe there is other easier way.
Rhys W    26 Feb 2015, 09:57
I'm using this code to automatically sort two columns in a-z order as I enter new Names, however, how do I make it so that when I delete a Name, the rest of the data under it moves up and takes its place?
Willy Vanhaelen    24 Feb 2015, 14:13
@Celia F.

Well simply write what you want to do:

The basic command is: Range("A1").Sort
Then you have to add a key to sort by: Key1:=Range("C1")
Now add the sort order: Order1:=xlAscending
Tell Excel if there is a header: Header:=xlYes
If you want a second key to sort by: Key2:=Range("A1")
If you want a different sort order for this one, simply add it: Order2:=xlDescending

Now bring this all together separated by comma's (no comma after Sort):

Range("A1").Sort Key1:=Range("C1"), Order1:=xlAscending, Header:=xlYes, Key2:=Range("A1)

That's it.
Celia F.    23 Feb 2015, 14:30
How do I do a macro for auto sort for multiple columns? I want it to sort column C then column A.

Chris    14 Feb 2015, 12:59

Thanks! I had to do some playing around with the ranges since I have a lot of data spread throughout the page, but it worked perfectly. Thanks again!
Willy Vanhaelen    14 Feb 2015, 06:00
@ Chris

Try this:

Range("A:B").Sort Key1:=Range("B1"), Order1:=xlAscending, Header:=xlYes
Pascal    14 Feb 2015, 05:23
Hi guys I want to create a contact list.
First Column will be Company/Organisation Name, the second column will be Department and the third column will be the Name. The rest columns will be theirs telephone numbers, fax numbers, emails addresses etc.

I just want the first 3 columns to be connected together in alphabetical order.

I tried with the Data and Sorting but nothing!!!!
Chris    13 Feb 2015, 13:53
This works great for what I'm trying to do except for one little issue. Say I have a 3 column worksheet but I only want the first 2 columns sorted by the data in column B, and want column C to remain constant? I'm new to using macros so be gentle. Thanks
OptimusPrime    13 Feb 2015, 11:54
Hi Sireen,

If you have MSoffice 2007 or 2010, then check this out:
Home \ Styles \ Conditional Formatting \ New Rules

Hope you may find a solution for yourself.
By the way, how the data is automatically changing in cell, are you taking from outside Excel or from other excel sheet ?

Sireen    12 Feb 2015, 05:57
I need for excel to automatic change the data in one column to different wording into another column.. as the first one is generated form a software that we use, but the analysis should be stated in different wording .. like the key to a map .. every green colour represent forest !!

Is it possible ?

OptimusPrime    02 Feb 2015, 23:25
Hi Tushar,

Check this out. You may find a solution for your query.


OptimusPrime    02 Feb 2015, 23:21
Sorry Guys, there was a mistake in my previous post.
The correct one is as follows:

Step1: Enter serial no 1 to 10 in cells A1 to A10 (S.No.).
Step2: Enter any values in cells B1 to B10 (Item Qty.).
Step3: Enter any object names in cells C1 to C10 (Item Name).
Step4: Enter formula =RANK(B1,B$1:B$10)+COUNTIF(B$1:B1,"="&B1)-1 in cell D1. Drag till D10. (Item position)
Step5: Enter formula =C1 in E1 and drag till E10. (Item Name as is)
Step6: Enter formula =LARGE($B$1:$B$10,A1) in F1 and drag till F10. (Desired Item qty. in order)
Step7: Enter formula =IFERROR(VLOOKUP(A1,D$1:E$10,2,FALSE), VLOOKUP(A1,D$1:E$10,2,TRUE)) in cell G1 and drag till G10. (Desired Item Name in order).

Watch carefully, Your Desired Item qty. and item name would be in Cell F1 to G10.
Tushar    31 Jan 2015, 00:42
Hi,I have to maintain student weekly attendance form.
My excel sheet having 6 sheet name
from mon to fri i have students name with enrollment no, and attendance.
in final sheet i have student list who havent appear three consecutive days

0 means present
1 means Absent in final sheet column m

i want only those students enrollment no , name in new sheet who having value 1 in final sheet column m please help
OptimusPrime    27 Jan 2015, 17:51
Check this out for a better solution and Do as i write:

Step1: Enter serial no 1 to 10 in cells A1 to A10 (S.No.).
Step2: Enter any values in cells B1 to B10 (Item Qty.).
Step3: Enter any object names in cells C1 to C10 (Item Name).
Step4: Enter formula =RANK(B4,B$4:B$16)+COUNTIF(B$4:B4,"="&B4)-1 in cell D1. Drag till D10. (Item position)
Step5: Enter formula =C4 in E1 and drag till E10. (Item Name as is)
Step6: Enter formula =LARGE($B$4:$B$16,A4) in F1 and drag till F10. (Desired Item qty. in order)
Step7: Enter formula =IFERROR(VLOOKUP(A4,D$4:E$16,2,FALSE), VLOOKUP(A4,D$4:E$16,2,TRUE)) in cell G1 and drag till G10. (Desired Item Name in order).

Watch carefully, Your Desired Item qty. and item name would be in Cell F1 to G10.

If still got problem, download the excel sheet, its protected and the password is password. change value in current cell and press Enter. Watch the last two columns.


Still in problems ? let me know.
Chris    21 Jan 2015, 09:27
Hi, I'm trying to automatically resort a constantly changing block of data (A80:P179) by the J column, descending by value. My data does not have headers.

Could you please help me out with this and show me where I would adjust the ranges for different data?

Thanks you in advance,
Brenda     15 Jan 2015, 12:06
Is there anyway I can alphabetize a list of names automatically and also transfer their specific information at the same time with one formula.
Brenda     15 Jan 2015, 12:04
Is there any way I can add new names to be sorted in alphabetical order and still have their pertinent data changed automaticall along with them when I add a new person to the list? I am very new at this process
Glenn Case    09 Jan 2015, 09:47

You can either record a macro of the sort you want, or use the examples in the tip and comments in order to produce a macro which does the basic sort. This macro would be located in a code Module. You can then use an event macro as per the tip to test whether a change to the worksheet was in the range of interest (hours), and if so, call the first macro.
Mickale    08 Jan 2015, 13:32
I am new to macro codes and I really need some help! I am trying to write a code for my worksheet that will automatically sort "total hours" from least to greatest. My first column has names and then I have their total number of hours worked in the next column. I have headers in the worksheet and it needs to change everytime the hours worked is changed.
Any help would be greatly appreciated! Thanks
Barry    24 Dec 2014, 05:21
@Julie Meng

I would use a Case select to filter out the worksheets either that I want the sorting to occur on or as an exclusion list depending if you'll be adding extra sheets to the workbook that either need to be auto-sorted or not. The code below works on an exclusion list

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
 On Error Resume Next
    Select Case Activesheet.Name
       Case "List", "Main", "X", "Y", "Z"
           If Not Intersect(Target, Range("H:H")) Is Nothing Then
              Range("B12").Sort Key1:=Range("B13"), _
              Order1:=xlDescending, Header:=xlYes, _
              OrderCustom:=1, MatchCase:=False, _
           End If
   End Select
End Sub
Julie Meng    23 Dec 2014, 15:41
Hello Everyone,

I am using this for my entire workbook. I would like to keep this from running in my first 5 worksheets. This is what I am running right now:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

 On Error Resume Next
    If Not Intersect(Target, Range("H:H")) Is Nothing Then
              Range("B12").Sort Key1:=Range("B13"), _
              Order1:=xlDescending, Header:=xlYes, _
              OrderCustom:=1, MatchCase:=False, _
     End If
End Sub

I am Auto sorting column B when a change is made to column H.

Please let me know how I can keep it from running on my worksheets named List, Main, X, Y and Z.

I have several worksheets and need this auto sorting for all of my sheets but the first five. There is no way in hell i'm setting this up in each individual sheet, way to much work.

Thanks for this Allan, it is making my work so much easier!

Hope I can get this figured out before I pull all my hair out!
Amanda    03 Dec 2014, 19:03
Hi there. I am creating a spreadsheet that pulls data from several other worksheets. I am trying to get it to sort automatically by data in column L rows 4-18, header is in row 3. I have tried several different macros, but it keeps disconnecting my data from the rest of the columns. all data that needs to be sorted is in A3:AB18. Help!
Bigger Don    05 Nov 2014, 09:22
@ Bill

Check the code below. Here are the assumptions
  - you will be entering date in only B & C.
  - you will enter B then C.

If you expect to sort after entering in a specific column and you are entering more than just B & C (e.g. you are entering in A, B, C, D, and E) and you want to sort after entering in E, then change the Intersect to look in column E.

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("C:C")) Is Nothing Then
        With ActiveSheet.Sort
            .SortFields.Add Key:=Range("B:B"), SortOn:=xlSortOnValues, Order:=xlAscending, _
            .SortFields.Add Key:=Range("C:C"), SortOn:=xlSortOnValues, Order:=xlAscending, _
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .SetRange Range("B2:C" & CStr(ActiveSheet.Rows.Count))
        End With
    End If
End Sub

For a more complex problem, say you want to sort after A through E on a row are complete then you would wrap an If statement around the With'''end With. The "If", in this case is whether all input is complete for the row. Below is the code for this...
Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next

    If Not Intersect(Target, Range("A:E")) Is Nothing Then
        If RangeInputComplete(Range("A" & Target.Row & ":E" & Target.Row)) Then
            With ActiveSheet.Sort
                .SortFields.Add Key:=Range("B:B"), SortOn:=xlSortOnValues, Order:=xlAscending, _
                .SortFields.Add Key:=Range("C:C"), SortOn:=xlSortOnValues, Order:=xlAscending, _
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .SetRange Range("A2:E" & CStr(ActiveSheet.Rows.Count))
            End With
        End If
    End If
End Sub

Public Function RangeInputComplete(rng As Range)
    Dim cel As Range
    RangeInputComplete = True
    For Each cel In rng.Cells
        If Len(cel.Value) = 0 Then
            RangeInputComplete = False
            Exit For
        End If
    Next cel
End Function
Bill    04 Nov 2014, 17:12
The original macro works great, but I want to now sort by 2 columns, "b" then "C". What do I add to the macro to accomplish this?
Bigger Don    28 Oct 2014, 15:37
@ Samuel

First, this is probably something that would best be covered by sending an email to Allen's Help Wanted email . It's listed at the bottom of every week's Tips newsletter. If you aren't already a subscriber, I strongly suggest you do. It's part of my on-going education and he doesn't pass on your information to others who are going to send you a bunch of junk mail.

The advantage of submitting that way would be several people will provide their methods for solving each problem and you are more likely to get an answer that fits your needs. The URL is http://excelribbon.tips.net/contact.html?awt_l=EQOC_&awt_m=JcuXuyTnu4R74X

OK...all of that aside I am going to give two approaches you might use. I am starting with the assumption that your Master List has each student by name plus their cumulative score. For the sake of this I will also assume those are columns A and B, respectively, and the names are sorted in alphabetical order.

One approach would be to sort A:B by B, descending then populating another column (let's say it's column C) with the ranking.

Assuming you start in row 2, then the formula for C2 would be (without the quotes) "=If(B1=B2, C1,Row()-1)"
The B1=B2 test's for ties and both would get the same ranking. Otherwise their ranking would be the Row number with an adjustment for the row where the data starts.

Once done, copy-pastespecial/values then you can re-sort on the names.

The second approach would be to read the the data into an array with a two-field data type: Name & Grade. DIM arr(1 - NumberOfStudents).

Load the data from Master into the array, then sort the array on Grade, descending.

When reading from the array, for each entry into the array FIND the ROW with the name and plug the current i of the array. Roughly, the code looks like this.

For i = Lbound(arr) to Ubound(arr)
   RowNum = Application.WorksheetFunction...Row
   ws.cells(RowNum,RankingColNum) = i
Next i

The last thing that I can think of that you might want to do is put the class ranking back on the report card sheets. Assuming you have the student's name on that sheet the a vlookup(StudentName, Master!A:C, 3, False) will return the Class Ranking.

Like I said, if you would like the input of several people, send the message to Allen. Hope this helps.
samuel paul chinonso.    27 Oct 2014, 07:04
please I need help. I have just developed a VBA app. in excel that automatically process report card for a class in a school. now I want to be a bale to assign class position to each pupil in class automatically. each pupils result is on a different sheet. I have a master sheet that collects the total scored for each pupil.
Michele    09 Sep 2014, 03:19

I would really appreciate it if someone could help me with my query.

I have a table with data inserted through Vlookup formula. I want a specific column (C) to be automatically sorted in descending order depending on its value. Can you please help me with the VBA formula I need to input? I have attached the table below FYI.

The data including the heading runs from B9 to K24.

Basically I want to sort the table depending on the values of C10 to C24 in a descending order.

Component Ingredients Product Code Weight Kg/L % Allergen, if present
Roast beef 35 0.100 28.33% nil 0 0 0 0 0
Rock melon #N/A 0.070 19.83% #N/A #N/A #N/A #N/A #N/A #N/A
Whole grain mustard #N/A 0.040 11.33% #N/A #N/A #N/A #N/A #N/A #N/A
Melon #N/A 0.070 19.83% #N/A #N/A #N/A #N/A #N/A #N/A
Tomato Wedge #N/A 0.026 7.37% #N/A #N/A #N/A #N/A #N/A #N/A
Parmesan #N/A 0.020 5.67% #N/A #N/A #N/A #N/A #N/A #N/A
Pesto 5 0.010 2.83% nil 0 0 0 0 0
Diced tomato #N/A 0.005 1.42% #N/A #N/A #N/A #N/A #N/A #N/A
Arugula #N/A 0.005 1.42%
Sundried tomato #N/A 0.004 1.13%
Lolorosso #N/A 0.002 0.57%
Kalamata olive #N/A 0.001 0.28%
Chive #N/A 0.001 0.28%
Wheat bread 400206 1 slice #VALUE!
0 #N/A 0.000 0.00%
Lost Boy     21 Aug 2014, 17:03

I want this but for rows. I need a code that will auto sort my row of totals (which are the end of a chain of formulas – the total cells themselves included)so that cell B12 is always the highest number and cell O12 is always the lowest number. While keeping the data in the columns above in tact with the number in row 12 as they are the data that sums to the totals in that row. My totals sheet uses column A for date ranges (starting at A3 and going to A12) and columns B through O are states (all on row 2). There are sheets for each state that connects to the totals page and provides the data for all the cells. How can I make it auto sort so the state with the highest number (which is the sum of - for example B3-B11)is always on the left and the lost number always on the right? Let me know if you need any more information. Thank you.
Colin    07 Aug 2014, 04:49
Is there anyway of automatically updating without the need to input anything. I have a table that receives updates automatically from a server, but I need it to auto sort every 2 seconds.

Thanks in advance
Salik Khatri    30 Jul 2014, 07:11

Your thread is really helpful, exactly what im looking for!!! However im kinda new to this deep dark world of excel (ofcourse, i know the basics) bur recently my company has had an increased level of activity which has left me no choice but to explore new techniques to sort out data efficiently and on hand at all times.

The idea is simple, i've made a list of invoices which need to be paid. Colums include supplier, description, amounts in AED & USD, date, due date etc..the usual sutff. I calculate the number of days due by subtracting the due date with today's date [i use =today ()] to do this. Now that i have the number of days, i want to sort the entire row in an ascending order (i.e. overdue or past due - reflected as a negative figure).

The colums start with A: Suppliers and run through to I: Due in(Days)

Many thanks!
Salik Khatri
Rocky    18 Jul 2014, 15:35

I have two questions:

1. If i have values in rows 1-9 and Im typing in a value in row 20. As it is today row number 20 wont count until row 1-19 are complete. What do I need to do to get every row in colum A count all the time?

2.If I have ex row number 5 as a parent and row number 6 is a child by using this group function. As Im entering a value for parent I want the child to move around with parent. Is this posible to do?
DRB    18 Jun 2014, 15:21
I like it, but with both excel and world cup fever, I have a harder issue.

I have a list of games/times/teams and scores (and calculate points and goal difference). Below that I have equations that sum the points and goal differences for each world cup group. I want to sort these cells that contain equations every time I enter a score above (so I know the top two teams in each group). Is there any way to sort those?

minhruj    07 Jun 2014, 23:11
Anyone help me in this issue, please?
Within one sheet I have 8 databases (all no heading), which can be listed as K8:Q11, K12:Q15,... What I need is an automatic procedure to sort these databases' rows separately . The procedure must comply with 2 levels: First, sort by column Q, order largest to smallest, then sort by column P with the same order (data in these 2 columns are all numeric format.
Thanks so much!
rashmi    28 May 2014, 03:19
i want to add a fixed date, say 30-apr-2014 everytime I run my macro how do i do this? please could you help
jonathan    20 May 2014, 05:12
is it possible to please send me a template which i can use
nitin    29 Mar 2014, 11:39
Got the solution.
But 2 queries:
1. What does Key1:=Range("A2") refer to?
2. The regional settings on my laptop are Indian but the date format (which was earlier accepting indian format of input viz. dd-mmm-yyyy) is now accepting only american format - ie: mm-dd-yyyy but is displaying in dd-mmm-yyyy format.
eg.: if i enter "2-1" the date automatically converts to "01-feb-2014"
& if i enter "23-5" it converts to "23-05-2014" but if i enter "5-23" it converts to "23-Jan-2023"

Can you please guide to resolve this?
BTW, I forgot to mention that the sorting is done on the date column
the macro i use is:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("d17:d1000")) Is Nothing Then
        Range("d17:i1000").Sort Key1:=Range("d1"), _
          Order1:=xlAscending, Header:=x1Yes, _
          OrderCustom:=1, MatchCase:=False, _
    End If
End Sub

NITIN    29 Mar 2014, 03:27
Hi! I tried it & is working but i have a query:

if i have the data header in D5
I enter anything in D6 to D100, then the range D6 to I100 should be sorted on D
the columns J onwards should not change as they contain formulae.
Steph    06 Mar 2014, 12:02

Nevermind. Thanks for your help. I ended up getting it to work with this:

Public RowNo As Long

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error Resume Next
    If Target.Row <> RowNo Then
        RowNo = Target.Row
        Range("B1").Sort Key1:=Range("B2"), _
          Order1:=xlDescending, Header:=xlYes, _
          OrderCustom:=1, MatchCase:=False, _
    End If
End Sub

Steph    06 Mar 2014, 09:30
This is what i have in there:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    Range("B1").Sort Key1:=Range("B2"), _
      Order1:=xlDescending, Header:=xlYes, _
      OrderCustom:=1, MatchCase:=False, _
End Sub

Barry Fitzpatrick    05 Mar 2014, 05:31

It looks as though the macro is not being triggered by the change you are making, or if triggered the second parameter for the "Intersect" test is causing the macro to exit before sorting.

I'm not sure which macro you are using could you paste it into a comment?
Steph    04 Mar 2014, 08:03
I have a spreadsheet (excel 2010) where the sheet I want to auto sort largest to smallest (numbers) from the data in column B. I put in this code and it works when I add a new piece of data but it wont work when the data already there changes. All the data in the cells in question are copied from another cell on another sheet (It is where all the extrapolated data from all the individual sheets goes) is there a way to get around this? It works when I manually sort the data and when I add just a plain number to the bottom but for some reason wont work when the data in the cell changes. Thanks
Barry Fitzpatrick    03 Mar 2014, 05:17

The first macro should be triggered on a change in the selection.

If you take the second macro if entry of the first name to completed by pressing 'Enter' AND "Enter" is set to move to the cells below (default) then then yes I agree this triggers sorting (as designed) if however the user uses TAB or the mouse to click to the cell to the right then sorting will not be triggered. Sorting is only triggered when the row in which the active cell is located is changed.
It is common data entry practice to TAB between field entries and use Enter to complete the record entry.

To be honest my preferred solution would be to use a Userform, and apply some validation before adding the entry to the main table and subsequently sorting the table. The validation would check for all mandatory fields to be completed, check for illegal characters, etc etc.
Willy Vanhaelen    02 Mar 2014, 11:45
When you make an entry in column A, the proposed macros in this tip do sort the table and your entry seems to disappear which can be very disconcerting. Neither of your two proposed solutions solves this.

The macro I proposed here on 17 November copes with it. When you enter a name in column A it immediately gets sorted but the cursor jumps to the new position and you can instantly continue entering data in the same row.

Barry Fitzpatrick    01 Mar 2014, 11:06
Another way is to execute the sorting when the last column has data entered into it.

So say if the last column was J then the macro would become:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("J:J")) Is Nothing Then
        Range("A1").Sort Key1:=Range("A2"), _
          Order1:=xlAscending, Header:=xlYes, _
          OrderCustom:=1, MatchCase:=False, _
    End If
End Sub

This presupposes that data is entered into this column if it is an optional field then the data will not change and the macro sorting the data will not be triggered to run.

Another way would be to sort only if the row value changed:

Public RowNo as Long

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error Resume Next
    If Target.Row <> RowNo Then
        RowNo = Target.Row
        Range("A1").Sort Key1:=Range("A2"), _
          Order1:=xlAscending, Header:=xlYes, _
          OrderCustom:=1, MatchCase:=False, _
    End If
End Sub
Willy Vanhaelen    28 Feb 2014, 13:50
That's right, the Excel build in Data Form doesn't support the change event. But this isn't a surprise since it is a remnant of older versions and excel keeps it only for backward compatibility.
Mar33    26 Feb 2014, 09:43
Hi, I tried the macro and it works great. The only problem I am having is that when I put the data into excels built-in form box and hit enter it does not reconize this as a change event even though the cell does have the new data in it. Any way to have it work while using forms instead of putting the data directly into the cell.

Willy Vanhaelen    19 Feb 2014, 10:51
In fact your macro works too perfect. Whenever you enter anything anywhere in your entire worksheet, this macro is fired and your range "B2" gets sorted. The code of your macro is OK but you must change its name: i.e. Sub SortB() and assign it a shortcut key (End is not allowed in Excel, you can only use Ctrl+letter or Ctrl+Shift+letter) or you can create a button in the QAT of it.
michael    18 Feb 2014, 07:00
Hi there i tried the following macro which works just perfect:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    Range("B1").Sort Key1:=Range("B2"), _
      Order1:=xlDescending, Header:=xlYes, _
      OrderCustom:=1, MatchCase:=False, _
End Sub

But could i make it work after i press a specific button? for example i start entering my data and when i am finished to press "End" button to activate the sorting?
thank you
eric    02 Dec 2013, 15:44
Yes. Everything came back to normal. Your assumption was totally correct.

I think everybody should pay attention to this tiny macro which can save you from immense frustration.

All respects, Willy, for your excellent Excel knowledge. This site is the best out of many other very good Excel sites.

Thank you for sharing with us your expertise!
Willy Vanhaelen    02 Dec 2013, 10:59
Eric, it seems to me that for some reason in your laptop the EnableEvents is perhaps set to False by an add-in or some workbook that is loaded on startup.

This macro should fix it for the current session:

    Sub EventsEnable()
        Application.EnableEvents = True
    End Sub

If it does, my assumption is correct and you'll have to find the offender.

eric    01 Dec 2013, 13:00
Additional info: After one laptop restart the code works in newly created files, but if I paste it in existing ones, doesn't.
eric    30 Nov 2013, 16:44
I tried to apply your macro and there is something which drives me crazy.

On desktop it worked. On laptop doesn't work.

Even I use the same file transferred between pc's I got the same behavior.

I use on both machines the same version of Excel (2007), same antivirus.

Moreover, I created in the same file other simple macros on laptop. They work. Other files with rich VBA code, created on desktop and transferred on laptop, they work.

Seems to be a tiny setting forgotten somewhere, but what?

For two days I try restlessly to identify the problem. Can you give me an idea what i'm missing?

Thank you.
cameron    29 Nov 2013, 21:42
Never mind. It wasn't too hard to figure out.
cameron    29 Nov 2013, 20:43
Thanks for the post Willy. What do I need to change in order to be able to do the sorting on Column "C"?
Willy Vanhaelen    17 Nov 2013, 09:31
I use this sorting technique for many years now and I solved the disconcerting effect that your entry seems to disappear and you have to search for it to continue. Here it is (for column A):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column <> 1 Or Target.Columns.Count > 1 Then Exit Sub
    Dim tmp As Variant
    tmp = Cells(Target.Row, 2).Formula 'save contents
    On Error GoTo Enable_Events
    Application.EnableEvents = False
    Cells(Target.Row, 2) = "#"
    Range("A1").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes
    Cells(Application.Match("#", Columns(2), 0), Selection.Column).Select
    Cells(Selection.Row, 2) = tmp 'restore contents
    Application.EnableEvents = True
End Sub

If there is any chance that there could be a record with a single # in the second column, simply replace the # in the macro with one or more characters that are unique.
Willy Vanhaelen    16 Nov 2013, 13:33
Steven, in Excel you can enter the date and time in one cell. You then have to format it accordingly. That solves your problem.
steven    14 Nov 2013, 08:38
i have a document that is used by my mother in law to hold data on children and clients she child minds for
it has 10 colums a-j and is about 50 rows deep
my problem is that i need it to auto sort by date and time these details are in colums d (date) and e (time)
i have tried making up a macro to do it but it didnt work correctly if anyone could help i would be very greatful.

will    31 Oct 2013, 21:45
Hi! This tips is awesome.

I would like to use this but make it appear on different sheet, would this be possible?

Please help. thanks in advance.

Dragoniel    26 Sep 2013, 06:56
Works flawlessly, thank you.
Miguel    12 Mar 2013, 12:37
This is really awasome, i am using to create time line for my project, and every time i add something even if the date is older or newer this macro put everithing in order just pressing enter Thanks.
Dappy    05 Mar 2013, 01:43
Topic: Automatically Center Cells using the center align on the tool bar.

I stumbled on your "Automatically Sorting as You Enter Information." I am looking for a VBA code to automatically center (align cells to the center) Pivot Table cells (for example range B3:B30,C3:C30).

Thanks in advance for your assistance.
Roy Prockter    17 Apr 2012, 13:22
This is interesting, I'd like to follow the thread

Our Company

Sharon Parq Associates, Inc.

About Tips.Net

Contact Us


Advertise with Us

Our Privacy Policy

Our Sites


Beauty and Style




DriveTips (Google Drive)

ExcelTips (Excel 97–2003)

ExcelTips (Excel 2007–2016)



Home Improvement

Money and Finances


Pests and Bugs

Pets and Animals

WindowsTips (Microsoft Windows)

WordTips (Word 97–2003)

WordTips (Word 2007–2016)

Our Products

Helpful E-books

Newsletter Archives


Excel Products

Word Products

Our Authors

Author Index

Write for Tips.Net

Copyright © 2016 Sharon Parq Associates, Inc.