轉換和創造
CDATE()
CDate()
將任何資料型別的內容轉換為 Date
資料型別
Sub CDateExamples()
Dim sample As Date
' Converts a String representing a date and time to a Date
sample = CDate("September 11, 2001 12:34")
Debug.Print Format$(sample, "yyyy-mm-dd hh:nn:ss") ' prints 2001-09-11 12:34:00
' Converts a String containing a date to a Date
sample = CDate("September 11, 2001")
Debug.Print Format$(sample, "yyyy-mm-dd hh:nn:ss") ' prints 2001-09-11 00:00:00
' Converts a String containing a time to a Date
sample = CDate("12:34:56")
Debug.Print Hour(sample) ' prints 12
Debug.Print Minute(sample) ' prints 34
Debug.Print Second(sample) ' prints 56
' Find the 10000th day from the epoch date of 1899-12-31
sample = CDate(10000)
Debug.Print Format$(sample, "yyyy-mm-dd") ' prints 1927-05-18
End Sub
請注意,VBA 還有一個鬆散型別的 CVDate()
,其功能與 CDate()
功能相同,而不是返回日期型別 Variant
而不是強型別 Date
。當傳遞給 Date
引數或分配給 Date
變數時,CDate()
版本應該是首選的,當傳遞給 Variant
引數或分配給 Variant
變數時,首選 CVDate()
版本。這避免了隱式型別轉換。
DateSerial()
DateSerial()
函式用於建立日期。它返回指定年,月和日的 Date
。
句法:
DateSerial ( year, month, day )
年,月,日引數為有效整數(年份為 100 至 9999,月份為 1 至 12,日期為 1 至 31)。
例子
Sub DateSerialExamples()
' Build a specific date
Dim sample As Date
sample = DateSerial(2001, 9, 11)
Debug.Print Format$(sample, "yyyy-mm-dd") ' prints 2001-09-11
' Find the first day of the month for a date.
sample = DateSerial(Year(sample), Month(sample), 1)
Debug.Print Format$(sample, "yyyy-mm-dd") ' prints 2001-09-11
' Find the last day of the previous month.
sample = DateSerial(Year(sample), Month(sample), 1) - 1
Debug.Print Format$(sample, "yyyy-mm-dd") ' prints 2001-09-11
End Sub
請注意,DateSerial()
將接受無效日期並從中計算有效日期。這可以創造性地用於:
正例
Sub GoodDateSerialExample()
'Calculate 45 days from today
Dim today As Date
today = DateSerial (2001, 9, 11)
Dim futureDate As Date
futureDate = DateSerial(Year(today), Month(today), Day(today) + 45)
Debug.Print Format$(futureDate, "yyyy-mm-dd") 'prints 2009-10-26
End Sub
但是,嘗試從未經驗證的使用者輸入建立日期時,更有可能導致悲傷:
反面例子
Sub BadDateSerialExample()
'Allow user to enter unvalidate date information
Dim myYear As Long
myYear = InputBox("Enter Year")
'Assume user enters 2009
Dim myMonth As Long
myMonth = InputBox("Enter Month")
'Assume user enters 2
Dim myDay As Long
myDay = InputBox("Enter Day")
'Assume user enters 31
Debug.Print Format$(DateSerial(myYear, myMonth, myDay), "yyyy-mm-dd")
'prints 2009-03-03
End Sub