Dim boucle As Boolean 'mémorise la variable
Sub Arret() 'bouton de sécurité
boucle = False
End Sub
Sub Tirages()
Dim cible As Range, etm#, Ntirages&, tirage&, col%, matin, soir, nuit, n&, c As Range, b As Byte, a
Application.ScreenUpdating = False
boucle = True
Set cible = [L1] 'à adapter
etm = [N1] 'à adapter, écart-type maximum
Ntirages = 100 'modifiable
With [B2:H13] 'à adapter
.Columns(1).EntireColumn.Insert
.Columns(0) = "=RAND()" 'ALEA()
Do
DoEvents 'permet le clic sur le bouton Arrêt
tirage = 0
For col = 1 To 7
.Columns(col) = 0 'RAZ
matin = .Cells(17, col): soir = .Cells(18, col): nuit = .Cells(19, col) 'lignes à adapter
n = 0
For Each c In .Columns(col).Cells
If c(1, 0) <> 0 Or IIf(col < 7, c(1, -1) = 0, False) Then
n = n + 1
b = IIf(n <= matin, 1, IIf(n <= matin + soir, 2, IIf(n <= matin + soir + nuit, 3, 0)))
If c(1, 0) & b = "31" Or c(1, 0) & b = "32" Then col = col - 1: tirage = tirage + 1: Exit For
c = b
End If
Next c
If tirage = Ntirages Then
If Not boucle Then .Value = "": .Columns(0).EntireColumn.Delete: MsgBox " Recommencez...": Exit Sub
Exit For
End If
.Columns(0).Resize(, col + 1).Sort .Columns(0), Header:=xlNo 'tri aléatoire
Next col
Loop While boucle And cible > etm Or tirage = Ntirages 'recherche des écarts-types < etm
.Columns(0).EntireColumn.Delete
'---formats personnalisés---
a = Array("""repos""", """matin""", """soir""", """nuit""")
For n = 0 To 3
.Replace n, ""
With .SpecialCells(xlCellTypeBlanks): .NumberFormat = "[=" & n & "]" & a(n): .Value = n: End With
Next n
End With
End Sub