6

I currently have a macro that when i click a button, it "randomly" gives me a number in a msgbox:

dim number as double
number= Int(8 * Rnd + 1) - 1
MsgBox number

The thing is, the numbers aren't actually randomized. For example: If i start the macro, click the button twice, lets say i get the numbers 5 and 2. Now if i close the macro and open it again and click the button twice, i get the same two numbers 5 and 2.

Now i know that in VB.net there was a way to actually get it to spit out random numbers each time without repeating the "sequence" but it's been years since i touched vb.net so i don't quite remember, also i would not know how to use it in excel vba.

Community
  • 1
  • 1
HumanlyRespectable
  • 203
  • 5
  • 12
  • 26

1 Answers1

19

You need to initialize the random number function

Sub test()
Dim number As Double
Randomize
number = Int(8 * Rnd + 1) - 1
MsgBox number
End Sub
ruedi
  • 5,365
  • 15
  • 52
  • 88
  • 2
    This is SOOOO unintuitive! Not, Rnd.Randomize(), or Rnd.Init()? No - an orphaned Randomize function! Blech! (Of course, it worked - thanks!) – SteveCinq Jun 14 '18 at 21:24
  • I can't believe this is a thing... I spent the last 3 hours looking at every other part of my code because of course the random number generator was fine - upon testing, it generated new numbers... But every new workbook, same order... Thank you for your help @ruedi! – ZAR Nov 29 '22 at 14:35