Using seed to generate random numbers if VBA

afndst

Board Regular
Joined
Sep 8, 2015
Messages
59
Office Version
  1. 365
Platform
  1. Windows
I am having trouble with the following code to get repeated series of random numbers using a seed value. The series obtained are always different.

Option Base 1
Option Explicit
Function MyRnd(n, Optional seed)
Dim x() As Double
ReDim x(n)
' Dim xc As Integer
' Dim xp As Double
Dim i As Integer
' Dim s(n) As Double



If IsMissing(seed) Then

For i = 1 To n
x(i) = Rnd
Next i
Else
Randomize seed
For i = 1 To n
x(i) = Rnd
Next i
End If

MyRnd = WorksheetFunction.Transpose(x)

End Function
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
Hi

Check the help.

If you want to repeat the random number sequence for the seed value, you have to call rnd with a negative value before, like:


Code:
...
Else
    
    Rnd -1
    Randomize seed
...

also the redim of the array should start at 1, you are not using element 0:

Code:
ReDim x(1 To n)
 
Upvote 0
Thank you very much. Problem solved:

Function xx0(n, seed, Optional out = 0)
Dim x()
ReDim x(1 To n)

Rnd (-1)
Randomize seed


For i = 1 To n
x(i) = Rnd()
Next i

If out = 0 Then
xx0 = WorksheetFunction.Transpose(x)
Else
xx0 = WorksheetFunction.Transpose(x(out))
End If

End Function
 
Upvote 0

Forum statistics

Threads
1,216,076
Messages
6,128,669
Members
449,463
Latest member
Jojomen56

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