Error Checking in Excel
Thanks Thanks:  0
Likes Likes:  0
Results 1 to 2 of 2

Thread: changing the counter in a loop

  1. #1
    New Member
    Join Date
    Apr 2002
    Posts
    6
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    hello I have written a little program below and it works as intended. How ever, I am completely stuck on the next step.

    Option Explicit

    Sub Example()
    Dim Ramdom As Single
    Dim i As Integer
    Dim j As Integer
    For j = 1 To 10
    For i = 1 To 7
    Ramdom = Rnd()
    ' generates a random number
    If Ramdom < 0.5 Then _
    Cells(i, j).Value = 0 _
    ' if the random number is < 0.5 a "0" results
    Else: Cells(i, j).Value = 1
    ' if the random number is > 0.5 a "1" results
    Next i
    Next j
    End Sub

    The program (try it if you want) produces a 7 x 10 table of numbers (0's and 1's).

    I would however like to put in an element whereby the 0 represents fail and 1 a pass.
    If there is a 0 I would like the next two numbers to be 0 (regardless of what the random number generator gives).

    I have tried changing the value of the counters (i & j) but always get bad results

  2. #2
    Board Regular giacomo's Avatar
    Join Date
    Feb 2002
    Posts
    1,802
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    Hi zviito,

    Here's what I came up with, I added some font coloring as a way to test the results. This can easily be removed.

    Sub Example2()
    Dim i, j, rand, zCounter, zFlag, color As Integer
    Range("a1:j7").Font.ColorIndex = color
    zFlag = 1
    For j = 1 To 10
    For i = 1 To 7
    rand = Application.WorksheetFunction.Round(Rnd(), 0) * zFlag
    Cells(i, j).Value = rand
    Cells(i, j).Font.ColorIndex = color
    If rand = 0 And zCounter < 2 Then
    zCounter = zCounter + 1
    zFlag = 0
    color = 3
    Else
    zCounter = 0
    zFlag = 1
    color = 0
    End If
    Next i
    Next j
    End Sub

    hope that helps,
    giacomo


Some videos you may like

User Tag List

Like this thread? Share it with others

Like this thread? Share it with others

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •