[英]How to loop VBA row and not stopping at last row?
VBA 的新手,例如,如果我们通过输入框输入开始和结束月份,我正在尝试计算单元格的总小时数。 我想通过循环遍历每一行来计算单元格的总和,如果我输入 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 小时。
我应该如何循环,所以当我输入开始月份高于结束月份时,它将遍历该行? 提前致谢。
更换您的:
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
和:
For i = 2 To 13
If endMonth < startMonth Then
For j = 2 To 5
If Cells(i, 1).Value >= startMonth Or Cells(i, 1).Value <= endMonth Then
time = Cells(i, j).Value
overtime = time - 40
TotalOvertime = TotalOvertime + overtime
End If
Next j
Else
For j = 2 To 5
If Cells(i, 1).Value >= startMonth And Cells(i, 1).Value <= endMonth Then
time = Cells(i, j).Value
overtime = time - 40
TotalOvertime = TotalOvertime + overtime
End If
Next j
End If
Next i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.