G’day,
I have a tricky problem with getting random numbers in sorted order according to how many I need by either VBA code or formula within VBA. This need is generated randomly between 1 and 10.
It looks something like this when it starts.

and here is the effect I had in mind where it shows sorted numbers according to how many failed in the example.

This is one attempt by VBA I did where cell J7 contains the random of how many I need but the numbers not quite sorted. I’m open to suggestions/feedback here. Many thanks.
Public Const BeCoolMachineCounter As String = "J7"
Public Const BeCoolMachineRange As String = "Q03:Q12"
'Generate the random data according to how many needed.
Call CreateNumbers(Range(BeCoolMachineRange), Range(BeCoolMachineCounter).Value)
Private Sub CreateNumbers(Which As Range, HowMany As Integer)
' Declaration of variables
Dim c As Range
Dim iCheck As Long
iCheck = 1
' Generate random failures based on the number of required for each supplier
For Each c In Which
If iCheck <= HowMany Then
c.Value = Random1to2192
iCheck = iCheck + 1
End If
Next c
End Sub
You could use an array formula in the destination range and a UDF returning the array.
It gives you exactly the result you’re showing.
So, the UDF :
and a sample formula :
(braces added by Excel)
You can of course simply call this UDF from a macro but IMHO using an array-formula could improve the user experience as all is transparent and the list is refreshed each time you change the count.
Note : the quick-sort implementation is from here : VBA array sort function?