如何分割日期和时间

问题描述 投票:1回答:3

嘿伙计们,我想知道如何将日期和时间分成不同的行。我将添加数据图片,以便您可以看到它。我希望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

excel vba excel-vba
3个回答
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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.