Forum Discussion
Sumit_Bhokare
Dec 23, 2021Brass Contributor
How to put random number from list
Hello Team, I have file in which there are few names in column A & Numbers are available in column C. What required is - can we have random single number from list C2:C18 at active cell after cl...
- Dec 23, 2021
Code for the command button:
Private Sub CommandButton1_Click() Static arr() Dim i As Long Dim j As Long Dim k As Long Dim tmp As Long If ActiveWindow.RangeSelection.CountLarge > 1 Then Exit Sub If Intersect(Range("B2:B18"), ActiveCell) Is Nothing Then Exit Sub If Application.Count(Range("B2:B18")) = 0 Then arr = Range("C2:C18").Value For k = 1 To 5 For i = 1 To 17 j = Application.RandBetween(1, 17) If j <> i Then tmp = arr(i, 1) arr(i, 1) = arr(j, 1) arr(j, 1) = tmp End If Next i Next k End If ActiveCell.Value = arr(ActiveCell.Row - 1, 1) End Sub
HansVogelaar
Dec 23, 2021MVP
Why not fill B2:B18 in one go?
- Sumit_BhokareDec 23, 2021Brass Contributor
HansVogelaar actually want doing this live during discussion hence one by one is required.
if its complicated then One go will also work, but one by one is preferred one 🙂
- HansVogelaarDec 23, 2021MVP
Code for the command button:
Private Sub CommandButton1_Click() Static arr() Dim i As Long Dim j As Long Dim k As Long Dim tmp As Long If ActiveWindow.RangeSelection.CountLarge > 1 Then Exit Sub If Intersect(Range("B2:B18"), ActiveCell) Is Nothing Then Exit Sub If Application.Count(Range("B2:B18")) = 0 Then arr = Range("C2:C18").Value For k = 1 To 5 For i = 1 To 17 j = Application.RandBetween(1, 17) If j <> i Then tmp = arr(i, 1) arr(i, 1) = arr(j, 1) arr(j, 1) = tmp End If Next i Next k End If ActiveCell.Value = arr(ActiveCell.Row - 1, 1) End Sub- Sumit_BhokareDec 23, 2021Brass Contributor
HansVogelaar Thank you for code, its working very well & very much appreciated.
Just few doubt, can you help to understand code by steps, if possible to you
and also not able to understand for what purpose k 1 to 5 is used.