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

后端 未结 3 524
长发绾君心
长发绾君心 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 an approach going from worksheet to worksheet directly. This might be necessary if the dataset is too big and available memory too small for using arrays. It's likely to be slow.

    It uses the same call parameters as reOrgV1, and pretty much the same logic.

    It's updated to add "DEFECTS" to the properies. The input looks like:

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

    Here's the code.

    Public Sub reOrgV2(inSource As Range, inTarget As Range)
    '' This version works directly on the worksheet
    '' and transfers the result directly to the target
    '' given as the top-left cell of the result.
    
    '' **** Changed to add "Defects"
        Dim resNames()
        Dim propNum As Integer
        Dim srcRows As Integer
        Dim resRows As Integer
        Dim i As Integer
        Dim j As Integer
        Dim g As Integer
    
        '' Shape the result
        resNames = Array("Size", "Grade", "Location", "Defects")
        propNum = 1 + UBound(resNames)
    
        '' Row counts
        srcRows = inSource.Rows.Count
        resRows = srcRows * propNum
    
        '' re-org and transfer source to result range
        inTarget = inTarget.Resize(resRows, 4)
        g = 1
        For i = 1 To srcRows
            For j = 0 To 3
                inTarget.Item(g + j, 1) = inSource.Item(i, 1)      '' Tag
                inTarget.Item(g + j, 2) = inSource.Item(i, 2)      '' SKU
                inTarget.Item(g + j, 3) = resNames(j)              '' Property
                inTarget.Item(g + j, 4) = inSource.Item(i, j + 3)  '' Value
            Next j
            g = g + propNum
        Next i
    End Sub
    

    This is the revised call sourcing the wider range.

    '' Call ReOrgV2 with input and output ranges
    Public Sub test4()
        Dim i As Integer
        i = Range("InData!A:A").Find("").Row - 2
        reOrgV2 Range("InData!A2").Resize(i, 6), [OutData!A1]
    End Sub
    

提交回复
热议问题