基本功能

檢索系統日期時間

VBA 支援 3 個內建函式,用於從系統時鐘中檢索日期和/或時間。

功能 退貨型別 返回值
現在 日期 返回當前日期和時間
日期 日期 返回當前日期和時間的日期部分
時間 日期 返回當前日期和時間的時間部分
Sub DateTimeExample()

    ' -----------------------------------------------------
    ' Note : EU system with default date format DD/MM/YYYY
    ' -----------------------------------------------------
    
    Debug.Print Now   ' prints 28/07/2016 10:16:01 (output below assumes this date and time)
    Debug.Print Date  ' prints 28/07/2016
    Debug.Print Time  ' prints 10:16:01
    
    ' Apply a custom format to the current date or time
    Debug.Print Format$(Now, "dd mmmm yyyy hh:nn")  ' prints 28 July 2016 10:16
    Debug.Print Format$(Date, "yyyy-mm-dd")         ' prints 2016-07-28
    Debug.Print Format$(Time, "hh") & " hour " & _
                Format$(Time, "nn") & " min " & _
                Format$(Time, "ss") & " sec "       ' prints 10 hour 16 min 01 sec
    
End Sub

定時器功能

Timer 函式返回一個 Single,表示自午夜以來經過的秒數。精度是百分之一秒。

Sub TimerExample()

    Debug.Print Time    ' prints 10:36:31  (time at execution)
    Debug.Print Timer   ' prints 38191,13  (seconds since midnight)

End Sub

由於 NowTime 功能僅精確到秒,Timer 提供了一種提高時間測量精度的便捷方法:

Sub GetBenchmark()
       
    Dim StartTime  As Single
    StartTime = Timer       'Store the current Time
    
    Dim i As Long
    Dim temp As String
    For i = 1 To 1000000    'See how long it takes Left$ to execute 1,000,000 times
        temp = Left$("Text", 2)
    Next i
    
    Dim Elapsed As Single
    Elapsed = Timer - StartTime
    Debug.Print "Code completed in " & CInt(Elapsed * 1000) & " ms"

End Sub

IsDate()

IsDate() 測試表示式是否是有效日期。返回 Boolean

Sub IsDateExamples()

    Dim anything As Variant
       
    anything = "September 11, 2001"

    Debug.Print IsDate(anything)    'Prints True
            
    anything = #9/11/2001#

    Debug.Print IsDate(anything)    'Prints True
   
    anything = "just a string"

    Debug.Print IsDate(anything)    'Prints False

    anything = vbNull
    
    Debug.Print IsDate(anything)    'Prints False
    
End Sub