seed random number in VBA

MetLife

Active Member
Joined
Jul 2, 2012
Messages
334
Office Version
  1. 365
Hi,

I wanted to generate random numbers, but they need to be the same random numbers. So in C++ I recall you could seed the random number generator with an integer.

So Rnd(8) should generate the same sequence of numbers. How do we do this in Excel?

I notice that if I use Rnd(8) it generates the same ones but they are the same as Rnd(9) etc...

VBA Code:
Sub test_array()
Dim x1(1 To 100, 1 To 200) As Double
Dim i As Integer, j As Integer

    For i = 1 To 100
        For j = 1 To 200
            x1(i, j) = Rnd(8)
            Range("G5").Offset(j, 0).Value = x1(i, j)
        Next j
    Next i

'1.) seed random number

End Sub
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
using Randomize 8 doesn't work. The numbers always change.

VBA Code:
Sub test_array()
Dim x1(1 To 200) As Double
Dim i As Integer, j As Integer

Randomize 8

    For i = 1 To 100
            x1(i) = Rnd()
            Range("G5").Offset(i, 0).Value = x1(i)
    Next i

MsgBox "done!"

End Sub
 
Upvote 0
Use "Rnd (-1)" before the "Randomize" statement. That should generate the same sequence given a certain seed. This behavior is described in a Note in the "Randomize" documentation.

Ie:
VBA Code:
Sub test_array()
Dim x1(1 To 200) As Double
Dim i As Integer, j As Integer

Rnd (-1)
Randomize 8

    For i = 1 To 100
            x1(i) = Rnd()
            Range("G5").Offset(i, 0).Value = x1(i)
    Next i

MsgBox "done!"

End Sub
 
Upvote 0
Solution
Thanks - I had read the documentation & it would have been helpful if they provided an example like you did.
 
Upvote 0

Forum statistics

Threads
1,224,813
Messages
6,181,107
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top