简体   繁体   中英

MS Excel. VBA function returns #value

It would be nice if someone could explain what causes function above return #value error.

Public Function papild(x)
    Dim Sum As Double, A As Double, pi As Double,
    Sum = 0.5 - (x - pi / 4)
    A = -(x - pi / 4)
    pi = Application.WorksheetFunction.pi()
    Dim k As Integer, i As Integer
    k = 2
    i = 0
    Do While Abs(A) > 0.0001
        A = -A * 4 * A * A / (k + i) * (k + i + 1)
        Sum = Sum + A
        k = k + 1
        i = i + 1
    Loop
    paplid = Sum
End Function

Function takes x value from MS Excel cell and it's equal = -1.5708 (=-PI()/2 @Formula Bar)

In lines 3 and 4 you work with variable pi before setting it in line 5...

Could there be some brackets missing in your formula. It basically says:

A = -4A^3 * (k+i+1)/(k+1)

This obviously drifts to +/- infinite so your loop cannot end.

Also there is a comma too much in the second line and a spelling error in the last line (paplid instead of papild).

Have you tried debugging the code? When I run the code I get an overflow error @ the 6th iteration of the while loop starting with x = -1.5708. Number gets to large to fit inside variable .Other than that there are some minor things: missing As Double

Public Function papild(x) As Double

and unnecessary comma at the end

Dim Sum As Double, A As Double, pi As Double,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM