Excel vba to create every possible combination of a Range

前端 未结 5 1008
南旧
南旧 2020-11-29 04:09

I have a problem that I haven\'t been able to find anywhere on the web (it may be there, but I can\'t find it, heh).

I have a spreadsheet with 13 columns of data. E

5条回答
  •  一个人的身影
    2020-11-29 04:54

    Not sure why you are averse to looping. See this example. It took less than a second.

    Option Explicit
    
    Sub Sample()
        Dim i As Long, j As Long, k As Long, l As Long
        Dim CountComb As Long, lastrow As Long
    
        Range("G2").Value = Now
    
        Application.ScreenUpdating = False
    
        CountComb = 0: lastrow = 6
    
        For i = 1 To 4: For j = 1 To 4
        For k = 1 To 8: For l = 1 To 12
            Range("G" & lastrow).Value = Range("A" & i).Value & "/" & _
                                         Range("B" & j).Value & "/" & _
                                         Range("C" & k).Value & "/" & _
                                         Range("D" & l).Value
            lastrow = lastrow + 1
            CountComb = CountComb + 1
        Next: Next
        Next: Next
    
        Range("G1").Value = CountComb
        Range("G3").Value = Now
    
        Application.ScreenUpdating = True
    End Sub
    

    SNAPSHOT

    enter image description here

    NOTE: The above was a small example. I did a test on 4 columns with with 200 rows each. The total combination possible in such a scenario is 1600000000 and it took 16 seconds.

    In such a case it crosses the Excel rows limit. One other option that I can think of is writing the output to a text file in such a scenario. If your data is small then you can get away without using arrays and directly writing to the cells. :) But in case of large data, I would recommend using arrays.

提交回复
热议问题