Forum Discussion
brooij_bdr
Oct 03, 2019Copper Contributor
Random value in table with fixed proportion/ratio
 Hi,     I am making a pivot table aka database in excel. I have a column to fill in randomly with the values "Yes" or "No". I do know how to fill in random values, however I need a fixed proportion/r...
Subodh_Tiwari_sktneer
Oct 03, 2019Silver Contributor
You may try something like this and tweak it if required.
Sub RandomYesNo()
Dim y()         As Variant
Dim No          As Object
Dim it          As Object
Dim i           As Long
Dim lr          As Long
Dim NoCount     As Long
'Defining the No Ratio %, change it if required
Const ratioNo   As Double = 0.6
'Finding last row with data in the data set
'The below line finds the last row with data in column A
lr = Cells(Rows.Count, 1).End(xlUp).Row
NoCount = Round((lr - 1) * ratioNo, 0)
ReDim y(1 To lr - 1, 1 To 1)
Set No = CreateObject("Scripting.Dictionary")
Do While No.Count < NoCount
    i = WorksheetFunction.RandBetween(2, lr)
    If Not No.exists(i) Then
        No(i) = ""
        y(i - 1, 1) = "No"
    End If
Loop
For i = 1 To UBound(y, 1)
    If y(i, 1) = "" Then y(i, 1) = "Yes"
Next i
'Writing the Yes/No in the column B, change it if required
Range("B2").Resize(UBound(y, 1)).Value = y
End Sub
In the attached, click the button called "Generate Random Yes/No" on Sheet1 to run the code and it will generate Random Yes/No in column B.