- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
VBA: How to Change Date Format
Understanding Date Variables
A VBA date varaible stores your date as a numeric values that can be converted into a wide array of formats.
The earliest date that can be stored is 1/1/1900.
Later dates are stored based on their relation to this date.
1=1/1/1900
2=1/2/1900
3=1/3/1900
and so on...
The code below would return 1/3/1900 in cell "A2"
Sub test() Dim testDate As Date testDate = 3 Range("A2") = testDate End Sub
Loading Date Variables
Loading date based on their values may seem pretty straightforward, but when you begin to think of more current dates they become quite a challenge.
For instance 9/29/2012 is represented by a value of 41,181. How many of you could come up with that off the top of your head?
Luckily for those of us who aren't some kind of mathematical genius. VBA has a function to convert a date from string to its value.
Converting Date String to Value
VBA can convert a date string in any standard format to its value.
A few examples:
DateValue("September 29, 2012")=41181
DateValue("Sep 29, 2012")=41181
DateValue("09/29/2012")=41181
DateValue("09/29/12")=41181
Sub test() Dim testDate As Date testDate = DateValue("Sep 29, 2012") Range("A2") = testDate End Sub
Formatting Dates
Once your string has been converted into a date format it can be returned in an format you'd like. To do this you use the format function in conjunction with the date function.
Note: You may have to apply custom number formatting in Excel if you aren't using a native date format.
Sub test() Dim testDate As Date testDate = DateValue("Sep 29, 2012") Range("A1") = "Examples of date formatting" Range("A2") = Format(testDate, "YYMMDD") Range("A3") = Format(testDate, "MMDDYY") Range("A4") = Format(testDate, "MM/DD/YYYY") Range("A5") = Format(testDate, "YY,MM,DD") Range("A6") = Format(testDate, "MMM, YY YY") Range("A7") = Format(testDate, "MMMM, DD YYYY") 'with custom formatting Range("A8") = Format(testDate, "DD MMMM YYYY") Range("A8").NumberFormat = "DD MMMM YYYY" End Sub