0

我们的会计软件以文本形式导出日期为 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

非常感谢您!李

4

3 回答 3

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
于 2013-07-26T15:18:08.983 回答
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(年、月、日)

于 2013-07-26T19:15:52.230 回答
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
于 2013-07-26T15:18:01.507 回答