VBA-将值的范围放入数组

时间:2018-07-02 14:13:04

标签: arrays excel-vba vba excel

我是一个非常新的自学成才的程序员,我希望向大家学习。

在这里,我想将excel的A列放入数组中,并形成三列的组合。代码已编写并以非常慢的速度运行。

  1. 如果我将Array(1,2,3 ...,9,10)放进去,它将起作用。但是,如果我定义 Dim nums():nums = Array(Range(“ A1:A5”)。Value)无效。

  2. 即使我放置Array(1,2,3 ...,9,10),代码运行也非常缓慢。

以下是必要的,因为当我的数组变长时将使用它。确实,我的阵列将获得2000多种组合。 (A列的值将发生变化。)

For x = 0 To 60
    For y = 0 To 2
        Cells(x + 1, y + 2).Value2 = arValues(x, y)
    Next
Next

下面我的整个代码,

Sub AllCombinations()

    Dim nums(): nums = Array(Range("A1:A5").Value)
    Dim arValues(999999, 5)
    Dim n1 As Integer, n2 As Integer, n3 As Integer, n4 As Integer, n5 As Integer, n6 As Integer, x As Long
    Dim y As Integer

    For n1 = 0 To UBound(nums)
        For n2 = n1 + 1 To UBound(nums)
            For n3 = n2 + 1 To UBound(nums)

                arValues(x, 0) = nums(n1)
                arValues(x, 1) = nums(n2)
                arValues(x, 2) = nums(n3)

                x = x + 1

            Next
        Next
    Next

    For x = 0 To 60
        For y = 0 To 2

            Cells(x + 1, y + 2).Value2 = arValues(x, y)

        Next
    Next

    For x = 61 To 120
        For y = 0 To 2

            Cells(x - 60, y + 6).Value2 = arValues(x, y)

        Next
    Next

End Sub

Here is a preview of the data

1 个答案:

答案 0 :(得分:0)

尝试:

Dim nums()
nums = Range("A1:A5").Value

nums数组如下所示:

enter image description here