excelvbatext-to-column

Text to Column (Date) using current year instead of the timestamp


I'm using text to columns as part of a VBA macro to separate timestamps into 2 other columns. When I format Column B to dd/mm/yyyy it uses the current year 2020 instead of 2019. Is there a way to adjust my macro to pull the year from the original timestamp or alternatively, pull the year from Column C once Text to Columns has completed?

Reference1

Reference2

Range("A5").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.TextToColumns Destination:=Range("A5"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 3), Array(2, 3), Array(3, 3)), TrailingMinusNumbers:=True
    Range("B5").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.NumberFormat = "dd/mm/yyyy;@"
    Selection.TextToColumns Destination:=Range("B5"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(1, 8), TrailingMinusNumbers:=True

Solution

  • This uses arrays:

    Sub mydatesplit()
        With ActiveSheet
            Dim arr As Variant
            arr = .Range("A5", .Cells(.Rows.Count, 1).End(xlUp)).Value
    
            Dim outArr() As Variant
            ReDim outArr(1 To UBound(arr, 1), 1 To 3)
    
            Dim i As Long
            For i = 1 To UBound(arr, 1)
                Dim spltStr() As String
                spltStr = Split(Replace(arr(i, 1), ",", ""), " ")
                If UBound(spltStr) >= 5 Then
                    outArr(i, 1) = spltStr(0)
                    outArr(i, 2) = DateValue(spltStr(2) & " " & spltStr(1) & " " & spltStr(3))
                    outArr(i, 3) = TimeValue(spltStr(4) & " " & spltStr(5))
                End If
            Next i
    
            .Range("B5").Resize(UBound(outArr, 1), UBound(outArr, 2)).Value = outArr
        End With
    End Sub
    

    After Running:

    enter image description here


    BTW with Dynamic Array formulas newly introduced into Excel with the latest subscription one can use fairly simple formula:

    Date:

    =--TEXTJOIN(" ",TRUE,INDEX(TRIM(MID(SUBSTITUTE(SUBSTITUTE(A5,",","")," ",REPT(" ",999)),(ROW($1:$7)-1)*999+1,999)),{3,2,4}))
    

    Time

    =--TEXTJOIN(" ",TRUE,INDEX(TRIM(MID(SUBSTITUTE(SUBSTITUTE(A5,",","")," ",REPT(" ",999)),(ROW($1:$7)-1)*999+1,999)),{5,6}))