Home » excel » excel – Getting error message from range.formula function

excel – Getting error message from range.formula function

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have tried to run this sub for generating a random sample, but when I try to fix the formula I get only an error message in the cells ” Name”, in state of gettings the values.
Can someone help?

This is the code, thanks:

Option Explicit

Sub Simulation()

    Dim iSize As Integer, pMean As Double, pSD As Double, iBins As String

    iBins = 15
    iSize = InputBox("New sheet: The size of your sample:", , 100)
    pMean = InputBox("New sheet: The mean of yoursample:", , 10)
    pSD = InputBox("New sheet: The SD of your sample:", , 0.2)

    Set oWS = Worksheets.Add(, ActiveSheet)

    Range(Cells(1, 1), Cells(iSize, 1)).Formula = "=Application.WorksheetFunction.NormInv(Rnd(), " & pMean & " , " & pSD & ")"
    Range(Cells(1, 1), Cells(iSize, 1)).Formula = Range(Cells(1, 1), Cells(iSize, 1)).Value

    Range("E1") = Application.WorksheetFunction.Average(Columns(1))
end sub
How to&Answers:

If you type =Application.WorksheetFunction.NormInv(Rnd(), 10, 0.2) in a worksheet cell, you’ll get the exact same #NAME? error, because Excel doesn’t know about any Application.WorksheetFunction.NormInv function.

Excel isn’t VBA, VBA isn’t Excel – VBA is hosted in Excel, and your VBA project references Excel’s type library, which defines things like Application, Range, and WorksheetFunction.NormInv.

When writing to Range.Formula, you want that value to be exactly what you would type in Excel’s formula bar.

Also you’ll want to properly qualify these Range and Cells calls:

With oWS
    .Range(.Cells(1, 1), .Cells(iSize, 1)).Formula = "..."
End With

Where "..." looks exactly like it does in PaichengWu’s answer, except you want to use Excel’s RAND function instead of VBA’s Rnd function.

Answer:

Try

Range(Cells(1, 1), Cells(iSize, 1)).Formula = "=NormInv(Rand(), " & pMean & " , " & pSD & ")"