我在excel电子表格的A列中有10个值(它会更多)有没有办法获取列的值并将它们放入数组中?
如果可能的话,是否可以将这些值以不同于它们在电子表格中的顺序放置。例如,如果我的电子表格值是“Apple”“Orange”和“Banana”,那么我希望我的数组看起来像位置 0“Orange”、位置 1“Banana”和位置 2“Apple”。
有人知道如何做到这一点吗?顺便说一句,它需要从 10 扩展到 1000 个值,而无需过多编辑代码
您可以为单个列创建索引数组而无需循环,如下所示
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
您没有发布您想要如何对数据进行排序? 针对随机排序进行了更新
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
下一个子使用Chip Pearson 的 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
一种将整个范围读入数组的方法:
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
几乎可以肯定,首先在 Excel 中排序(即按字母顺序?增加?按顺序?等)而不是在 vba 中这样做。