Loading
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, _
      Orientation:=xlTopToBottom
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, _
          Orientation:=xlTopToBottom
    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:

Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!

 

Comments for this tip:

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.Clear
            .SortFields.Add Key:=Range("B:B"), SortOn:=xlSortOnValues, Order:=xlAscending, _
                            DataOption:=xlSortNormal
            .SortFields.Add Key:=Range("C:C"), SortOn:=xlSortOnValues, Order:=xlAscending, _
                            DataOption:=xlSortNormal
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .SetRange Range("B2:C" & CStr(ActiveSheet.Rows.Count))
            .Apply
        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.Clear
                .SortFields.Add Key:=Range("B:B"), SortOn:=xlSortOnValues, Order:=xlAscending, _
                                DataOption:=xlSortNormal
                .SortFields.Add Key:=Range("C:C"), SortOn:=xlSortOnValues, Order:=xlAscending, _
                                DataOption:=xlSortNormal
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .SetRange Range("A2:E" & CStr(ActiveSheet.Rows.Count))
                .Apply
            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?
Thaks
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
Hi

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
Hello,

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
Hi!

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
Hi,

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?

DRB
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
Hi!
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, _
          Orientation:=xlTopToBottom
    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
@Barry

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, _
          Orientation:=xlTopToBottom
    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, _
      Orientation:=xlTopToBottom
End Sub


Thanks!
Barry Fitzpatrick    05 Mar 2014, 05:31
@Steph,

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
@Willy

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
@Barry
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, _
          Orientation:=xlTopToBottom
    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, _
          Orientation:=xlTopToBottom
    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.

Thanks
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, _
      Orientation:=xlTopToBottom
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
Enable_Events:
    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.

thanks
steven
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.

Will
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

Leave your own comment:

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

Our Company

Sharon Parq Associates, Inc.

About Tips.Net

Contact Us

 

Advertise with Us

Our Privacy Policy

Our Sites

Tips.Net

Beauty and Style

Cars

Cleaning

Cooking

DriveTips (Google Drive)

ExcelTips (Excel 97–2003)

ExcelTips (Excel 2007–2013)

Gardening

Health

Home Improvement

Money and Finances

Organizing

Pests and Bugs

Pets and Animals

WindowsTips (Microsoft Windows)

WordTips (Word 97–2003)

WordTips (Word 2007–2013)

Our Products

Premium Newsletters

Helpful E-books

Newsletter Archives

 

Excel Products

Word Products

Our Authors

Author Index

Write for Tips.Net

Copyright © 2014 Sharon Parq Associates, Inc.