type-declaration character does not match declared data type

有些话、适合烂在心里 提交于 2021-02-04 16:25:26

问题


I keep getting this compile error based on the code below and I cannot figure it out for the life of me. Can you guys see what the problem is? It highlights the "p" when I go back to debug.

Thanks, R

Function EuroBin(S, K, T, rF, sigma, n, PutCall As String)
dt = T / n: u = Exp(sigma * Sqr(dt))
d = 1 / u: p = (Exp(rF * dt) - d) / (u - d)
EuroBin = 0
For i = 0 To n
    Select Case PutCall
        Case "Call":
            EuroBin = WorksheetFunction.Combin(n, i) * EuroBin + p^(i) * (1 - p) ^ (n - i) * WorksheetFunction.Max(S * u^(i) * d^(n - i) - K, 0)
        Case "Put":
            EuroBin = WorksheetFunction.Combin(n, i) * EuroBin + p^(i) * (1 - p) ^ (n - i) * WorksheetFunction.Max(K - S * u^(i) * d^(n - i), 0)
    End Select
Next i
EuroBin = Exp(-rF * T) * EuroBin
End Function

回答1:


For exponentiation, use

WorksheetFunction.Power(b, e)

instead of b^e, which seems to not work in VBA!

I'm saying that based on the test Debug.Print 2^2, which returns 2 2; Debug.Print WorksheetFunction.Power(2, 2) returns 4.




回答2:


Exponentiation works like you expect when you use the caret ^ in 32-bit Excel VBA. It fails to work as expected only in 64-bit Excel VBA.

In 64-bit Excel VBA, the caret is the type declaration character for the LongLong variable type. So when you enter a number followed by a caret or a variable name followed by the caret, VBA assumes you are talking about a LongLong constant or variable. Having made that assumption, it then tries to parse the expression and will give you either a run-time error or an unexpected result.

If you surround your constant or variable in parentheses like (a)^b or (2)^3, you may then use the caret to perform exponentiation in 64-bit Excel VBA. That is my recommended practice as it works as expected in 32-bit Excel VBA, too.

You may also notice that doubling the caret appears to exponentiate correctly--but that is only true for whole numbers. The first caret converts your whole number into a LongLong, while the second one performs the exponentiation. But you can't count on this behavior in general, because 2.3^^3 will raise a run-time error (because 2.3 can't be a LongLong). And if your code is used in both 32-bit and 64-bit Excel, doubling the caret will produce a run-time error in 32-bit Excel. For these reasons, I recommend against the practice of doubling the caret.



来源:https://stackoverflow.com/questions/25172899/type-declaration-character-does-not-match-declared-data-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!