How to Display the Difference of Dates as Hours in VBA

Microsoft includes the VBA, or Visual Basic for Applications, programming language with most of the major Microsoft Office programs, like Excel, Access, PowerPoint and Word. VBA includes the "DateDiff" function, which will return the difference between two given dates. The function also allow you to choose the interval that the function will use from a list that includes years, days, hours, minutes and seconds.


    • 1

      Open the Microsoft Office product that you are using with VBA. Press "Alt" and "F11" to bring up the VBA console.

    • 2

      Click on the module that holds your VBA code from the list on the left side of the screen. When your code appears on the right side, place your cursor on the empty line in the code where you need to determine the difference between two dates.

    • 3

      Enter the following line into your VBA code:

      x = DateDiff("h", date1, date2)

      The "h" will ensure that you get your date difference in hours. "X" is a variable that you established earlier in the code, and you can change it to whatever variable you need it to be. "Date1" and "date2" are variables that will hold your date values. You can assign dates to these values earlier in the code. Instead of these variables, you can use "Now" to return the current date and time, "Date" to return the current date, or "Time" to return the current time. You can also manually enter a date and time, using the following format: "#mm/dd/yy hh:mm:ss#". Be sure to include the pound signs date so VBA can understand it.

    • 4

      Press "Enter" to access a new line of code. Enter the following code to display the difference between the dates:

      Msgbox x

      Change "x" to whatever variable you used at the front of the "Datediff" line. When you run the code, the difference between the dates will display in a small message box on the screen.

Related Searches


Related Ads

Check It Out

7 Tips for Photographing Your Kids on Halloween