You dimensioned the array as 9, and I see a problem with that.
If you didn't use the Option Base 1 statement at the module level, then the default lower range of your array will be 0. So, the lower range of your array is 0 while the upper range of your array 9.
If you did use the Option Base 1 statement at the module level, then the lower and upper range of your array will be 1 and 9, respectively.
Either way your FOR/NEXT loop will throw an exception when the index to your loop reaches 10. Your loop will try to assign a random number to an array element that doesn't exist and you will get:
So you have a couple of choices:
If you are comfortable with 0 based arrays you can change your macro to:
Code:
Dim myArray(9) As Integer
...
For i =
or you can use the Option Base 1 statement at the module level:
Code:
) As Integer
...
For i = 1 To 10
...
or, perhaps the easiest, is to just let the module default to a zero based lower bound array, but still use 10 as the upper bound of your array, as in:
Code:
) As Integer
...
For i = 1 To 10
...
The only differnce between this and using the Option Base 1 statement, is that myArray(0) does exist as an array element, but you just choose not to use it. Since myArry(0) does exist, it is allocated memory, and if unused is wasteful. But on a single-dimensional array, the non-use is extremely minimal. (2 bytes for an Integer data type)
(I find it easier to think that the 1st elemenet I'm going to use has 1 as it's index, as opposed to 0. Oftentimes, I use the 0 index for sorting routines.)
That will work for predefined arrays. But you said "... and am creating a sample file which will select distinct names from a table". What if the number of distinct names is greater than 10? Well, you can create a dynamic array! You do this by NOT dimensioning the array with a preset number of elements. After you have determined the number of elements you'll need, you redimension the array using ReDim statement.
To loop through all the elements of a dynamic array, you'll probably want use the UBound function. The UBound function returns the upper bound of your array.
Here's an an example of a dynamic array. (The number of elements in this array is random).
Code:
Sub TestDynamicRandomNumberArray()
Dim myArray() As Integer
Dim idx As Integer
Dim minValue As Integer
Dim maxValue As Integer
Dim maxElements As Integer
ActiveSheet.Cells.ClearContents
maxElements = Int(100 * Rnd) + 20
ReDim myArray(maxElements)
minValue = 0
maxValue = 100
For idx = 1 To UBound(myArray)
myArray(idx) = Int((maxValue - minValue + 1) * Rnd) + minValue
ActiveSheet.Range("A" & idx).Value = myArray(idx)
Next idx
End Sub