Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random order for 16 variables

Status
Not open for further replies.

BoxHead

Technical User
May 6, 2001
876
US
I have to assign random values (Location1 through Location16) to 16 Command Buttons.

I've done it with:

Code:
Randomize
Do
LOC1 = Int((16 * Rnd) + 1)
Loop While LOC1 = ""
Do
LOC2 = Int((16 * Rnd) + 1)
Loop While LOC2 = LOC1 Or LOC2 = ""
Do
LOC3 = yada yada yada.


By the time I get to LOC16, the Loop While statement gets ridiculously long.

I'm rewriting this program and it's always struck me that there has to be a simpler/shorter way to get this done.

Does anyone know what it is?

Thanks in advance,

BoxHead
 
Basically you're assigning the numbers 1 thru 16 to your controls in a random order without replication. Try nesting for next statements rather than the Do Loops.

...
Dim ctl As Control
Dim intPos As Integer
Dim intCount As Integer
Dim bFlag As Boolean
bFlag = True

LOC1 = Int((16 * Rnd) + 1) 'set first control's value

For intPos = 2 To 16 'set remaining control values
ctl = Me!("LOC" & intPos)
While bFlag
ctl.Value = Int((16 * Rnd) + 1)
bFlag = True
For intCount = intPos-1 to 1 Step -1
If ctl.Value = Me!("LOC" & intCount) Then 'test for repeat
bFlag = False
End If
Next
Wend
Next
...

NOTE: I haven't tested this for syntax, but the principle is sound. Basically, you're assigning the first control's value. Then you assign each of the other control's values then test this against the existing ones before. If a value has been duplicated you reassign it another value until you've found one that hasn't been used.
 
Actually, I kinda screwed up. The flagged loop should run as long as the flag is not true:

While Not bFlag

Anyway, you should get the picture.
 
I do get the picture. Thank you.

BoxHead
 
You're welcome. You can reduce the time required to find the available number if you'll pop out of the while loop once it determines that it's a duplicate:

...
For intCount = intPos-1 to 1 Step -1
If ctl.Value = Me!("LOC" & intCount) Then 'test for repeat
bFlag = False
Wend
End If
...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top