Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: How to get date as a string yyyy-mm-dd

Tags:

excel

vba

I am trying to get the Date as a string formatted yyyy-mm-dd.

I have tried various things with strange results:

Dim mydate As String
mydate = Date
mydate = Year(Date)
mydate = Month(Date)
mydate = Day(Date)
  1. The first one gives 11/02/ without the year.

I can try to concatenate the data but:

  1. The second gives the year OK
  2. However the third gives month as 2 instead of 02
  3. Similar for fourth.

Any clarification or an example would be very welcome.

like image 621
Studix Avatar asked Feb 11 '16 16:02

Studix


People also ask

How do I convert a date to a string in VBA?

In VBA, there is a method through which we can convert a given string to a date. The method is known as the CDATE function in VBA. It is an inbuilt function in VBA, and the parts required for this function are first to convert the string to a number, then convert the given number to date.

How do I change the date format in VBA?

To format a date in VBA, we use the inbuilt FORMAT function itself. It takes input as the date format and returns the desired format required. The arguments required for this function are the expression and the format type.


2 Answers

Use the Format function from the VBA.Strings built-in module:

Debug.Print Format(Now, "YYYY-MM-DD")
like image 93
Mathieu Guindon Avatar answered Oct 17 '22 22:10

Mathieu Guindon


Dim sToday As String
sToday = CStr(Date)

That gives sToday value, e.g. "2020-12-31", in the format of my system's date.

like image 40
Marek M Avatar answered Oct 17 '22 23:10

Marek M