0

我有以下格式的日期和时间:

7/12/2012 3:41

我只想保留日期。我试图编写一个函数来执行此操作,但 excel 只会将其识别为字符串,因此我很难编辑条目。如果有人可以帮助我提供功能或方向以仅泄露日期部分,将不胜感激。

我的预期应用程序类似于

  Public Function Change(X As Variant)
   '
   If X > Application.WorksheetFunction.Now() Then
   Change = 1
   End If
   '
  End Function
4

2 回答 2

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返回系统当前日期的函数。相同的

于 2013-10-21T06:19:02.080 回答
0

取决于您是在寻找日期还是字符串作为输出。以下是如何做到这两点。

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
于 2013-10-21T08:09:33.070 回答