Subtract Hours from Time Using VBA Change Event

bemp87

Board Regular
Joined
Dec 10, 2016
Messages
102
Hi Community - it's been a while since I did this, and I can't remember for the life of me how to add / subtract hours from time.

Here is a draft of the VBA code I have to perform expression:
VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)

If Target = Range("D6") Then
     Target.Value = Target.Value - 2
Else
      ' Do Nothing
End If

End Sub

This isn't performing the expression that I would hope. Essentially I will have users that will enter time based on a 12 hour format in column D based on Central Standard Time. After the user has made the change / entry the event should trigger and subtract (2) hours from the users entered time to reflect the time it would be based on Pacific Standard Time. Not sure what exactly I am missing.
 

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.
Its always best to enter time (and dates) in Excel serial time. And the cell will accept it as a date (if the user types is a space before AM or PM)

VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)

If Target = Range("D6") Then
     Application.EnableEvents = False
     Target.Value = Target.Value - TimeSerial(2,0,0)
     Target.Format = "h:mm AM/PM ""PT"""
     Application.EnableEvents = True
Else
      ' Do Nothing
End If

End Sub
 
Upvote 0
Thanks for the help! This is working as expected with one minor error. It seems there is an issue when calling the .Format property / method of the Target object. I'm getting the following error:

1596425895656.png


Here's the line of code when i run the debugger.
1596425922179.png
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,177
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top