1

I have a worksheet that calculates various values based on a random value and would like to use the law of large numbers to converge to an average for each calculation.

I am thinking of using VBA to execute the calculation 1000's of times and store the values in a list for averaging at the end. My current testing code only stores the original value after each iteration. ie Safety1 does not change even though the value in R36 changes.

Dim Safety1(0 To 10) As Long


For i = 0 To 10

    Safety1(i) = Sheet34.Range("R36").Value
    Debug.Print Safety1(i)

Next i

myAverage = Application.WorksheetFunction.Average(Safety1)

myAverage should be the converging average.

R36 contains the sum of other ranges, which contain values based on rand()

If there is a better way to do this, i am happy to listen.

Thanks in advance.

theotheraussie
  • 495
  • 1
  • 4
  • 14
  • That loop is going to loop the same cell data over and over again before the sheet recalcs. You need to look into a worksheet_change event that calls a routine with a static or global variable that won't be erased between iterations. – K.Dᴀᴠɪs Feb 04 '20 at 00:41

2 Answers2

0

This post resolved the problem. I needed to wait until the calculation process had completed before storing the value

theotheraussie
  • 495
  • 1
  • 4
  • 14
0

Please do sheet calculate like this:

Dim Safety1(0 To 10) As Long

Application.ScreenUpdating = False    

For i = 0 To 10
    Worksheets("Sheet34").Calculate
    Safety1(i) = Sheet34.Range("R36").Value
    Debug.Print Safety1(i)

Next i
Application.ScreenUpdating = True
myAverage = Application.WorksheetFunction.Average(Safety1)
user11982798
  • 1,878
  • 1
  • 6
  • 8