【问题标题】:Split Column to Date and Time将列拆分为日期和时间
【发布时间】:2022-06-14 17:23:09
【问题描述】:

我正在尝试将包含日期和时间组合的列拆分为两列,其中日期和时间是分开的。

C 列包含日期和时间的组合,例如“2022-01-01 09:30:00”。
这应该分为 D 列中的日期和 E 列中的时间,格式为“dd.mm.yyyy”和“hh:mm”:
D 列与 01.01.2022
E 列“09:30”

我需要与不同的工作表进行比较,它们是这种格式的。

虽然我设法将日期和时间分成两列,但时间格式是错误的。

我发现建议使用 Int() 获取日期,然后减去以获取时间,但是我的日期似乎是字符串。我尝试使用 Cdate 函数将我的列格式化为 Date 数据类型,但这导致了错误。

由于我不一定需要具有此数据类型的值,因此我认为我可以使用 Left() 和 Right() 函数。这首先给出了一个问题,但通过在两者之间包含一个字符串,我越来越接近我想要的。

Dim iAircol As Integer
Dim lastrow As Integer
Dim i As Integer
Dim str1 As String
Dim str2 As String
Dim spacepos as Int

iAircol= Worksheets(ws).Cells.Find(What:="Airdate", SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column
lastrow = Range("A" & Rows.Count).End(xlUp).Row

For i = 2 To lastrow
    spacepos = InStr(Cells(i, iAircol), " ")
    str1 = Left(Cells(i, iAircol).Value, spacepos)
    Cells(i, iAircol + 1) = str1
    str2 = Left(Right(Cells(i, iAircol).Value, Len(Cells(i, iAircol)) - spacepos), 6)
    Cells(i, iAircol + 2) = str2
Next i

时间值还在"hh:mm:ss":

我给单元格提供了总时间的前 5 个字符,所以不知道为什么它又以全部 8 个字符结束,现在这应该是一个字符串,但 Debug.Print 给了我类型“日期”日期和时间的 Double。

【问题讨论】:

  • 日期不是字符串而是数字。与时间相同。您可以更改单元格的格式以匹配您想要的格式,但数量将保持不变。
  • 我知道日期是数字,但是我文件中的日期似乎是字符串(我从外部来源获取它们)。当我检查 TypeName 时,它​​至少给了我字符串。

标签: excel vba date


【解决方案1】:

使用DateValueTimeValue,它们正是为此:

Cells(i, iAircol + 1) = DateValue(Cells(i, iAircol))
Cells(i, iAircol + 2) = TimeValue(Cells(i, iAircol))

然后将您喜欢的格式应用于两个日期和时间列,因为它们将保存真正的 DateTime 值,而不是文本。

【讨论】:

  • 非常感谢!!!这节省了我的时间,正是我所需要的:)
【解决方案2】:

请使用下一个函数根据需要拆分字符串:

Function splitDateTime(strTime As String) As Variant
   Dim d As Date, t As Date, arrD
   arrD = Split(Split(strTime, " ")(0), "-")
   
   d = DateSerial(CLng(arrD(0)), CLng(arrD(1)), CLng(arrD(2)))
   t = CDbl(CDate(Format(Split(strTime, " ")(1), "hh:mm")))
   splitDateTime = Array(d, t)
End Function

可以这样测试:

Sub testSplitDateTime()
   Dim arr, ac As Range
   
   Set ac = ActiveCell 'in the active cell should be the string to be split/converted...
   arr = splitDateTime(ac.value)
   ac.Offset(0, 2).EntireColumn.NumberFormat = "HH:mm"
   Range(ac.Offset(0, 1), ac.Offset(0, 2)).value = arr   
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 2021-11-08
    • 2018-08-28
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多