seed random number in VBA

MetLife

Active Member
Joined
Jul 2, 2012
Messages
330
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

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
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,223,880
Messages
6,175,153
Members
452,615
Latest member
bogeys2birdies

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