Non-contiguous named range into an array, then into row in different sheet

前端 未结 1 1687
闹比i
闹比i 2020-12-05 21:17

I\'m trying to get data posted from a non-contiguous range into a row in a separate sheet. Before I built the non-contiguous range, this code worked perfectly. I\'ve tried

相关标签:
1条回答
  • 2020-12-05 21:56

    This is an example to explain how to achieve what you want. Please amend the code to suit your needs.

    Let's say, I have a Sheet1 which looks like as shown below. The colored cells make up from my non contiguous range.

    enter image description here

    Now paste the code given below in a module and run it. The output will be generated in Sheet2 and Sheet3

    Code

    Sub Sample()
        Dim rng As Range, aCell As Range
        Dim MyAr() As Variant
        Dim n As Long, i As Long
        
        '~~> Change this to the relevant sheet
        With Sheet1
            '~~> Non Contiguous range
            Set rng = .Range("A1:C1,B3:D3,C5:G5")
            
            '~~> Get the count of cells in that range
            n = rng.Cells.Count
            
            '~~> Resize the array to hold the data
            ReDim MyAr(1 To n)
            
            n = 1
            
            '~~> Store the values from that range into
            '~~> the array
            For Each aCell In rng.Cells
                MyAr(n) = aCell.Value
                n = n + 1
            Next aCell
        End With
        
        '~~> Output the data in Sheet
        
        '~~> Vertically Output to sheet 2
        Sheet2.Cells(1, 1).Resize(UBound(MyAr), 1).Value = _
        Application.WorksheetFunction.Transpose(MyAr)
        
        '~~> Horizontally Output to sheet 3
        Sheet3.Cells(1, 1).Resize(1, UBound(MyAr)).Value = _
        MyAr
    End Sub
    

    Vertical Output

    enter image description here

    Horizontal Output

    enter image description here

    Hope the above example helps you in achieving what you want.

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