我在這里遺漏了一些東西,我只是想不通。
函式被設計為接受兩個范圍。第一個范圍通常應該是一行乘七列(一周中的 7 天),第二個范圍是一個接受值的單元格。我在設定一個單元格的值時遇到了特別的問題。
我遇到的問題:rCell.Value = sngOT
我不斷收到“應用程式定義或物件定義的錯誤”。
我試過使用 rCell.Cells(1,1).Value = sngOT 并得到同樣的錯誤。
Function TotalHours(myRange As Range, rOT As Range) As Single
Dim sngHours As Single, sngNormal As Single, sngOT As Single
Dim rCell As Range
sngHours = 0
sngNormal = 0
sngOT = 0
For Each rCell In myRange
If rCell.Value > 8 Then
sngOT = sngOT rCell.Value - 8
sngNormal = sngNormal 8
Else
sngNormal = sngNormal rCell.Value
End If
Next rCell
If sngNormal > 40 Then
sngOT = sngOT (sngNormal - 40)
sngNormal = 40
End If
sngHours = sngNormal sngOT
Set rCell = rOT
rCell.Value = sngOT
Set rCell = Nothing
TotalHours = sngHours
End Function
任何幫助表示贊賞。
謝謝,韋斯特利
uj5u.com熱心網友回復:
像 Scott Craner 一樣,我假設在您的函式被用作 UDF 時拋出錯誤(否則您不會收到錯誤)。假設這是真的,有一種方法可以從 UDF 中更改其他單元格。
以下做你想要的。
注意:我進行了其他更改并添加了代碼注釋以說明原因。
Function TotalHours(rgHours As Range, rgWriteOT As Range) As Single
''' Declare hour values as doubles
''' Note: doubles declares as zero
Dim dbTotalHrs#, dbNormalHrs#, dbOTHrs#, rgCell As Range
''' Get normal hours (max 8 per day) and bandwidth OT (i.e. any hours > 8 on any given day)
For Each rgCell In rgHours
dbNormalHrs = dbNormalHrs WorksheetFunction.Min(rgCell, 8)
dbOTHrs = dbOTHrs WorksheetFunction.Max(rgCell - 8, 0)
Next rgCell
''' For any given week worked more than 40 hours: All hours after 40 are OT
If dbNormalHrs > 40 Then
dbOTHrs = dbOTHrs (dbNormalHrs - 40)
dbNormalHrs = 40
End If
''' Round results to 4 places (to avoid floating point rounding issues)
dbOTHrs = Round(dbOTHrs, 4)
dbTotalHrs = Round(dbNormalHrs dbOTHrs, 4)
''' Return Total Hours
TotalHours = dbTotalHrs
''' Write OT Hours to rgWriteOT (via SetOTValue)
With rgWriteOT
.Parent.Evaluate "SetOTValue(" & .Address(False, False) & "," & dbOTHrs & ")"
End With
End Function
''' Sub to set a value in another cell
Sub SetOTValue(Target As Range, Value#)
Target = Value
End Sub
所有這些都涵蓋了,重要的是要指出,您可以使用公式輕松完成所有這些:
假設您的每日作業時間在單元格 A2:G2 中,總小時數在單元格 H2 中,加班時間在 I2 中,以下執行您想要的操作:
總時數 (H2) 的=SUM(A2:G2)
公式:加班時數 (I2) 的公式:{=IF(H2>40,H2-40,SUM(IF(A2:G2>8,A2:G2-8)))}
注意I2 處的開始{和結束}:
o 這是一個陣列公式。您不輸入{或}
o 而是使用 Ctrl、Shift 和 Enter 來“提交”公式
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361272.html
上一篇:While回圈使Excel崩潰
下一篇:洗掉復制粘貼的范圍N次
