这是我的简单思路,未经测试Private Sub …… 结果 = Format(Right(prvToDate("要转换的字符串"), 8), "####-##-##") End SubPrivate Function prvToDate(strDate As String) Dim lngI As Long For lngI = 1 To Len(strDate) If IsNumeric(Mid(strDate, lngI, 1)) Then prvToDate = prvToDate & Mid(strDate, lngI, 1) End If Next prvToDate = "20" & prvToDate '具体根据你的需要判断是“19”还是“20”什么的 End Function
?autodate("060612") 2006-06-12 ?autodate("2006.06.12") 2006-06-12 ?autodate("2006/06/12") 2006-06-12'自动格式化日期 Function AutoDate(ByVal str As String) As String Dim i As Integer Dim subStr As String
If IsDate(str) Then AutoDate = Format(CDate(str), "yyyy-mm-dd") Else For i = 1 To Len(str) subStr = Mid(str, i, 1) If InStr("0123456789", subStr) = 0 Then str = Replace(str, subStr, "") Exit For End If Next If Len(str) = 6 Then str = "20" & str End If AutoDate = Format(str, "####-##-##") End If End Function
结果 = Format(Right(prvToDate("要转换的字符串"), 8), "####-##-##")
End SubPrivate Function prvToDate(strDate As String)
Dim lngI As Long
For lngI = 1 To Len(strDate)
If IsNumeric(Mid(strDate, lngI, 1)) Then
prvToDate = prvToDate & Mid(strDate, lngI, 1)
End If
Next
prvToDate = "20" & prvToDate '具体根据你的需要判断是“19”还是“20”什么的
End Function
2006-06-12
?autodate("2006.06.12")
2006-06-12
?autodate("2006/06/12")
2006-06-12'自动格式化日期
Function AutoDate(ByVal str As String) As String
Dim i As Integer
Dim subStr As String
If IsDate(str) Then
AutoDate = Format(CDate(str), "yyyy-mm-dd")
Else
For i = 1 To Len(str)
subStr = Mid(str, i, 1)
If InStr("0123456789", subStr) = 0 Then
str = Replace(str, subStr, "")
Exit For
End If
Next
If Len(str) = 6 Then
str = "20" & str
End If
AutoDate = Format(str, "####-##-##")
End If
End Function
而不是想一个什么“万能”的函数来转换。这是根本不切实际的。
比如要是给你个 060304
如果你不加事先限定的话,到底是2006年3月4日?还是2006年4月3日?还是2004年6月3日?还是2004年3月6日?。严格限定输入格式可以让你的程序更加强壮。