PDA

View Full Version : Making the random...random



Waubain
09-10-2010, 09:36 AM
During a lecture I click on a button on a slide and a name is randomly picked from a list and displayed on the screen. Below is the code. The problem is that the random selection is always in the same order every time I start the slide presentation. This might be how the random is seeded? I have about 100 student names in the text file.

Is there a way to make the seed random, so the order is always different each time the presentation starts.

Thanks.

----------------------------

Private Sub UserForm_Initialize()

Me.StartUpPosition = 0 'From Top Left
Me.Top = 310
Me.Left = 450

Dim arr, fs, a
Dim ThePath As String
Dim NewPath As String
Dim name As String

ThePath = CurDir ' Returns Path of lecture
NewPath = ThePath & "\names\names.txt" ' Creates a new path where names are located
Set fs = CreateObject("Scripting.FileSystemObject") ' Chooses a random student from text file
Set a = fs.openTextFile(NewPath)
arr = Split(a.readall, Chr(13) & Chr(10))
name = arr(Int((112 * Rnd)))
lblName.Caption = name ' displays name in label caption
End Sub

Private Sub cmdOK_Click()

Dim SlideNumber As Long
Unload frmName ' unloads form from memory

End Sub

Cosmo
09-10-2010, 10:25 AM
Try something like this to see if it make a difference:
Rnd(cSng(Time))

This should give you a different number each time

Paul_Hossler
09-10-2010, 06:32 PM
Easiest way I know is to use Randomize

From Help:



Randomize Statement

Initializes the random-number generator.

Syntax

Randomize [number]

The optional number argument is a Variant or any valid numeric expression.

Remarks

Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.

If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.


Note
To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.


Paul

John Wilson
09-10-2010, 11:09 PM
Randomize
name = arr(Int((112 * Rnd)))

Should do it

John Wilson
09-12-2010, 06:53 AM
Your formula can return zero by the way, I'm assuming that arr is an array that has a zero member?

Also this may interest you http://www.pptalchemy.co.uk/Random_Choice.html