jeudi 24 septembre 2015

VBA Random number generation with user defined mean & Std dev

I am attempting to generate normally distributed random variables. I have a user input for the total number of variables (M), the number of sets of random variables (N). I am using the formula =NORM.INV(RAND(),0,1) and it works fine. However when I want to have a user input mean and std dev, I declare a variable for each. The cell that is bring referenced by the variable I put say a 0 for Mean and 1 for StdDev. The code will run, however the output of the random variables is the good old #NAME?. I do not understand why referencing a cell if just entering the formula on the worksheet works, but in VBA is does not.

Any help would be appreciated. I am probably overlooking something basic. Cheers

The Code is as follows.

Sub RandomNorm()

Dim WS_W As Worksheet: Set WS_W = ActiveWorkbook.Worksheets("Working") ' Sheet for calculations
Dim WS_Rand As Worksheet: Set WS_Rand = ActiveWorkbook.Worksheets("Random Generated") ' Sheet for random variable generation

Application.ScreenUpdating = False

Dim N As Long: N = WS_W.Range("B3").Value ' Number of random variable sets
Dim M As Long: M = WS_W.Range("C3").Value ' Number of simulations

WS_W.Select

Dim Mean As Double: Mean = WS_W.Cells(3, 4).Value ' Mean of Normal distribution
Dim StdDev As Double: StdDev = WS_W.Cells(3, 5).Value ' Standard Deviation of normal distribution

Dim i As Long
Dim j As Long

WS_Rand.Select
WS_Rand.Cells.Select
Selection.ClearContents ' Prepare for generation by clearing Generation sheet

For i = 1 To N
    For j = 1 To M
        WS_Rand.Cells(j, i).Select
        ActiveCell.FormulaR1C1 = "=NORM.INV(RAND(),Mean,StdDev)"
    Next
Next
End Sub




Aucun commentaire:

Enregistrer un commentaire