Need help with VBA for time change when result is different day

logandiana

Board Regular
Joined
Feb 21, 2017
Messages
107
I have column D of times that I need to subtract 5 hours from each.
I wrote the following code:
Code:
For i = 2 To LR
    If IsEmpty(data.Cells(i, 4)) = False Then
        data.Cells(i, 4) = DateAdd("h", -5, data.Cells(i, 4)
   End If
Next i
I wasn't sure if this was the best way or not, but it seemed to work just fine until it came to a line where the time was 3 am for example. I get an error.
This made me think of another problem though. If it is 3 am and I am subtracting 5 hours, assuming I can fix the error, for those instances I also need to subtract 1 day from column C, which has the date.
Can someone help here?
Thanks
 

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.
Try this:
Code:
    Dim dt As Date
    For i = 2 To LR
        If IsEmpty(data.Cells(i, 4).Value) = False Then
            dt = data.Cells(i, 3).Value + data.Cells(i, 4).Value
            data.Cells(i, 3).Value = Int(DateAdd("h", -5, dt))
            data.Cells(i, 4).Value = DateAdd("h", -5, dt) - Int(DateAdd("h", -5, dt))
        End If
    Next i
 
Upvote 0
A different angle than I was thinking, but it works! Thanks
Came up with this and it seems to work as well.
Code:
For i = 2 To LR
    If IsEmpty(data.Cells(i, 3)) = False And data.Cells(i, 4).Value < TimeValue("5:00:00") Then
        data.Cells(i, 3) = DateAdd("d", -1, data.Cells(i, 3))
    End If
Next I
For i = 2 To LR
    If IsEmpty(data.Cells(i, 4)) = False Then
        data.Cells(i, 4) = DateAdd("h", 19, data.Cells(i, 4))
    End If
Next i
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,337
Members
452,637
Latest member
Ezio2866

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