Reputation: 761
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
Upvotes: 2
Views: 3849
Reputation: 55682
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
Upvotes: 1
Reputation: 14145
A way to read in an entire range into an array:
Sub readText()
Dim i As Integer
Dim dataStr As String
Dim arr As Variant
'read data
arr = Range("A1:A10").Value
'display the data...
For i = 1 To UBound(arr)
'add the value at this point - given by arr(i,1) - to the string. You can access these elements
'directly via this sort of array notation
dataStr = dataStr & arr(i, 1) & vbCrLf
Next i
'show what was in those cells
MsgBox (dataStr)
MsgBox (arr(3,1) )
End Sub
It is almost assuredly easier to sort in Excel first (ie alphabetical? increasing? by order? etc) rather than doing so in vba.
Upvotes: 0