excel - 如何拆分日期和时间

标签 excel vba

我想知道如何将日期和时间分成单独的行。

enter image description here

我想要 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

最佳答案

日期/时间是一个数字而不是文本字符串,因此要获取您需要从小数中拆分整数的日期,然后对其进行格式化:

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

关于excel - 如何拆分日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47999466/

相关文章:

excel - 将两个不同工作簿中的两个范围粘贴到 Outlook 邮件正文中

vba - Excel 选择与激活

excel - 更新更改而不取消选择/重新选择复选框

从列表中随机选择

excel - 如何根据文件名模式使用最新的文件?

excel - 是否可以将数组的字段传递给具有可变参数数组的函数?

vba - 使用 Excel VBA 向右移动列数据

python - 从 Python 操作 Excel

vba - 使用 VBA 引用行号

excel - 强制字符串变量为英国日期格式