我有一个VBA宏,它读取Excel文件并需要处理其中的数据,包括一些日期。但是,根据导出这些文件的用户,这些工作表中的日期可能会写为YYYYMMDD
,MM/DD/YYYY
,DD.MM.YYYY
,M/D/YYYY
等等。所有内容都只是格式化为文本。
到目前为止,我已尝试解析字符串并创建新日期。当我遇到更多异国情调的日期时,例如M/DD/YYYY
或D.MM.YY
,我的代码变得非常大,看起来并不优雅。我搜索过,但是我找不到任何标准化的方法或功能来检测这些日期格式并相应地进行转换。
我是否遗漏了某些内容,或者只是解析字符串是唯一可行的方法?
答案 0 :(得分:4)
试用此代码 - 它会转换以下任何格式:DD.MM.YYYY
,DD.MM.YY
,YYYYMMDD
,MM/DD/YYYY
,MM/DD/YY
,{{1 },M/D/YYYY
。
您可以轻松添加其他格式,只需在M/D/YY
语句中添加更多转化规则。
If...ElseIf...
请注意,只要数字位数匹配且结果日期有效,此代码就会将Option Explicit
Private mStrLastPattern As String
Private mStrSourceDate As String
Private mDatResult As Date
Public Function fctDateFromString(strDate As String) As Date
mStrSourceDate = strDate
mDatResult = 0
If TryConvert("(^\d{2})\.(\d{2})\.(\d{4})$", "$2/$1/$3") Then 'DD.MM.YYYY
ElseIf TryConvert("(^\d{2})\.(\d{2})\.(\d{2})$", "$2/$1/20$3") Then 'DD.MM.YY
ElseIf TryConvert("(^\d{4})(\d{2})\.(\d{2})$", "$2/$3/$1") Then 'YYYYMMDD
ElseIf TryConvert("(^\d{2})/(\d{2})/(\d{4})$", "$1/$2/$3") Then 'MM/DD/YYYY
ElseIf TryConvert("(^\d{2})/(\d{2})/(\d{2})$", "$1/$2/20$3") Then 'MM/DD/YY
ElseIf TryConvert("(^\d{1})/(\d{1})/(\d{4})$", "0$1/0$2/$3") Then 'M/D/YYYY
ElseIf TryConvert("(^\d{1})/(\d{1})/(\d{2})$", "0$1/0$2/20$3") Then 'M/D/YY
End If
If mDatResult = 0 Then Debug.Print "Cannot find matching format for " & strDate
fctDateFromString = mDatResult
End Function
Private Function TryConvert(strFrom As String, strTo As String) As Boolean
If RegExMatch(strFrom) Then
mDatResult = RegExConvert("$1/$2/$3")
TryConvert = (mDatResult <> 0)
End If
End Function
Private Function RegExMatch(strPattern As String) As Boolean
mStrLastPattern = strPattern
With CreateObject("VBScript.RegExp")
.Pattern = strPattern
.IgnoreCase = True
.MultiLine = False
RegExMatch = .Test(mStrSourceDate)
End With
End Function
Private Function RegExConvert(strReplacePattern As String) As Date
On Error Resume Next
With CreateObject("VBScript.RegExp")
.Pattern = mStrLastPattern
.IgnoreCase = True
.MultiLine = False
RegExConvert = CDate(.Replace(mStrSourceDate, strReplacePattern))
If Err.Number Then
Err.Clear
RegExConvert = 0
End If
End With
End Function
解释为MM.DD.YYYY
,依此类推。