Excel VBA or Formula to convert text to Date with Time type

date timemicrosoft excelvbaworksheet-function

I have a quite a number of data where its date/timestamp has been imported into excel as text. Excel does not really recognize it as date with time. e.g. 25.08.2011 16:17:59 (mm.dd.yyyy hh:mm:ss)

Now I need to convert it to a date with time so it can be used for further calculation with excel.

How can I do that? The current workaround is to "re-enter" the stuff. Means if you click into the cell to activate the "edit" and press just return then it gets automatically converted by Excel to a date time. I can automate the stuff by the VBA macro below, but while I have a quite a huge range over 30'000 it takes long time and you can not change the window / or app in the mean time because it works through the gui.

 Set c = Range("A1").Cells
 c.Select
 For row = c.row To 30000
     SendKeys "{F2}", True
     SendKeys "{ENTER}", True
 Next row

Any other suggestions how to automate this stuff much quicker? I tried already the following other possiblities but did not work:

  • change ther format of the cell to date with custom format mm.dd.yyyy hh:mm:ss – cell value get not automatically converted to date
  • using formula DATEVALUE(String) : the value get converted but it just converts the date and the time gets lost e.g. 25.08.2011 00:00:00 (mm.dd.yyyy hh:mm:ss)
  • using formula TIMEVALUE(String) the value get converted but it just converts the time and the date gets lost e.g. 00.00.1900 16:17:59 (mm.dd.yyyy hh:mm:ss)
  • using VBA function "Format()" e.g. value get changing the format but still afterwards recognized as text e.g.

    Dim myVar as String
    myVar = Format(cell.value, "dd/mm/yyyy hh:nn:ss")

  • using VBA macro with cell.FormulaR1C1 = "25.08.2011 16:17:59" but it does not work either. value keep recognized as text

Thanks for your help

Best Answer

Select the cells and run:

Sub DateFixer()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
        For Each r In Selection
            v = r.Text
            r.Clear
            r.NumberFormat = "dd/mm/yyyy hh:mm:ss"
            r.Value = DateSerial(Mid(v, 7, 4), Mid(v, 4, 2), Left(v, 2)) + TimeSerial(Mid(v, 12, 2), Mid(v, 15, 2), Right(v, 2))
        Next r
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
End Sub
Related Question