You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA循环行计算加班总和 如何适配起始月大于结束月的跨年场景

VBA跨年区间加班时长求和逻辑适配问题

我是VBA新手,希望通过InputBox输入起始月份、结束月份后,计算对应区间的单元格总加班时长,通过逐行循环实现单元格数值求和。当前编写的程序仅在startMonth < endMonth时可正常运行,需要适配startMonth > endMonth的跨年场景(例如输入起始月为10、结束月为2时,需累加计算10月+11月+12月+1月+2月的数值)。

现有实现代码

Function TotalOvertime(startMonth As Integer, endMonth As Integer) As Integer

Dim i As Integer, j As Integer
Dim time As Integer, overtime As Integer

If (startMonth < 1 Or 12 < startMonth) Or (endMonth < 1 Or 12 < endMonth) Then
    TotalOvertime = -1
Else
    For i = startMonth + 1 To endMonth + 1
        For j = 2 To 5
            time = Cells(i, j).Value
            overtime = time - 40
            TotalOvertime = TotalOvertime + overtime
        Next j
    Next i
End If

End Function

Sub Kadai()

Dim startMonth As Integer, endMonth As Integer
Dim overtime As Integer

startMonth = InputBox("Enter starting month。")
endMonth = InputBox("Enter ending month。")
overtime = TotalOvertime(startMonth, endMonth)

If overtime <> -1 Then
    Call MsgBox(overtime)
Else
    Call MsgBox("Error")
End If

End Sub

数据样例

数据样例截图

当前运行表现

  • 输入1月到2月时,加班计算结果为40小时
  • 输入1月到1月时,加班计算结果为18小时

问题诉求

请问应如何调整循环逻辑,使得输入起始月份大于结束月份时可正常遍历对应行完成计算?在此先行致谢。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 07:16:01