我们的会计软件日期为07262013,为文本。要将此文本字符串转换为日期格式,我通常会键入公式
=IF(A2>10000000,DATE(VALUE(RIGHT(A2,4)),VALUE(LEFT(A2,2)),VALUE(MID(A2,3,2))),
DATE(VALUE(RIGHT(A2,4)),VALUE(LEFT(A2,1)),VALUE(MID(A2,2,2))))
每次我导出数据。我想编写一个自定义函数=convert_text(text)
来完成相同的功能。
我想出了
Function Convert_Date(text)
If text > 10000000 Then
Convert_Date = Application.Date(Application.Value(Application.Right(text, 4)), Application.Value(Application.Left(text, 2)), Application.Value(Application.Mid(text, 3, 2)))
Else
Convert_Date = Application.Date(Application.Value(Application.Right(text, 4)), Application.Value(Application.Left(text, 1)), Application.Value(Application.Mid(text, 2, 2)))
End Function
提前非常感谢! 利
答案 0 :(得分:1)
您正在寻找以下内容:
Function Convert_Date(text)
' assuming text is of the form mmddyyyy
' or mddyyyy
Dim year As Integer, month As Integer, day As Integer, L As Integer
L = Len(text)
year = Val(Right(text, 4))
day= Val(Mid(text, L - 5, 2))
If L = 7 Then month= Left(text, 1) Else month= Left(text, 2)
' >>>>> the next line is there for debugging;
' >>>>> take it out once you are happy with the result
MsgBox "year: " & year & "; month: " & month & "; day: " & day
Convert_Date = DateSerial(year, month, day)
End Function
返回“日期序列号”。然后,您可以使用所需的日期格式格式化单元格,然后就可以了。请注意,使用年,月,日的显式提取可使代码更具可读性。
注意 - 如果您想要更通用,可以将格式指定为可选的第二个字符串;例如ddmmyyyy
在这种情况下,您可以搜索这些字符并使用它来正确提取日期:
Function Convert_Date(text, Optional formatString)
' assuming text is of the form mmddyyyy
' alternatively specify the format with the second parameter
Dim L As Integer, ii As Integer
Dim yearString As String, monthString As String, dayString As String
If IsMissing(formatString) Then formatString = "ddmmyyyy"
L = Len(text)
For ii = 1 To L
c = Mid(formatString, ii, 1)
t = Mid(text, ii, 1)
If c = "d" Then dayString = dayString & t
If c = "m" Then monthString = monthString & t
If c = "y" Then yearString = yearString & t
Next ii
Convert_Date = DateSerial(Val(yearString), Val(monthString), Val(dayString))
End Function
答案 1 :(得分:0)
=DATE(YEAR(A1),MONTH(A1),DAY(A1))
没有必要!它已经存在:)如果您需要在fx中执行此操作,它可能看起来像这样
function convert_date(text As String) As Date
convert_date = EVALUATE("DATE(YEAR(text),MONTH(text),DAY(text))")
end function
答案 2 :(得分:0)
我能想到的最快
Public Function FUNNYDATE(text As String) As Date
Dim padded As String
padded = Format(text, "00000000")
FUNNYDATE = DateSerial(Right(padded, 4), Left(padded, 2), Mid(padded, 3, 2))
End Function
此外,不是你这样做,但是如果它出现在某些建议的解决方案中,我会避免使用DATEVALUE(“mm-dd-yyyy”),因为它的结果取决于用户的语言环境。始终坚持DATESERIAL(年,月,日)