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

前端 未结 2 1938
我在风中等你
我在风中等你 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

提交回复
热议问题