Convert row with columns of data into column with multiple rows in Excel

后端 未结 3 541
长发绾君心
长发绾君心 2021-01-07 08:33

I hv rows of data:-

TAG   SKU   SIZE   GRADE   LOCATION
A001  123    12      A       X1
A002  789    13      B       X3
A003  456    15      C       X5
         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 08:59

    Here's a really simple solution that assumes the dataset isn't huge. It takes the input range into an array, transforms it into a result array, then moves the array to the specified target. The target is defined by the top left cell.

    When it's possible, this approach is orders of magnitude faster than working directly with cells on worksheets.

    The test function at the bottom needs you to put an input set on sheet InData and have a sheet OutData defined for the results but your input and output ranges can be anywhere you want.

    Option Explicit
    
    Public Sub reOrgV1(inSource As Range, inTarget As Range)
    '' This version uses VBA arrays to do the work.
    '' Takes a source range, reorganizes it to the target
    ''    given as the top-left cell of the result.
    
        Dim srcArray As Variant
        Dim resArray As Variant
        Dim resNames()
        resNames = Array("SIZE", "GRADE", "LOCATION")
    
        Dim srcRows As Integer
        Dim resRows As Integer
        Dim i As Integer
        Dim j As Integer
        Dim g As Integer
    
        '' Move range into source array
        srcArray = inSource.Value
        srcRows = UBound(srcArray, 1)
        resRows = srcRows * 3
    
        ''Build result array
        ReDim resArray(1 To resRows, 1 To 3)
    
        '' transfer source to result array
        g = 1
        For i = 1 To srcRows
            For j = 0 To 2
                resArray(g + j, 1) = srcArray(i, 1)
                resArray(g + j, 2) = srcArray(i, 2)
                resArray(g + j, 3) = resNames(j) & " " & srcArray(i, j + 3)
            Next j
            g = g + 3
        Next i
    
        '' Move the results to the target range
        inTarget.Resize(resRows, 3).Value = resArray
    End Sub
    
    Public Sub test1()
        reOrgV1 Range("InData!A2:E4"), Range("OutData!A1")
    End Sub
    

提交回复
热议问题