Excel VBA编译错误:预期的子,函数或属性

时间:2014-08-05 14:36:35

标签: excel vba excel-vba

我在Excel VBA中遇到编译错误,其中显示了预期的子,函数或属性。我正在使用的函数如下所示,它试图在Excel中复制rate函数。 谢谢你的帮助。

Function rate_m(nper As Double, pmt As Double, pv As Double, fv As Double, types As Double, guess As Double) As Variant
    Dim y, y0, y1, x0, x1, f, i As Double
    Dim FINANCIAL_MAX_ITERATIONS As Double
    Dim FINANCIAL_PRECISION As Double

    If IsNull(guess) Then guess = 0.01
    If IsNull(fv) Then fv = 0   
    If IsNull(types) Then types = 0

    FINANCIAL_MAX_ITERATIONS = 128 'Bet accuracy with 128
    FINANCIAL_PRECISION = 0.0000001 '1.0e-8

    y , y0, y1, x0, x1, f, i = 0
    rate_m = guess

    If Abs(rate_m) < FINANCIAL_PRECISION Then
        y = pv * (1 + nper * rate_m) + pmt * (1 + rate_m * types) * nper + fv
    Else
        f = Exp(nper * Log(1 + rate_m))
        y = pv * f + pmt * (1 / rate_m + types) * (f - 1) + fv

        y0 = pv + pmt * nper + fv
        y1 = pv * f + pmt * (1 / rate_m + types) * (f - 1) + fv
    End If

    'find root by Newton secant method
    i , x0 = 0
    x1 = rate_m

    While Abs(y0 - y1) > FINANCIAL_PRECISION & i < FINANCIAL_MAX_ITERATIONS
        rate_m = (y1 * x0 - y0 * x1) / (y1 - y0)
        x0 = x1
        x1 = rate_m

        If Abs(rate_m) < FINANCIAL_PRECISION Then
            y = pv * (1 + nper * rate_m) + pmt * (1 + rate_m * types) * nper + fv
        Else
            f = Exp(nper * Log(1 + rate_m))
            y = pv * f + pmt * (1 / rate_m + types) * (f - 1) + fv
        End If

        y0 = y1
        y1 = y
        i = i + 1
    Wend
End Function

2 个答案:

答案 0 :(得分:2)

有几件事......

首先,你必须单独分配每个变量......就像这样:

y = 0
y0 = 0
y1 = 0
x0 = 0
x1 = 0
f = 0
i = 0

其次,您可能希望将DIM变量全部设为Double。不幸的是,这一行:

Dim y, y0, y1, x0, x1, f, i As Double

仅将i声明为Double,其他所有人都为Variant。您需要单独声明每个,如下所示:

Dim y As Double
Dim y0 As Double
Dim y1 As Double
Dim x0 As Double
Dim x1 As Double
Dim f As Double
Dim i As Double

答案 1 :(得分:1)

每个 IF 结束如果(除非在一行中)和在...循环结束。您可能想看看VBA的语法:
http://msdn.microsoft.com/en-us/library/office/ee814737(v=office.14).aspx

编辑:您必须单独声明变量,而不是:     y,y0,y1,x0,x1,f,i = 0

你可以这样做:
y = 0
y0 = 0
y1 = 0
x0 = 0
x1 = 0
f = 0
i = 0