How can I generate an array of numbers between multiple ranges defined in separate cells in Sheet?

前端 未结 2 1934
我在风中等你
我在风中等你 2021-01-25 05:16

A1: 1 | B1: 4
A2: 3 | B2: 6

How can I get {1, 2, 3, 3, 4, 4, 5, 6} out of this?<

相关标签:
2条回答
  • 2021-01-25 05:58

    In Excel 365 with your data in columns A and B, pick a cell and enter:

    ="{" & TEXTJOIN(",",TRUE,SEQUENCE(,MAX(A:B),MIN(A:B))) & "}"
    

    EDIT#1:

    Try this VBA macro:

    Sub MakeArray()
        Dim I As Long, N As Long, J, k
        Dim strng As String
        Dim arr As Variant
    
        N = Cells(Rows.Count, "A").End(xlUp).Row
        For I = 1 To N
            For J = Cells(I, 1) To Cells(I, 2)
                strng = strng & "," & J
            Next J
        Next I
        strng = Mid(strng, 2)
    
        strng = "{" & Join(fSort(Split(strng, ",")), ",") & "}"
    
    
        MsgBox strng
    End Sub
    
    Public Function fSort(ByVal arry)
    Dim I As Long, J As Long, Low As Long
        Dim Hi As Long, Temp As Variant
    
        Low = LBound(arry)
        Hi = UBound(arry)
    
        J = (Hi - Low + 1) \ 2
        Do While J > 0
            For I = Low To Hi - J
              If arry(I) > arry(I + J) Then
                Temp = arry(I)
                arry(I) = arry(I + J)
                arry(I + J) = Temp
              End If
            Next I
            For I = Hi - J To Low Step -1
              If arry(I) > arry(I + J) Then
                Temp = arry(I)
                arry(I) = arry(I + J)
                arry(I + J) = Temp
              End If
            Next I
            J = J \ 2
        Loop
        fSort = arry
    End Function
    

    The macro:

    1. creates a comma-separated string from each A/B pair
    2. sorts the string
    3. outputs the string
    0 讨论(0)
  • 2021-01-25 06:10

    Here is a relatively simple formula to generate the array you're talking about based on an infinite number of ranges in columns A and B.

    =ARRAYFORMULA(QUERY(SPLIT(FLATTEN(SEQUENCE(1,MAX(B1:B10-A1:A10)+1,0)+A1:A10&"|"&B1:B10),"|",0,0),"Select Col1 where Col1<=Col2 order by Col1",0))
    

    You can see it demonstrated in the tab called Demo 2 on this sheet.

    0 讨论(0)
提交回复
热议问题