0

I need to read the time of day data from my computer using Excel's VBA editor and then parse the data into independent integers recording year, month, day, hour, minute, second separately.

In C# the function would be DateTime.Now; is there a VBA equivalent?

2 Answers 2

4

This should get you going:

Sub ShowTime()

    Dim myYear As Long
    myYear = Year(Now)
    Debug.Print myYear

    Dim myMonth As Long
    myMonth = Month(Now)
    Debug.Print myMonth

    Dim myDay As Long
    myDay = Day(Now)
    Debug.Print myDay

    Dim myHour As Long
    myHour = Hour(Now)
    Debug.Print myHour

    Dim myMinute As Long
    myMinute = Minute(Now)
    Debug.Print myMinute

    Dim mySecond As Long
    mySecond = Second(Now)
    Debug.Print mySecond

    Debug.Print Now

End Sub
2
  • 2
    Your sub is hiding the built in VBA.DateTime.Time property. You also implicitly declare everything but mySecond as Variant.
    – Comintern
    Mar 7, 2017 at 19:42
  • @Comintern fixed Mar 7, 2017 at 19:54
3

The VBA.DateTime module has everything you need.

As in Visual Studio, the VBE has its own object browser (F2 takes you there) - if you look at the contents of the VBA standard library, you'll notice a module named DateTime:

Object Browser

As with all standard library modules, VBA.DateTime members live in global scope, so you don't have to explicitly qualify them:

Debug.Print Now

Outputs exactly the same thing as:

Debug.Print VBA.DateTime.Now

...unless you have functions in your own project with identical names.

In C# DateTime.Now returns a DateTime struct, so you just do DateTime.Now.Year to get the year - however in VBA you can't call member methods on value types. Instead you use the VBA.DateTime module functions to retrieve each date part; they all take a Date parameter - Wujaszkun's answer shows them in action.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.