生成随机数时输入不匹配错误

时间:2015-04-16 07:59:38

标签: excel vba excel-vba

当我生成随机数时,我有时会得到(并非总是)以下错误:

  

运行时错误' 13':类型不匹配。

Z = Sqr(time) * Application.NormSInv(Rnd())行(和第二个for循环结束)。

为什么我会收到此错误?

我认为这与它包含Rnd()的事实有关。

Sub asiancall()
'defining variables
Dim spot As Double
Dim phi As Integer
Dim rd_cont As Double
Dim rf_cont As Double
Dim lambda As Double
Dim muY As Double
Dim sigmaY As Double
Dim vol As Double

Dim implied_vol As Double
Dim spotnext As Double
Dim time As Double
Dim sum As Double
Dim i As Long
Dim mean As Double
Dim payoff_mean As Double
Dim StDev As Double
Dim K As Double
Dim Egamma0 As Double
Dim mulTv As Double
Dim prod As Double
Dim U As Double
Dim Pois As Double
Dim Q As Double
Dim Z As Long
Dim gamma As Double
Dim payoff As Double
Dim payoff_sum As Double
Dim secondmoment As Double
Dim j As Long
Dim N As Long
Dim mu As Double
Dim sum1 As Double

'read input data
spot = Range("B3")
rd_cont = Range("C5")
rf_cont = Range("C4")
muY = Range("B17")
sigmaY = Range("B18")
lambda = Range("B16")
K = Range("F33")
implied_vol = Range("F35")
N = Range("F34")
vol = Range("B6")
'calculations

 sum_BS = 0
 payoff_BS = 0
 mean_BS = 0
 secondmoment_BS = 0
 For j = 1 To N
     spotnext = spot
     spotnext_BS = spot
     time = 0
     sum1 = 0
     time = 184 / (360 * 6)
     For i = 1 To 6

    '        'Merton uitvoeren
         Egamma0 = Exp(muY + sigmaY * sigmaY * 0.5) - 1
         mu = rd_cont - rf_cont
         mulTv = (mu - lambda * Egamma0 - implied_vol * implied_vol * 0.5) *   time
         sum = 0
         prod = 1
         Do While sum <= time
             U = Rnd()
             Pois = -Log(U) / lambda
             sum = sum + Pois
             Q = Application.NormInv(Rnd(), muY, sigmaY)
             gamma = Exp(Q) - 1
             prod = prod * (1 + gamma)
         Loop
         prod = prod / (1 + gamma)
         Z = Sqr(time) * Application.NormSInv(Rnd())
         spotnext = spotnext * Exp(mulTv + implied_vol * Z) * prod
         sum1 = sum1 + spotnext
     Next i
     mean = sum1 / 6
     payoff = Application.Max(mean - K, 0)
     payoff_sum = payoff_sum + payoff
     secondmoment = secondmoment + payoff * payoff
Next j

2 个答案:

答案 0 :(得分:0)

Rnd()返回值&gt; = 0且&lt; 1。

在某些时候它必然会返回0.当在Excel中输入0作为输入时,NormSInv会返回#NUM!

Excel错误。*通过Application.NormSInv(0)在VBA中调用时,它返回一个变量的子类型Error,其值为#34;错误2036&#34; (相当于#NUM! Excel错误)。

这样的Variant / Errors不能被隐式强制转换为数值(这是*运算符期望的值),因此在这种情况下,您将得到类型不匹配错误。

Rnd()碰巧返回0时,您才会收到此错误,这与您的观察结果一致,即错误有时发生。

*这是user3964075在对该问题的一个现已解散的评论中首次评论。

答案 1 :(得分:0)

跟进the community wiki answer I posted,可能的解决方案就是:

Function RndExcludingZero()
    Do
        RndExcludingZero = Rnd()
    Loop While RndExcludingZero = 0
End Function

用法:

Z = Sqr(time) * Application.NormSInv(RndExcludingZero())