2013-10-21 34 views
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 
+0

可能重複的[如何將日期時間轉換爲Excel中的日期?](http://stackoverflow.com/questions/8834080/how-can-i-convert-a-datetime-to- Excel中的日期) –

+0

@chrisneilsen:That [other question](http://stackoverflow.com/questions/8834080/how-can-i-convert-a-datetime-to-a-date-in- excel)是關於Excel公式的,因此被作爲離題(超級用戶)關閉,並正在刪除。這個問題是關於VBA的,所以不是重複的。 –

回答

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 
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返回系統當前日期的函數。 相同