# For loops and random numbers

#### Darkpagey

##### New Member
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?

### Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
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"

Code:
``````    Dim A()         As Integer
Dim n           As Long

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

:S Oh man that's so easy, thanks guys.

You have to assign a value to n >=1 first -- I should have shown that.

Replies
2
Views
498
Replies
1
Views
104
Replies
0
Views
236
Replies
4
Views
237
Replies
1
Views
219

Threads
1,207,402
Messages
6,078,263
Members
446,324
Latest member
JKamlet

### 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

### 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