Excel / VBA Date Function with 7 Formatting Examples
VBA Date function returns the current date of the system. It can be used with the format function to get the date in the desired format. We will show this in examples.
Date function in VBA
- VBA Date function returns the current date of the system.
- This is a variant type.
- It can be used with the format function to get the date in the desired format. We will show this in examples.
An example of using Date function
We will simply display the Date in the message box to get the current date:
1 2 3 4 5 6 |
Sub Date_ex() MsgBox (Date) End Sub |
Output:
You can see, it displays the current date of the system – in the set format.
Format date in day, full month name, and two digit year format
Using Date() alone might not be as meaningful as you might want to display in your Excel sheet.
Now let us have a look at formatting date by using the Date function with Format().
So first, we will show you using a Date type variable and assigning it the Date() function and using it in Format() function.
Code:
1 2 3 4 5 6 7 8 9 10 |
Sub Date_ex() Dim Dt As Date Dt = Date MsgBox (Format(Dt, "dd mmmm yy")) End Sub |
Result:
In order to get the date with the full month name, use ‘m’ four times.
With full year like 2021, 2022 etc.
Just adding two more ‘yy’ to the above example and it will get us a year in four digits.
1 2 3 4 5 6 7 8 9 10 11 12 |
Sub Date_ex() Dim Dt As Date Dt = Date 'Four digit year MsgBox (Format(Dt, "dd mmmm yyyy")) End Sub |
Result:
Date in yyyymmdd format
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Sub Date_ex() Dim Dt As Date Dt = Date 'Four digit year MsgBox (Format(Dt, "yyyymmdd")) End Sub |
Result
Day, Short Month name with four digit year example
1 2 3 4 5 6 7 8 9 10 11 12 |
Sub Date_ex() Dim Dt As Date Dt = Date 'Short Month Name MsgBox (Format(Dt, "dd mmm, yyyy")) End Sub |
Result:
Short Day name, Short Month, and Full year
Use ‘ddd’ for the short day name as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Sub Date_ex() Dim Dt As Date Dt = Date 'Short Day Name, Short Month MsgBox (Format(Dt, "ddd, dd mmm, yyyy")) End Sub |
Full Day, Short Mon and four-digit year formatting
By using Date() function with Format() function, we will display the date in Full day name, short month, and four digit year:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Sub Date_ex() Dim Dt As Date Dt = Date 'Full Day Name, Short Month MsgBox (Format(Dt, "ddd, dd mmm, yyyy")) End Sub |