Search code examples
vbaexceldatetimesubtraction

Subtract date and time from two NOWs


I am trying to create a VBA code that calculates elapsed time after a certain action checkbox is clicked.

  1. On clicking checkbox1 NOW is captured and display in textbox1.
  2. on clicking checkbox2, NOW is displayed in textbox3 and the elapsed time (value in textbox3 - value in textbox1) needs to be displayed in textbox4 in hours and minutes format accurately. Which I am unable to do after trying and Googling for different codes.

I have remained on and off with VBA, so I am not fluent. Can someone help me with the piece of code?


Dim X1 As Date


Private Sub CheckBox1_Click()

X1 = Now

If CheckBox1.Value = True Then TextBox1.Value = Now
If CheckBox1.Value = False Then TextBox1.Value = Null

If CheckBox1.Value = True Then TextBox2.Value = "00:00"
If CheckBox1.Value = False Then TextBox2.Value = Null


End Sub

Private Sub CheckBox2_Click()

Dim X2 As Date
Dim X3 As Date
Dim X4 As Date

X2 = Now

If CheckBox2.Value = True Then TextBox3.Value = Now
If CheckBox2.Value = False Then TextBox3.Value = Null
If CheckBox2.Value = False Then TextBox4.Value = Null


X3 = X2 - X1
TextBox4.Value = X3

End Sub

Solution

  • format the x3 value
    

    change the last code line as below

    TextBox4.Value = Format(X3, "hh:mm:ss")