gpt4 book ai didi

excel - 如何在 Excel 中将文本日期转换为日期格式,如 mm/dd/yyyy

转载 作者:行者123 更新时间:2023-12-04 21:27:29 26 4
gpt4 key购买 nike

我在 excel 单元格中以文本格式获取日期,例如 -



日期


123
2018 年 6 月 19 日

124
2019 年 9 月 9 日

125
2017 年 1 月 1 日


我希望这些文本日期看起来像 06/19/2018 , 09/09/2019 , 01/01/2017分别。
那么,我该怎么做呢?

最佳答案

将文本/字符串解释为日期的唯一可靠方法是将它们拆分并使用 DateSerial function 将它们转换为真实日期。 :

Option Explicit

Public Function ConvertDDMMMYYYYtoDate(ByVal DateString As String) As Date
Dim DateParts() As String
DateParts = Split(DateString, "-")


' convert text month into numeric month
Dim Months() As Variant
Months = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") ' these need to be adjusted according the language used for the text dates

Dim NumericMonth As Long

Dim i As Long
For i = LBound(Months) To UBound(Months)
If DateParts(1) = Months(i) Then
NumericMonth = i + 1
Exit For
End If
Next i

ConvertDDMMMYYYYtoDate = DateSerial(DateParts(2), NumericMonth, DateParts(0))
End Function

Public Sub Example()
Dim MyDate As Date
MyDate = ConvertDDMMMYYYYtoDate("19-Jun-2018")

' you can now write a real numeric date to a cell
Range("A1").Value = MyDate
' and format it the way you want
Range("A1").NumberFormat = "mm\/dd\/yyyy"
End Sub
请注意,这将需要调整 Months将文本日期写入语言的数组字符串。这将返回一个真实的数字日期,您可以将其写入单元格并使用 NumberFormat 以您想要的方式格式化.优点是您现在可以随时更改日期的格式(因为它是数字),甚至可以使用它进行计算。
任何其他解决方案可能看起来都有效,但它可能会失败,因为它们都依赖于 Windows 的日期设置。他们可能在一个地区工作而在另一个地区失败。

关于excel - 如何在 Excel 中将文本日期转换为日期格式,如 mm/dd/yyyy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67898308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com