[英]How to convert text dates into date format like mm/dd/yyyy in Excel
我在 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 的日期設置。 他們可能在一個地區工作而在另一個地區失敗。
這是@PEH 解決方案的變體,使用 Win32 API 進行實際轉換:
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
Private Declare Function SystemTimeToVariantTime Lib "OleAut32.dll" _
(ByRef lpSystemTime As SYSTEMTIME, ByRef vbtime As Date) As Long
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
Dim udtST As SYSTEMTIME
Dim dtmDate As Date
With udtST
wYear = DateParts(2)
wMonth = NumericMonth
wDay = DateParts(0)
End With
If CBool(SystemTimeToVariantTime(udtST, dtmDate)) = True Then
ConvertDDMMMYYYYtoDate = dtmDate
Else
' Return this in case of an error
ConvertDDMMMYYYYtoDate = CDate(0)
End If
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.