Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date & time text to column

Tags:

excel

vba

I have problem with a Text to column macro.

I have an Excel file with different macros and one sheet is a table which a user needs to fill in before running one of the macros. Two of the cells are date and time.

I need to copy a date from one file to another and then split the date from e.g. 19/03/2016 to 3 columns Day, Month and Year i.e. 19, 3 & 2016. When I record the macro all works fine, but when I run the macro, the date is converted into US format and I get 3, 19 & 2016. The same applies to time, if I have e.g. 15:30, when recording macro I get 15 and 30 but when I run macro I get 3 & 30.

Below is the code which I use:

Sub Reporting_Start_Date()

Application.Workbooks(1).Activate
Sheets("Activity Info").Select
Range("C8").Select
Selection.Copy
Application.Workbooks(2).Activate
Range("O2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False

Selection.NumberFormat = "m/d/yyyy"
Selection.TextToColumns Destination:=Range("O2"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
    :="/", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
    TrailingMinusNumbers:=True
Selection.NumberFormat = "0"

End Sub

And recorded macro for time is:

Sub Reporting_Start_Time()

Application.Workbooks(1).Activate
Sheets("Activity Info").Select
Range("C9").Select
Selection.Copy
Application.Workbooks(2).Activate
Range("R2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False

Selection.NumberFormat = "[$-F400]h:mm:ss AM/PM"
Selection.TextToColumns Destination:=Range("R2"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
    :=":", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 9)), _
    TrailingMinusNumbers:=True
Selection.NumberFormat = "0"

End Sub
like image 491
Yuri Avatar asked Mar 12 '23 22:03

Yuri


1 Answers

Say we have a cell with a date in dd/mm/yyyy format. Select it and run:

Sub DateSplitter()
    Dim ary
    With Selection
        ary = Split(.Text, "/")
        .Offset(0, 1) = ary(o)
        .Offset(0, 2) = ary(1)
        .Offset(0, 3) = ary(2)
    End With
End Sub

enter image description here

You can code something similar for time. The code can easily be modified to handle all the dates or times in a column, etc.

like image 72
Gary's Student Avatar answered Mar 21 '23 04:03

Gary's Student