Excel VBA Sort by Date: Step-by-Step Guide
In this article
To sort by date using Excel VBA, you must define the range of your data, specify the column containing the dates, and set the sort order to either ascending (oldest to newest) or descending (newest to oldest). The most reliable way to achieve this is by using the Range.Sort method, which allows you to target a specific key column while keeping the rest of your data rows intact. This automation is essential for reports that update daily, ensuring your timeline remains chronological without manual clicking.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- A dataset containing at least one column formatted specifically as a Date.
- The Developer tab enabled in the Excel Ribbon (if not visible, right-click the Ribbon, select Customize the Ribbon, and check the Developer box).
- Basic access to the Visual Basic for Applications (VBA) editor.
Step-by-Step
- Open the VBA Editor: Press
Alt + F11on your keyboard. This opens the Visual Basic Editor window where all your macros are written. - Insert a New Module: In the top menu, go to
Insert > Module. This creates a blank sheet of code where you can write your sorting script without interfering with specific sheet objects. - Define Your Variables: Start your sub-routine by declaring the variables you will use. This prevents errors and makes the code run faster. For example, use
Dim ws As WorksheetandDim sortRange As Range. - Set the Worksheet: Assign your target sheet to the variable. Use
Set ws = ThisWorkbook.Sheets("Sheet1"), replacing "Sheet1" with the actual name of your tab. - Identify the Data Range: You need to tell VBA exactly which cells to sort. To make the code dynamic (so it works even if you add more rows), use the
CurrentRegionproperty. For example:Set sortRange = ws.Range("A1").CurrentRegion. This selects all connected data starting from cell A1. - Write the Sort Command: Use the
.Sortmethod on your range. A complete line looks like this:sortRange.Sort Key1:=ws.Range("B1"), Order1:=xlAscending, Header:=xlYes. In this example,Key1is the column containing the dates (Column B),Order1determines the direction, andHeader:=xlYesensures your top row isn't sorted into the data. - Run the Macro: Close the VBA editor and return to Excel. Press
Alt + F8, select your macro name from the list, and clickRun.
Common Mistakes
One of the most frequent errors is sorting data that is not actually formatted as a date. If your dates are stored as text (e.g., "January 1st, 2023" written as a string), VBA will sort them alphabetically rather than chronologically. This results in "April" coming before "January" because A precedes J. Always ensure your date column is set to a Date format in the Home tab before running the script.
Another common mistake is failing to include the Header:=xlYes argument. If you omit this or set it to xlNo, Excel will treat your column headers (like "Date" or "Transaction ID") as actual data points. Consequently, your header row will be moved somewhere into the middle of your list based on its alphabetical value, which ruins the structure of your table.
Users also frequently forget to define the full CurrentRegion. If you only apply the sort to the date column itself (e.g., Range("B1:B100").Sort) without including the surrounding columns, you will decouple the dates from their associated data. This means the date in row 2 might move to row 50, but the name or amount associated with that date will stay in row 2, effectively corrupting your entire database.
Tips
To make your sorting more flexible, avoid hard-coding the column letter. Instead, use a variable to find the column header by name. You can use the .Find method to locate the word "Date" in the first row and then use that column index for the Key1 argument. This ensures the macro still works even if you insert a new column to the left of your date column.
If you are dealing with very large datasets (thousands of rows), you can speed up the execution by disabling screen updating. Add Application.ScreenUpdating = False at the beginning of your code and Application.ScreenUpdating = True at the end. This prevents Excel from visually refreshing the screen every time a row moves, which significantly reduces the time it takes for the macro to complete.
Consider adding a toggle for the sort order. Instead of hard-coding xlAscending, you can create a simple If...Then statement that checks a specific cell (like cell Z1). If Z1 says "Newest", the code uses xlDescending; if it says "Oldest", it uses xlAscending. This allows non-technical users to change the sort order without opening the VBA editor.
Troubleshooting
If the code runs but the dates do not move, first check for merged cells. VBA's sort function often fails or produces unpredictable results when merged cells are present within the sort range. Unmerge all cells in your dataset and use "Center Across Selection" if you need the visual look of merged cells.
If you receive a "Type Mismatch" error, it usually means the Key1 range is not valid or the data types in that column are inconsistent. Check for cells that contain errors like #VALUE! or #N/A within the date column. These errors can crash the sorting algorithm. Use a filter to find and remove these errors before running the macro.
If the macro sorts the dates but leaves the other columns behind, you have a range definition problem. Ensure you are using CurrentRegion or a specific range that encompasses all columns (e.g., Range("A1:G100")). If your data has completely empty columns or rows, CurrentRegion will stop at the gap. In this case, manually define the range using ws.UsedRange or find the last row and column using Cells(Rows.Count, 1).End(xlUp).Row.
If the dates are sorting in a strange order (e.g., 1/1/2023, 1/1/2024, 2/1/2023), your dates are definitely stored as text. To fix this, select the date column, go to the Data tab, select Text to Columns, click Next twice, select Date (MDY), and click Finish. This forces Excel to convert text strings into actual serial date numbers that VBA can recognize.
Frequently Asked Questions
Can I sort by date and then by another column?
Yes. You can add a second level of sorting by using the Key2 and Order2 arguments within the same .Sort method. For example, you can sort by Date (Key1) and then by Customer Name (Key2).
Does this work on Excel for Mac?
Yes, the Range.Sort method is standard across both Windows and Mac versions of Excel VBA, though the keyboard shortcuts to open the editor may differ slightly.
What is the difference between xlAscending and xlDescending for dates?
xlAscending sorts from the oldest date to the newest date. xlDescending sorts from the newest (most recent) date to the oldest date.
How do I make the sort happen automatically when I enter a date?
You can move your code from a standard module to the Worksheet_Change event of the specific sheet. This triggers the macro every time a cell value is modified in the worksheet.
Will this macro delete any of my data?
No, the sort method only rearranges the order of existing rows; it does not delete or overwrite the content of the cells.
Can I sort dates that include timestamps?
Yes. Excel stores dates and times as numbers (dates are integers and times are decimals). The sort method handles date-time stamps accurately, sorting them to the second.