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 小時。
我應該如何回圈,所以當我輸入開始月份高于結束月份時,它將遍歷該行?提前致謝。
uj5u.com熱心網友回復:
更換您的:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/492542.html
上一篇:回圈瀏覽作業簿中的所有作業表
下一篇:如何將范圍值添加到vba中的鏈接
