将这个Excel公式转换成VBA代码(函数)

这是Excel中的公式,我试图转换为VBA代码:

=IFERROR(IF(effDate>curDate,0,IF((curDate-effDate+1)>nDays,nDays*(nSpend/365),((nSpend/365)*(curDate-effDate+1))-IF((curDate-effDate+1)-nDays>0,nSpend/365,0))),0) 

为了检查工作目的,这里是每个variables的值:

 effDate: 1/1/17 (dimmed as value) curDate: 3/31/17 (dimmed as value) nDays: 60 nSpend: 1600 

正确答案: 263

我试图让它工作两天,然后我用大约一百种不同的方法重新input,而且都没有工作。 该代码可能适用于一个单元格,但不能正确计算其他单元格。 或者根本不起作用。 这是我之前做的一个例子(函数的名字是APFcst):

 If effDate > curDate then APFcst = 0 Exit Function End if If (curDate - effDate + 1) > nDays then APFcst = nDays * (nSpend / 365) Else val1 = (nSpend / 365) * (curDate - effDatea + 1) end if if (curDate - effDate + 1) - nDays > 0 then val2 = nSpend / 365 else val2 = 0 end if APFcst = val1 - val2 Exit Function End if 

注意:一切正常,我遇到的问题只是翻译实际的公式,所以它会给我正确的答案。 请帮忙! 我一直盯着这么长时间,我可能看不到一个明显的解决scheme。

在注意到公式中的最后一次IF检查是多余的之后,下面简化一下你的公式:

 Function xAPFcst(effDate, curDate, nSpend, nDays) As double xAPFcst = IIf(effDate > curDate, 0, (nSpend / 365) * Application.Min(nDays, curDate - effDate + 1)) End function 

像这样的东西,也许有可能使用IIF来缩短它的接触,也许可以更有效地使用(nSpend / 365) ,稍后再看看。 我还没有正确testing。

 Function formula_test(dtCurrentDate As Date, dtEffectiveDate As Date, nDays As Long, nSpend As Double) As Double On Error GoTo eHandle If dtEffectiveDate > dtCurrentDate Then formula_test = 0 Else If ((dtCurrentDate - dtEffectiveDate) + 1) > nDays Then formula_test = nDays * (nSpend / 365) Else formula_test = ((nSpend / 365) * (dtCurrentDate - dtEffectiveDate + 1)) If (dtCurrentDate - dtCurrentDate + 1) - nDays > 0 Then formula_test = formula_test - nSpend / 365 End If End If End If Exit Function eHandle: formula_test = 0 End Function