For loops and random numbers

Darkpagey

New Member
Joined
Mar 18, 2013
Messages
3
Hey guys.

I've got the following code (variables declared previously):

Code:
ReDim A(i) As Integer
For i = 1 To n
[COLOR=#ff0000]    A(i) = i[/COLOR]
Next i


For i = 1 To n
    r = Int((n - i + 1) * Rnd() + i)
    y = A(i)
    A(i) = A(r)
    A(r) = y
    Cells(i).Value = A(i)
Next i

This creates (in this case for my data, n=4) 4 numbers between 1 and 4 which have been swapped in a random fashion to create a random permutation.

What I want to achieve is a set of random numbers from i = 1 to n^2 (as opposed to from i = 1 to n). However, when I try to do this, the line which I have highlighted above gives error 9 (subscript out of range)

Sorry for this being such a pedestrian question, but how do I get around this?
 

Some videos you may like

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.

engineer69

New Member
Joined
Apr 3, 2009
Messages
34
Have you tried:
Dim A(1000) As Integer?
Not sure if 1000 is large enough, but your ReDim statement does not contain a size or you might try to declare it "As Variant"
 

shg

MrExcel MVP
Joined
May 7, 2008
Messages
21,779
Office Version
  1. 2010
Platform
  1. Windows
Code:
    Dim A()         As Integer
    Dim n           As Long

    ReDim A(1 To n)
    ' or
    ReDim A(1 To n ^ 2)
 

shg

MrExcel MVP
Joined
May 7, 2008
Messages
21,779
Office Version
  1. 2010
Platform
  1. Windows
You have to assign a value to n >=1 first -- I should have shown that.
 

Watch MrExcel Video

Forum statistics

Threads
1,122,469
Messages
5,596,325
Members
414,053
Latest member
Dual Showman

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
Top