'random draw with condition
I want to modify my code to select only a range for example C2:C12, but I can't modify it and I want to apply the mm code on other tabs, is there a loop.
Here is my code
Sub test()
Const LIMIT = 1000000 ' limit iterations to solve
Dim wb As Workbook, ws As Worksheet
Dim lastrow As Long
Dim dict As Object, key, bLoop As Boolean
Dim n As Long, x As Long, sType As String
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "W", 3
dict.Add " ", 0
Set wb = ThisWorkbook
Set ws = wb.Sheets("Feuil4")
bLoop = True
With ws
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("C2:C8" & lastrow).Cells.Clear
Do While bLoop
' select random row
x = lastrow * Rnd() + 1
sType = Trim(.Cells(x, "B"))
' check if needed
If Len(.Cells(x, "C")) = 0 And dict(sType) > 0 Then
.Cells(x, "C") = "W"
dict(sType) = dict(sType) - 1
' check if finished
bLoop = False
For Each key In dict
If dict(key) > 0 Then bLoop = True
Next
End If
' avoid infinite loop
n = n + 1
If n > LIMIT Then
For Each key In dict.keys
Debug.Print key, dict(key)
Next
MsgBox "Too many iterations to solve", vbCritical, "limit=" & LIMIT
Exit Sub
End If
Loop
End With
MsgBox "Done in " & n & " iterations", vbInformation
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
