Mari
Mari

Reputation: 37

VBA Run Loop until have X examples in MsgBox

Today I am trying to run basic loop using "for". I would like to run a loop till I get 20 random numbers between 26 - 28 in MsgBox.

Sub C7()

    Dim b As Integer
    Dim f As Single
    Dim ret As String

    For b = 1 To 20
        f = Rnd() * 28
        If f >= 26 And f <= 28 Then
        ret = ret & Str(f)

        End If
    Next b

        MsgBox ret

End Sub

Following code runs the loop 20-times and gives me all values between 26 - 28 (usually not more than 3). What I need is a code which will run the loop X-times until it gives me 20 numbers between 26 - 27.

Every advice is welcome! Thanks

Upvotes: 0

Views: 164

Answers (2)

Peter Ward
Peter Ward

Reputation: 61

Change the randomize to give a number less than 3, then add 26.

Rnd() returns a number between [0, 1), multiplying that by 28 will never result in 28. And frequently will result in a number below 28, which gets avoided in the output because of your if block.

f = (Rnd() * 3) will give a random number between [0, 3).

f = ((Rnd() * 3) + 26) will give a random number between [26, 29).

Upvotes: 2

Nicholas Kemp
Nicholas Kemp

Reputation: 337

What you are looking for is a Do-Loop Until or Do While-Loop loop. This kind of loop runs until a condition is met. In your case, that condition would be "20 messages are printed".

The Do While-Loop loop checks the condition at the start, so if the condition is False at first, the loop wont run.

The Do-Loop Until loop checks the condition at the end, so the loop will run at least once.

An example code following your previous For loop:

Sub C7()

Dim b As Integer
Dim f As Single
Dim ret As String
dim count as Integer: count = 0

Do
    f = Rnd() * 28
    If f >= 26 And f <= 28 Then
        ret = ret & Str(f)
        count = count + 1
    End If
Loop until count = 20

    MsgBox ret

End Sub

Upvotes: 0

Related Questions