1

I have a number of strings in cells which are dates but they need to be converted to date format.

They are in the following format:

mmm dd, yyyy

For Example:

Feb 10, 2016

So they can be 11 or 12 in length:

Feb 1, 2016

I have started writing a function to parse each part of the string individually (day as integer, month as integer and year as integer) to then convert into date format.

Firstly, is there an easier/slicker way to do this than the above?

If there isn't an easier way, what's the best was to convert the 3 letter month (e.g. Feb or Mar or Apr) into a month number (e.g. 2 or 3 or 4)? As that is the only bit I'm really stuck with.

Teamothy
  • 2,000
  • 3
  • 16
  • 26
megatron77
  • 221
  • 1
  • 8
  • 18

4 Answers4

10

In VBA you could use: cdate("Feb 10, 2016").
As a function this would be:

Public Function ConvertToDate(rng As Range) As Date

    ConvertToDate = CDate(rng)

End Function
Darren Bartrup-Cook
  • 18,362
  • 1
  • 23
  • 45
3

Use a Date variable to read the value and then use the Format function to format the date as you see fit.

For example:

Sub test()
    Dim D As Date
    D = Range("A1").Value
    MsgBox Format(D, "mm/dd/yyyy")
End Sub

If I run the code with the string "Feb 10, 2016" in A1 then "02/10/2016" is displayed in the message box

John Coleman
  • 51,337
  • 7
  • 54
  • 119
2

Try this:

Sub test()
    MsgBox Month(Datevalue("Feb 10, 2016"))
End Sub

This will give: 2

Mrig
  • 11,612
  • 2
  • 13
  • 27
2

Do you really need VBA? Excel provides you with a Text to Date function =DATEVALUE() and it does recognize Feb 10, 2016.

Robert Co
  • 1,715
  • 8
  • 14
  • Are you sure of that? I tried it before leaving my answer and it returned a `#VALUE!` error. Admittedly the help file for the function states: _Using the default date system in Microsoft Excel for Windows, the date_text argument must represent a date between January 1, 1900 and December 31, 9999_. Using the format (and date) they've used I get the error with `=DATEVALUE("January 1, 1900")` – Darren Bartrup-Cook May 10 '16 at 13:50
  • @DarrenBartrup-Cook It will depend on your regional settings. In the UK that format wouldn't be recognised. – Rory May 10 '16 at 14:08
  • ah, ok. Cheers Rory - that'll be why it wasn't recognised then. – Darren Bartrup-Cook May 10 '16 at 14:13