MOCKSTACKS
EN
Questions And Answers

More Tutorials









VBA Base functions

Retrieve System DateTime


VBA supports 3 built-in functions to retrieve the date and/or time from the system's clock.

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 Function


The Timer function returns a Single representing the number of seconds elapsed since midnight. The precision is one hundredth of a second.

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

Because Now and Time functions are only precise to seconds, Timer offers a convenient way to increase accuracy of time measurement:

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


Conclusion

In this page (written and validated by ) you learned about VBA Base functions . What's Next? If you are interested in completing VBA tutorial, your next topic will be learning about: VBA Data Types and Limits.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.