Excel VBA 日期替换

Excel VBA Date Replacement

我在单元格中有一些日期作为 ISO 标准 (YYYY/MM/DD),但我被要求将其更改为 DD MMMMMMMM YYYY,例如2018 年 1 月 1 日。

一个单元格中有多个日期,我查了几个网站都找不到一些 VBA 我可以用来搜索 YYYY/MM/DD 格式并更改为 DD MMMMMMMM YYYY。

有人知道一些 VBA / 链接可以帮助一次更改所有日期而不是手动更改吗?

[

目前我已经尝试过,但我的 VBA 充其量只是新手,因此无法对以下解决方案进行逆向工程。 https://www.myonlinetraininghub.com/6-ways-to-fix-dates-formatted-as-text-in-excel

https://www.ozgrid.com/forum/.../excel.../93919-search-and-replace-date-with-vba

https://whosebug.com/.../find-replace-macro-that-properly-formats-a-date-cell

https://webcache.googleusercontent.com/search?q=cache:EIyJ2TGgqQMJ:https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-msoffice_custom-mso_2007/find-and-replace-date-in-vba-keeping-the-format/64377177-9b0f-4118-81ed-49d8f9ddc8f4+&cd=6&hl=en&ct=clnk&gl=uk

编辑: 使用下面的 Karthick 解决方案输出。唯一的问题是第一个日期已更改,但 ALT+Enter 的换行符丢失且格式不正确。

enter image description here

试试下面的公式

=TEXT(LEFT(C2,10),"DD MMMMMMMM YYYY")&MID(C2,11,LEN(C2))

输出

编辑

请使用 vba 代码获得您想要的结果。

Sub test()
    Dim a, b As String
    Dim str1, str2 As Long
    a = Range("C2").Value
    str1 = Split(a, Chr(10))
    str2 = UBound(str1)
    For i = 0 To str2
        b = b & Format(Left(str1(i), 10), "DD MMMM YYYY") & Mid(str1(i), 11, Len(str1(i))) & Chr(10)
    Next i
    Range("D2").Value = b
End Sub

VBA 输出

正则表达式将成为您的朋友。以下将匹配每个带有 / 作为分隔符的数字日期。然后它将找到每个匹配项并替换为 DateFormat 变量指定的格式。将 With ActiveSheet 更新为您的 sheet 的名称以明确声明它,您可能需要修改 rng 变量以适应您自己的范围

Option Explicit
Public Sub ConvertDateFormat()
    Dim rng As Range
    Dim RegExp As Object: Set RegExp = CreateObject("VBScript.RegExp")
    Dim DateFormat As String
    Dim c, d

    DateFormat = "DD MMMM YYYY"

    With ActiveSheet
        Set rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 3))
    End With

    With RegExp
        .Global = True
        .Pattern = "(\d{2,4}(\/|(?=\s)|\d$)){3}"

        For Each c In rng
            If .test(c) Then
                For Each d In .Execute(c.Value2)
                    c.Value2 = Replace(c.Value2, d, Format(d.Value, DateFormat))
                Next d
            End If
        Next c
    End With
End Sub