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

What does custom number format of ;;; mean?
Three semi-colons will hide the value in the cell. Although most people use white font instead.
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,622
Messages
6,120,580
Members
448,972
Latest member
Shantanu2024

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