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

佐手、 提交于 2020-05-09 07:42:55

问题


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

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

– – – – – –

I know this way:
=ArrayFormula({ROW(INDIRECT(A1&":"&B1)); ROW(INDIRECT(A2&":"&B2))})

That does the job perfectly but what if I don't know, how many ranges there will be? I want to generate an array of all the numbers between values specified in cells from A1:B1 all the way to A:B.

Thank you in advance!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/61505164/how-can-i-generate-an-array-of-numbers-between-multiple-ranges-defined-in-separa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!