VBA:For循环退出而不返回值

时间:2016-12-02 14:33:15

标签: excel-vba vba excel

我有以下用于使用随机过程模拟股票价格的代码

C:/Users/Ghenja/AppData/Local/opencv/build/OpenCVConfig.cmake

在这段代码中,我通过在Next处放置一个断点来运行调试,整个For循环工作正常。问题是在完成循环后函数退出并且单元格中显示Function varswap1(s0, r0, sigma0, t) As Double Rnd (-10) Randomize (999) Dim i As Integer, j As Integer, r As Double Dim stock() As Double, dt As Double Dim per As Integer per = WorksheetFunction.Round(t * 252, 0) ReDim stock(per) stock(1) = s0 dt = 1 / 252 For i = 1 To per stock(i + 1) = stock(i) * Exp((r0 - 0.5 * sigma0 ^ 2) * dt + sigma0 * Sqr(dt) * WorksheetFunction.NormSInv(Rnd())) Next varswap1 = WorksheetFunction.Average(stock) End Function 错误。

我无法弄清楚这段代码有什么问题。 如果有人能帮助我,我将感激不尽。

1 个答案:

答案 0 :(得分:0)

试试这个:

Const n As Integer = 252

Function varswap1(s0, r0, sigma0, t) As Double
  Rnd (-10)
  Randomize (999)

Dim i As Integer, j As Integer, r As Double
Dim stock() As Double, dt As Double
Dim per As Integer
  per = WorksheetFunction.Round(t * n, 0)

  ReDim stock(per)
  stock(0) = s0  ' First item in the array has index 0
  dt = 1# / n    ' Avoid integer division, 1/252 = 0

  For i = 1 To per
    'Each stock depends on the previous stock value:
    stock(i) = stock(i - 1) * Exp((r0 - 0.5 * sigma0 ^ 2) * dt + sigma0 * Sqr(dt) * WorksheetFunction.NormSInv(Rnd()))
  Next

  varswap1 = WorksheetFunction.Average(stock)
End Function

我看到了两个问题和一个建议。

其中一个数组stock来自0..252,但您将值分配给1..253,以便崩溃。

还有一个可能的整数除法导致dt=0.0。我更新了定义,使意图明确表示在从整数转换为double之后进行除法。最后,我将幻数252移动到常数。

相关问题