VBA-日期时间字符串替换/替换

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

我有一列,其中包含来自Outlook的电子邮件的日期和时间。某些日期格式为January 2, 2020 4:15 PMJanuary-14-20 12:44 PMDecember-24-19 20:15 PM

我已尝试使用Replace和Substitute函数,Replace确实按定义工作,但是从字符串时间中删除了。我想将所有日期都设为2019-12-27 3:02 PM

sub Replace()
 Dim sString, searchString as String
 dim i, LastCell as Long

 LastCell = Range("C" & Rows.Count).End(xlUp).Row
 Set searchRng = Range("C3:C" & lastCell)

 For Each c In searchRng
   sString = c
   searchString = "-"

   If InStr(1, sString, searchString, vbTextCompare) > 0 Then
      i = InStr(1, sString, SearchString, vbTextCompare)
      i = InStr(i + 1, sString, SearchString, vbTextCompare)
      c.Offset(0, 1) = WorksheetFunction.Replace(sString, i, "19", " 2020")
   End If
 Next c
End Sub
excel vba datetime replace substitution
1个回答
2
投票

CDate会将字符串形式的日期/时间转换为可以格式化的实际日期/时间。

所以代码如下:

For Each c In rngSrc
    c.Offset(0, 1) = CDate(c)
    c.Offset(0, 1).NumberFormat = "yyyy-mm-dd h:mm AM/PM"
Next c

将转换

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.