将列拆分为日期和时间 vba

Split Column to Date and time vba

我是 VBA 的新手(我常用的编码语言是 python),我只是想将包含日期和时间组合的列拆分为两列,其中日期和时间是分开的。尽管我设法将它们分成两列,但格式总是以错误告终。让我快速告诉你我的意思:

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

我需要这种格式,因为稍后我需要与不同的 sheet 进行比较,它们是这种格式。

我找到了建议使用 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 为日期提供了“日期”类型,为时间提供了一个双精度...

如果你能向我解释一下后台发生了什么,以及如何解决我的问题,那就太好了。 在此先感谢,如果缺少任何信息,请告诉我,我会提供。

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

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

使用DateValueTimeValue,它们正是用于:

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

然后将您喜欢的 Format 应用于两个日期和时间列,因为这些将适用于 DateTime 值,而不是文本。