Search code examples
arraysexcelfor-loopmontecarlovba

Store in array single value produced by each step in a for loop VBA


I have exactly the problem stated in this discussion:

Storing and Printing values in Array - VBA

but I need to see them through debug, not only print them.

Substantially, I created this code:

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

Anyway there are two problems here:

1) when I go through debug, into ArraydXi() I see it is stored only the last (the fifth in this case) dXi value of the for loop, while I want to be stored all the five dXi values of each step of the for loop and

2) consequently in the SumElements variable, there is no trace of the sum of the five elements that should be stored into the array.

May I ask any idea to solve this problem?


Solution

  • Please let me know wheter this solves the problem or not.

    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