Function is_not_colored(n As Integer, m As Integer)
    Dim is_colred As Bool
    t = False
    While i < n
        While j < n
            If Cells(i + 1, j + 1).Font.ColorIndex <> 8 Then t = True
            j = j + 1
            i = i + 1
            j = 0
            is_colred = t
        End While
    End While
End Function

Sub test()

    Dim n As Integer, M1 As Double, M2 As Double, M3 As Double, U As Double, L As Integer
    Dim i As Integer, j As Integer, p As Double, m As Integer, Z As Integer


    n = 0


    Z = 30
    m = 5
    p = 0.5



    While is_not_colored(n)
        M1 = 4 * p * ((1 - p) ^ 3)
        M2 = M1 + 6 * (p ^ 2) * ((1 - p) ^ 2)
        M3 = M2 + 4 * (p ^ 3) * ((1 - p))
        U = Rnd
    End While

    If U <= M1 Then
        L = 1
    ElseIf U <= M2 Then
        L = 2
    ElseIf U <= M3 Then
        L = 3
    Else
        L = 4
    End If


    If L = 1 Then
        i = Abs(i - 1)
    ElseIf L = 2 Then
        i = i + 1
    ElseIf L = 3 Then
        j = Abs(j - 1)
    Else  j = j + 1

    End If


    If i >= m Then
        i = m - 1
    End If

    If j >= m Then
        j = m - 1
    End If


    Cells(i + 1, j + 1).Select
    With Selection.Interior
        .ColorIndex = 8
        .Pattern = xlSolid
    End With

    n = n + 1


End Sub
