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

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
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,216,052
Messages
6,128,509
Members
449,455
Latest member
jesski

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