让VBA转换不同的date格式

我有一个VBAmacros读取Excel文件,并需要在那里处理数据,包括一些date。 但是,根据导出这些文件的用户,这些表中的date可能会写成YYYYMMDDMM/DD/YYYYDD.MM.YYYYM/D/YYYY等等。 全部只是格式化为文本。

到目前为止,我已经尝试parsingstring并创build一个新的date。 当我遇到更多的异国情调的date,如M/DD/YYYYD.MM.YY ,我的代码变得非常大,看起来不是很优雅。 我search了,但我找不到任何标准化的方式或函数来检测这几种date格式,并相应地转换它们。

我是否错过了一些东西,或者只是parsingstring是唯一可靠的方法呢?

试试这个代码 – 它会转换任何以下格式: DD.MM.YYYYDD.MM.YYYYYYMMDDMM/DD/YYYYMM/DD/YYM/D/YYYYM/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 

请注意,只要位数匹配且结果date有效,此代码将将MM.DD.YYYY解释为DD.MM.YYYY等等。