arrays - 如何创建一个excel列内容的数组

标签 arrays excel scalable vba

我在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

您没有发布您想要如何对数据进行排序?
enter image description here
更新了随机排序
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

下一个 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

关于arrays - 如何创建一个excel列内容的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342568/

相关文章:

vba - 跳过循环中的空单元格

css - 响应式 css 表,多行包含多个可缩放图像

excel - 有没有办法在Excel中添加时自动填充一行单元格

excel - 从 Excel 回复 Outlook 邮件

database - 跨区域/区域保持数据库同步(写入/更新后)

Redis 回写缓存仍然是一项手动任务?

php选择字符串中的数字

c - 在c中传递数组

c++ - 如何在 C++ 中创建多类型对象池

arrays - 从 n 个排序数组中找到第 k 个最小的数字