如何创建excel列的内容数组

时间:2012-09-09 20:13:25

标签: arrays excel-vba scalable vba excel

我在Excel电子表格的A列中有10个值(它会更多)有没有办法获取列的值并将它们放入数组?

如果可能的话,可以将值放在与电子表格中不同的顺序中。例如,如果我的电子表格值是“Apple”“Orange”和“Banana”,那么我希望我的数组看起来像位置0“橙色”位置1“香蕉”和位置2“Apple”。

有人知道如何做到这一点吗?顺便说一下,它需要可以从10到1000的值进行扩展,而无需编辑太多的代码

2 个答案:

答案 0 :(得分:1)

您可以为单个列创建索引数组,而不进行循环,如下所示

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

您没有发布您想要对数据进行排序的方式? enter image description here 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

下一个子版使用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

enter image description here

答案 1 :(得分:0)

将整个范围读入数组的方法:

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中进行排序。