Excel VBA Text to Date: Convert Strings to Date Formats
In this article
To convert text to a date in Excel VBA, the most reliable method is using the CDate() function for standard formats or the DateSerial() function for non-standard strings. These tools allow you to transform a string of characters—which Excel treats as simple text—into a serial date number that can be used for calculations, sorting, and formatting. This process is essential when importing data from CSVs or external databases where dates are often stored as strings, preventing you from using date-based filters or formulas.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- The Developer tab enabled in the Excel Ribbon (Right-click any tab > Customize the Ribbon > Check "Developer").
- A dataset containing dates stored as text (identifiable by a small green triangle in the cell corner or by being left-aligned by default).
- Basic familiarity with opening the Visual Basic Editor (ALT + F11).
Step-by-Step
- Open the Visual Basic Editor: Press ALT + F11 on your keyboard to launch the VBA environment.
- Insert a New Module: In the top menu, go to Insert > Module. This creates a blank space where you can write your custom macro code.
- Define Your Variable Types: Start your subroutine by declaring your variables. Use String for the original text and Date for the converted result. This ensures VBA handles the memory and data types correctly.
- Write the Conversion Logic (Standard Formats): If your text is in a recognizable format (e.g., "01/01/2023" or "January 1, 2023"), use the CDate function. For example:
Dim textDate As String: textDate = "12/25/2023"Dim realDate As Date: realDate = CDate(textDate) - Write the Conversion Logic (Custom Formats): If your text is in a non-standard format like "20231225" (YYYYMMDD), CDate will fail. You must use Mid to slice the string and DateSerial to assemble it.
Dim rawText As String: rawText = "20231225"Dim finalDate As DatefinalDate = DateSerial(Left(rawText, 4), Mid(rawText, 5, 2), Right(rawText, 2)) - Apply the Result to a Cell: Assign the converted date variable back to a worksheet cell. To ensure Excel doesn't turn it back into text, explicitly set the cell's number format.
Range("A1").Value = finalDateRange("A1").NumberFormat = "mm/dd/yyyy" - Loop Through a Range: To convert an entire column, wrap your logic in a For Each loop. Define a range (e.g., Set myRange = Range("A1:A100")) and iterate through every cell, applying the conversion logic to each value.
- Run the Macro: Press F5 or click the green "Run" arrow in the toolbar to execute the code and transform your text data into actual dates.
Common Mistakes
One of the most frequent errors is relying on CDate for dates that do not match the system's regional settings. For instance, if your computer is set to US English (MM/DD/YYYY) but you try to convert a UK date string (DD/MM/YYYY), VBA may swap the month and day or throw a "Type Mismatch" error if the day is greater than 12. This is a silent failure that can corrupt your data without triggering a crash.
Another common mistake is forgetting to format the destination cell. Even if the VBA code successfully converts a string to a date, if the cell is formatted as "Text," Excel may display the date as a five-digit serial number (e.g., 45285). This number is actually how Excel stores dates internally, but it is not user-friendly. Always include a .NumberFormat line in your code to ensure the visual output is correct.
Users also frequently fail to handle empty cells. If your loop encounters a blank cell, CDate will return an error because it cannot convert a null value. Always wrap your conversion logic in an If Not IsEmpty(cell) check or use an On Error Resume Next statement (though the former is safer) to skip blanks.
Tips
To make your code more robust, use the IsDate() function before attempting a conversion. IsDate returns a Boolean (True or False) and allows you to verify if the string can be converted without causing the macro to crash. This is particularly useful when dealing with messy datasets that might contain "N/A" or other non-date text in the date column.
When dealing with very large datasets (thousands of rows), avoid writing to the sheet inside the loop. Instead, read the range into a VBA Array, perform the conversions within the array in memory, and then write the entire array back to the sheet in one operation. This can reduce the execution time from minutes to seconds.
For absolute control over date parsing, consider creating a custom function (UDF) that you can use both in VBA and as a formula in your spreadsheet. By creating a function like Function FixMyDate(txt As String), you can standardize how your organization handles date conversions across multiple workbooks.
Troubleshooting
If you receive a "Type Mismatch" (Error 13), it means VBA encountered a value it cannot interpret as a date. Use the Trim() function to remove leading or trailing spaces from your strings before converting them.
If the dates are converting but the months and days are swapped, your system regional settings are conflicting with the data format. In this case, stop using CDate and switch to DateSerial. By manually extracting the year, month, and day using Left, Mid, and Right, you bypass the system's regional interpretation and force Excel to read the date exactly as you intend.
If the macro runs but nothing happens, ensure your range references are correct. If you are using ActiveCell or Selection, make sure the correct cells are highlighted before running the code. It is generally better to use explicit references like Sheets("Sheet1").Range("A1:A10") to avoid targeting the wrong sheet.
Frequently Asked Questions
Can I convert text to date without VBA?
Yes, you can use the "Text to Columns" feature under the Data tab. Select the column, go to Text to Columns > Next > Next, and in the third step, select "Date" and choose the format of the original text (e.g., MDY).
Why does my date look like a number like 45123?
Excel stores dates as sequential serial numbers starting from January 1, 1900. If you see a number, the value is a valid date, but the cell is formatted as "General" or "Number". Change the cell format to "Short Date" to fix this.
What is the difference between CDate and DateValue?
CDate is more flexible and can handle both dates and times, whereas DateValue is specifically designed to extract the date portion of a string. For most text-to-date tasks, CDate is the standard choice.
How do I handle dates in YYYYMMDD format?
Since this is not a standard date format, use DateSerial(Left(str, 4), Mid(str, 5, 2), Right(str, 2)). This tells VBA exactly which characters represent the year, month, and day.
Will this work on a Mac?
Yes, VBA is supported on Excel for Mac, though the keyboard shortcuts for the editor may differ. The logic for CDate and DateSerial remains identical across both platforms.