'Excel VBA Code Works Stepping Through But Overflow Error 6 When Run

This problem has been written about quite a few times, but I've never found an answer to the problem of Excel VBA code working fine when stepping through line-by-line but failing when the macro is run.

I'm trying to round a Date to the nearest minute (get rid of seconds). Seems like it should be a simple problem, right? To simplify and isolate the problem, I've stripped the code down to eliminate all references to a worksheet.

The same problem happens if I use a static Date/Time or use Now(). The same problem happens with Option Explicit or without.

You can uncomment the commented lines to see the failure at various places.

How can I reliably convert a date/time in VBA to eliminate the seconds without an Overflow 6 error when the code runs? Note that I am getting the original date/time value from Now() in the macro, not from a cell on the spreadsheet. The rounded value will ultimately be placed in a cell on a worksheet, but for now, I've eliminated all worksheet integration.

UPDATE

This short snippet works without Overflow 6. I'm not sure what I was doing wrong with the original code.

Sub TestDate
    Dim dDate As Date

'   Store current date & time with seconds rounded off
    dDate = CDate(Round(Now() * 1440, 0) / 1440)
    Range("A1") = dDate
End Sub

Previous problematic code

Sub DateTimeDev2()
'   Round date to nearest minute
'   Works when you step through code
'   Fails on overflow when you run the code

    Dim dt1 As Date
    Dim dblDt1 As Double
    
    'dt1 = "3/8/22 10:35:40"
    dt1 = Now()
    
    Debug.Print "dt1 Double = " & CDbl(dt1)
'    Debug.Print "dt1 = " & dt1 ' Running macro fails here with Overflow 6
'    Debug.Print "dt1 = " & CDate(Round(CDbl(dt1) * 1440, 0) / 1440) ' Running macro fails here with Overflow 6
    Debug.Print vbCr

'   Coerce Date to Double and assign to double variable
'    dblDt1 = CDbl(dt1)  ' Running macro fails here with Overflow 6
'    Debug.Print "dblDt1 = " & dblDt1 ' Running macro fails here with Overflow 6
'    Debug.Print "cDate(dblDt1) = " & CDate(dblDt1) ' Running macro fails here with Overflow 6
    
End Sub


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source