Calculate Difference Between two Times in Excel VBA

Calculate Difference Between two Times

Calculate Difference Between two Times in Excel VBA

Calculate Difference Between two Times in Excel VBA. Most of the time we wanted find differences of two Times. It’s a very regular and common exercise in Excel and VBA when dealing with times. We can find this using Excel VBA DateDiff function. In order to calculate we need start time and end time. It returns an integer value as a result. We use Excel DateDif function in Excel to perform same task.

Macro to Calculate Hours Between two Times in Excel VBA

Let us see the macro to calculate Difference Between two Times in Excel VBA.

'Calculate Difference Between two Times in Excel VBA
Sub VBA_Calculate_Difference_Between_Two_Times()
    
    'Variable declaration
    Dim sDate As Date, eDate As Date
    Dim iValue As Integer
    
    'Start Date
    sDate = "8:10:00"
    
    'End Date
    eDate = "12:10:00"
    
    iValue = DateDiff("h", sDate, eDate)
    
    'Display output on the screen
    MsgBox "The Difference Between two Times in hours : " & iValue, vbInformation, "Difference Between two Times in Hours"
    
End Sub

Here is the output screenshot of above macro.
Calculate Difference Between two Times

Instructions to use Macro

Here are the instructions to use above macro in Visual basic editor.

  • Open Visual Basic Editor(VBE) by clicking Alt +F11
  • Goto code window by clicking F7
  • Copy above specified macro or procedure
  • Paste above copied code in code window
  • Run macro by clicking F5 or Run command
  • You can see ouput on the screen
  • Find above specified output screenshot.

Related VBA Functions used in this article

We have used Date and DateDiff VBA functions. Click on below specified links to learn more about VBA functions.

VBA DateDiff Function VBA Time Function




Leave a Comment

Your email address will not be published. Required fields are marked *