Search code examples
excelvba

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


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.


Solution

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

    Debug.Print Format(Now, "YYYY-MM-DD")