I have 10 values in column A of a excel spreadsheet (it will be more) is there a way to take the values of the column and put them into an array?
And if possible would it be possible to put the values in a different order than they are in in the spreadsheet. For example, if my spreadsheet values are "Apple" "Orange" and "Banana", then I would like my array to look something like, position 0 "Orange" position 1 "Banana" and position 2 "Apple".
Does anybody know how this might be done? By the way, it needs to be scalable from 10 to 1000 values without editing the code much
You can create an indexed array for a single column without looping as follows
Sub GetArray()
Dim X
Dim lngCol As Long
lngCol = Cells(Rows.Count, "A").End(xlUp).Row
X = Application.Transpose(Application.Evaluate("If(row(A1:A" & lngCol & "),row(1:" & lngCol & ")-1 & A1:a" & lngCol & ",0)"))
End Sub
You didn't post how you wanted to sort the data?
Udpated for random ordering
Sub GetArray2()
Dim X()
Dim lngCol As Long
lngCol = Cells(Rows.Count, "A").End(xlUp).Row
X = Application.Transpose(Range("A1:A" & lngCol))
Call ShuffleArrayInPlace(X())
End Sub
The next sub uses a modified version of Chip Pearson's ShuffleArray
Sub ShuffleArrayInPlace(InArray() As Variant)
'http://www.cpearson.com/excel/ShuffleArray.aspx
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim N As Long
Dim Temp As Variant
Dim J As Long
Randomize
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
If N <> J Then
Temp = InArray(N)
InArray(N) = InArray(J)
InArray(J) = Temp
End If
Next N
For N = LBound(InArray) To UBound(InArray)
InArray(N) = N - 1 & " " & InArray(N)
Debug.Print InArray(N)
Next N
End Sub