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?
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
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"
 
Upvote 0
Code:
    Dim A()         As Integer
    Dim n           As Long

    ReDim A(1 To n)
    ' or
    ReDim A(1 To n ^ 2)
 
Upvote 0
You have to assign a value to n >=1 first -- I should have shown that.
 
Upvote 0

Forum statistics

Threads
1,214,918
Messages
6,122,249
Members
449,075
Latest member
staticfluids

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