You need to enable JavaScript to run this app. Excel VBA累计时长超24小时被识别为跨天时间,如何输出正确总时长?
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA累计时长超24小时被识别为跨天时间,如何输出正确总时长?

Excel VBA 累计工时超24小时跨天折算问题

现有代码单段时长计算逻辑运行正常,但多段有效时长累加、总时长超过24小时时,系统会自动将其识别为次日时间而非累计总时长。

具体计算场景

代码判定规则为:单元格内容包含CTC、OFF、LEAVE的,直接跳过不参与计算。逐行计算场景如下:

  • C3单元格值为0500_1145,对应单段时长6小时45分
  • D3单元格值为CTC,自动跳过进入下一格
  • E3单元格值为0500_1145,对应单段时长6小时45分
  • F3单元格值为0500_1145,对应单段时长6小时45分,以上三段累加时长为20小时15分
  • G3、I3单元格值为OFF,自动跳过
  • H3单元格值为1000_1800(ACP),对应单段时长8小时

问题现象

所有单段时长计算结果均准确,但所有有效时长累加后的正确总时长应为28小时15分,当前系统会自动按照跨天时间逻辑折算,最终返回总时长4小时15分的错误结果。
需求为调整代码逻辑,实现累计总时长超过24小时时直接输出正确的总时长(如28:15格式),而非跨天折算后的当日时间。

现有代码

Sub CalculateHourly()

Dim j As Long
Dim TextTime, wStart, wStop, midnight As String
Dim TrueTime, Temp As Date
Dim Parts As Variant
Dim lRow As Long
Application.Calculation = xlManual

midnight = "24" & ":" & "00"
 'Find the last non-blank cell in column A(1)
lRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 3 To lRow
For j = 3 To 9

    TextTime = ""
    'copy content of the cells
    TextTime = ThisWorkbook.Application.Sheets("Sheet1").Cells(i, j).Value
     'loop only of cell does not contain any text
    If InStr(1, TextTime, "CTC", vbTextCompare) = 0 And InStr(1, TextTime, "OFF", vbTextCompare) = 0 And InStr(1, TextTime, "LEAVE", vbTextCompare) = 0 _
     And Not IsEmpty(TextTime) Then
     
        Parts = Split(TextTime, "_")
        
        'Left(Parts(0), 2) of 0430-04
        'Right(Parts(0), 2) of 0430-30
        wStart = Left(Parts(0), 2) & ":" & Right(Parts(0), 2)
        'wStop = Left(Parts(1), 2) & ":" & Right(Parts(1), 2)
         wStop = Left(Parts(1), 2) & ":" & Mid(Parts(1), 3, 2)
        
        
        Debug.Print ("test : " & Format(wStart, "h:mm;@"))
        'If timeout is less than timein
        If wStart > wStop Then
        'Add 24 hours and make the diff
        TrueTime = 24 + CDate(CDate(CDate(Format(wStop, "h:mm;@")) - CDate(Format(wStart, "h:mm;@"))))
        
        Else
        'if timeout greater than timein
        TrueTime = CDate(CDate(CDate(Format(wStop, "h:mm;@")) - CDate(Format(wStart, "h:mm;@"))))
        
        End If
        
        If (Temp + TrueTime) > 24 Then
        TrueTime = 24 + Temp + TrueTime
        Else
        TrueTime = Temp + TrueTime
        End If
        
        
        Temp = TrueTime
    
    End If
    
Next j 'move to the number column in the same row

Cells(i, 10).Value = CDate(Format(Temp, "h:mm;@"))
Temp = Temp - Temp
Next i 'move to the next row

End Sub

内容的提问来源于stack exchange,提问作者Vishal Soodursun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 17:15:01