在Excel VBA中返回声明
所以,我在处理return语句的VBA编码时遇到了一些麻烦,我不明白是什么原因造成的。 我做了和其他人一样的回复声明,但似乎在某个地方有一个错误。 有人可以告诉我,我的函数的返回语句中的错误吗?
Public Function GetPay(Hours, RegHours, OTHours, PayRate, RegPay, OTPay) As Double Const MAX_REG_HOURS As Integer = 40 Dim RT As Double If Hours > MAX_REG_HOURS Then RegHours = 40 OTHours = Hours - MAX_REG_HOURS Else RegHours = Hours End If RegPay = CDbl(txtPayRate.Text) OTPay = CDbl(txtPayRate.Text * 1.5) Return RT = (RegPay * RegHours) + (OTHours * OTPay) End Function
你的function也过于复杂。 例如
-
OTHours
是函数中的计算,所以任何input都是不必要的,因为它将被覆盖 -
PayRate
未使用 -
RegPay
和OTPay
在函数中被覆盖 -
RegHours
是在函数中计算的
如下所示,可以简化函数计算和input
调用函数的例子
Sub B() MsgBox GetPay(41, 8.1, 12.1) MsgBox GetPay(44, CDbl(txtPayRate.Text), CDbl(txtPayRate.Text * 1.5)) End Sub
新function
Public Function GetPay(Hours, RegPay, OTPay) As Double Dim MAX_REG_HOURS As Long Dim RegHours As Double Dim OTHours As Double MAX_REG_HOURS = 40 RegHours = Application.Min(Hours, MAX_REG_HOURS) If Hours > MAX_REG_HOURS Then OTHours = Hours - MAX_REG_HOURS GetPay = (RegPay * RegHours) + (OTHours * OTPay) End Function