存储在for循环VBA中由每个步骤生成的数组单值

时间:2018-04-05 16:44:07

标签: arrays excel excel-vba for-loop montecarlo vba

我完全有讨论中提到的问题:

Storing and Printing values in Array - VBA

但我需要通过调试来查看它们,而不仅仅是打印它们。

基本上,我创建了这段代码:

Sub Montecarlo()

Dim X0, Xi, T, dt, m, s, Zi, dXi As Double
Dim ArraydXi() As Variant

X0 = 10
T = 5
dt = 1
m = 0.01
s = 0.2

n = T / dt

For i = 1 To n
    Zi = Application.WorksheetFunction.Norm_S_Inv(Rnd())
    dXi = m * dt + s * (dt) ^ (1 / 2) * Zi
    ArraydXi() = Array(dXi)
Next

SumElements = Application.WorksheetFunction.Sum(ArraydXi())

Xi = X0 + SumElements

End Sub

无论如何,这里有两个问题:

1)当我进行调试时,进入ArraydXi()我看到它只存储了for循环的最后一个(在这种情况下为第五个)dXi值,而我想要存储所有for循环的每个步骤的五个dXi值和

2)因此在SumElements变量中,没有应该存储到数组中的五个元素之和的跟踪。

我可以问任何想法来解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

猜一点,但是你没有声明ArraydXi的大小,因此你没有将每个值存储在一个单独的元素中。试试这个。

Sub Montecarlo()

Dim X0, Xi, T, dt, m, s, Zi, dXi As Double
Dim ArraydXi() As Variant

X0 = 10
T = 5
dt = 1
m = 0.01
s = 0.2

n = T / dt

ReDim ArraydXi(1 To n)

For i = 1 To n
    Zi = Application.WorksheetFunction.Norm_S_Inv(Rnd())
    dXi = m * dt + s * (dt) ^ (1 / 2) * Zi
    ArraydXi(i) = dXi
Next

SumElements = Application.WorksheetFunction.Sum(ArraydXi)

Xi = X0 + SumElements

End Sub

答案 1 :(得分:0)

请让我知道这是否解决了这个问题。

Sub Montecarlo()

Dim X0, Xi, T, dt, m, s, Zi, dXi As Double
Dim ArraydXi() As Variant

X0 = 10
T = 5
dt = 1
m = 0.01
s = 0.2

n = T / dt

ReDim ArraydXi(n)
For i = 1 To n
    Zi = Application.Norm_S_Inv(Rnd())
    dXi = m * dt + s * (dt) ^ (1 / 2) * Zi
    ReDim Preserve ArraydXi(i)
    ArraydXi(i) = dXi
    Debug.Print ArraydXi(i)
Next

SumElements = Application.Sum(ArraydXi)

Xi = X0 + SumElements

End Sub