Convert String to Date

yeheya

Board Regular
Joined
May 20, 2004
Messages
162
Could you pls tell me how to convert a string to date in VBA?

strDate="051228" - Input (YYMMDD)

2005-12-28 - Output

I need this in VBA only

Regards,
Yeheya
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
One way:

Code:
Sub Test()
    strdate = "051228"
    MsgBox DateSerial(Left(strdate, 2), Mid(strdate, 3, 2), Right(strdate, 2))
End Sub
 
Upvote 0
Need to bear in mind that a date is basically a number that can be formatted various ways. So if we want it into a cell as a date we use the serial number.
Code:
Sub test()
    Dim strDate As String
    Dim MyDate As Date
    '---------------------------
    strDate = "051228"
    MyDate = DateSerial(2000 + CInt(Left(strDate, 2)), _
        CInt(Mid(strDate, 3, 2)), CInt(Right(strDate, 2)))
    Range("A1").Value = MyDate
    MsgBox (Format(MyDate, "yyyy-mm-dd"))
End Sub
 
Upvote 0
BrianB:
You don't need to convert the parts to integer to use the values in the DateSerial function.
Also that assumes that it will always be a year in 2000+

The way Andrew has it posted it will use Excel's method of figuring out the century.
 
Upvote 0
Code:
You don't need to convert the parts to integer

Experience in answering queries in this forum shows that it is best not to assume exactly how the code is going to be used. It can save further queries.
 
Upvote 0
Code:
x = DateValue("Nov-28-05")
MsgBox x
 
Upvote 0

Forum statistics

Threads
1,214,614
Messages
6,120,530
Members
448,969
Latest member
mirek8991

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top