Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split date/time not working when 12:00:00 AM

Tags:

excel

vba

I have vba function to split date/time on my worksheet but when it find 0:00AM it will stop and I don't know how to fix this

code

Function extractDateTime(strTime As Date) As Variant
  Dim arrD, d As String, t As Date
  arrD = Split(strTime, " ")
  d = arrD(0)
  t = CDate(arrD(1) & " " & arrD(2))
  extractDateTime = Array(d, t)
End Function

pic when it find date/time at 12:00:00 AM function not return value arrD(1) and arrD(2) enter image description here

cell value

enter image description here

pic when function normally working enter image description here

like image 656
alpha Avatar asked Nov 18 '25 04:11

alpha


2 Answers

Always handle date/time as Date, not text, not numbers, no exceptions. So:

Public Function ExtractDateTime(Value As Date) As Variant

    Dim d   As Date
    Dim t   As Date

    d = DateValue(Value)
    t = TimeValue(Value)

    ExtractDateTime = Array(d, t)

End Function
like image 153
Gustav Avatar answered Nov 21 '25 01:11

Gustav


Parsing the Date for spaces is not a great way to go about it.

Instead, you can use Format to just get the pieces you want.

Function extractDateTime(dt As Date) As Variant
    Dim d As String, t As String
    d = Format(dt, "dd/mm/yyyy")
    t = Format(dt, "hh:mm:ss AMPM")
    extractDateTime = Array(d, t)
   
    Debug.Print d
    Debug.Print t

    Debug.Print Format(dt, "mmm dd, yyyy")
    Debug.Print Format(dt, "mmmm")

    Debug.Print WeekdayName(Weekday(dt))

End Function

Kinda seems like a waste of a function tho when you can just do this:

Result = Array(Format(dt, "dd/mm/yyyy"), Format(dt, "hh:mm:ss AMPM"))
like image 21
braX Avatar answered Nov 20 '25 23:11

braX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!