我有以下格式的日期和时间:
7/12/2012 3:41
我想只保留此日期。我曾尝试编写一个函数来执行此操作,但excel只会将其识别为字符串,因此我无法编辑该条目。如果有人可以帮助我完成一个功能或方向,只能将其日期部分泄露出来,我们将不胜感激。
我的预期应用是
Public Function Change(X As Variant)
'
If X > Application.WorksheetFunction.Now() Then
Change = 1
End If
'
End Function
答案 0 :(得分:0)
使用Format
功能,如下所示:
Public Function Change(DateExp) As Date
'Format function lets you transform most data in your desired format.
'CDate handles any Date Expression conversion to Date data type.
'CStr handles any expression conversion to String data type
If IsMissing(ReturnType) Then
'Return as Date, default when ReturnType is not supplied
Change = Format(CDate(DateExp), "m/d/yyyy")
Else
If ReturnType = True Then
'Return as Date
Change = Format(CDate(DateExp), "m/d/yyyy")
ElseIf ReturnType = False Then
Change = Format(CDate(DateExp), "m/d/yyyy")
'Return as String
Change = CStr(Change)
Else
'Error out any values other than TRUE or FALSE
Change = CVErr(xlErrValue)
End If
End If
End Function
但如果您真的对仅返回日期感兴趣,请使用Today() Function
代替Now()
(对于WS)。
VBA中的等效功能是Date
函数,它返回系统的当前日期。
相同
答案 1 :(得分:0)
取决于您是在寻找Date还是String作为输出。以下是两种方法。
Dim strDateTime As String
Dim strDate As String
Dim s() As String
Dim pureDate As Date
strDateTime = "7/12/2012 3:41"
strDate = Split(strDateTime, " ")(0) ' "7/12/2012"
pureDate = CDate(strDate) ' 7 Dec 2012 (in my locale)
' ... results may be ambiguous depending on your locale
'Another way to get a Date, not blindly using CDate:
s = Split(strDate, "/")
' if date in day/month/year format:
pureDate = DateSerial(CInt(s(2)), CInt(s(1)), CInt(s(0))) ' 7 Dec 2012
' or, if date in month/day/year format:
pureDate = DateSerial(CInt(s(2)), CInt(s(0)), CInt(s(1))) ' 12 July 2012