如何分割日期和时间

时间:2017-12-27 22:40:48

标签: excel vba excel-vba

嘿伙计们,我想知道如何将日期和时间分成不同的行。我将添加数据图片,以便您可以看到它。我希望Date在A列上,时间在B列,包括AM / PM。

我试图用空格分隔符来做这件事,但我一直在犯错误,而在互联网上人们首先选择单元格,但我想知道如何在不选择单元格的情况下进行操作。

Sub CompareTime()

Dim ws As Worksheet

Dim lastRow As Long
Dim arr As Long
Dim test As Double

Set ws = ActiveSheet

Cells(1, 2).EntireColumn.Insert

'Find last data point
With ws
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With


For Count = 1 To lastRow
'split date
Cells(1, Count).Offset(0, 1) = Split(Cells(1, Count).Value, " ")


Next Count


End Sub

enter image description here

3 个答案:

答案 0 :(得分:4)

日期/时间是一个数字,而不是一个文本字符串,所以要获得从十进制中删除整数所需的日期,然后格式化它们:

Sub CompareTime()

Dim ws As Worksheet

Dim lastRow As Long
Dim Count As Long
Dim test As Double

Set ws = ActiveSheet


'Find last data point
With ws
    .Columns(2).Insert
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    For Count = 5 To lastRow
        'split date
        test = .Cells(Count, 1).Value2
        .Cells(Count, 1).Value2 = Int(test)
        .Cells(Count, 1).NumberFormat = "m/d/yyyy"
        .Cells(Count, 1).Offset(0, 1).Value2 = test - Int(test)
        .Cells(Count, 1).Offset(0, 1).NumberFormat = "hh:mm AM/PM"

    Next Count
End With

答案 1 :(得分:2)

另一种方法。斯科特的代码更简单。

Sub CompareTime()

Dim ws As Worksheet

Dim lastRow As Long
Dim arr As Long
Dim test As Double
Dim vDB, vR(), n As Long, i As Long

Set ws = ActiveSheet



'Find last data point
With ws
    .Cells(1, 2).EntireColumn.Insert
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    vDB = .Range("a5", "a" & lastRow)

    n = UBound(vDB, 1)
    ReDim vR(1 To n, 1 To 2)

    For i = 1 To n
        vR(i, 1) = DateValue(Format(vDB(i, 1), "yyyy/mm/dd"))
        vR(i, 2) = TimeValue(Format(vDB(i, 1), "hh:mm"))
    Next i
    .Range("a5").Resize(n, 2) = vR
    .Columns(1).NumberFormatLocal = "mm/dd/yyyy"
    .Columns(2).NumberFormatLocal = "hh:mm"
End With
End Sub

答案 2 :(得分:1)

所以我在搞乱分割功能后发现了一种非常简单的方法。我只使用了一个空格分隔符,并将日期与包含AM / PM的时间分开。

Sub CompareTime()

Dim ws As Worksheet
Dim count As Long
Dim lastRow As Long
Dim arr As Long
Dim store As Double

Set ws = ActiveSheet

Cells(1, 2).EntireColumn.Insert

'Find last data point
With ws
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

For Count = 5 To lastRow

'split date
Cells(Count, 1).Offset(0, 1).Value = Split(Cells(Count, 1), " ")(1) & " " & Split(Cells(Count, 1), " ")(2)
Cells(Count, 1).Value = Split(Cells(Count, 1), " ")


Next Count

End Sub