简体   繁体   中英

VBA- Put range of values into array

I'm a pretty new self-taught programmer and I hope to learn from all of you.

Here, I'd like to put columns A of excel into an array and form a combination of three columns. The code is written and it runs, however, in a very slow speed.

  1. If I put Array(1,2,3...,9,10) it works. However, if I define the Dim nums(): nums = Array(Range("A1:A5").Value) it does not work.

  2. Even if I put Array(1,2,3...,9,10), the code runs very slowly.

The following is necessary because it's gonna be used when my array gets long. Indeed, my array would get over 2 thousand combinations. (Values of column A would change).

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

My entire code below,

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

这是数据的预览

Try:

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

The nums array will look like:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM