Home » excel » How to duplicate rows in excel based on column content?

How to duplicate rows in excel based on column content?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have following data in excel table

r1 r2 r3 r4 r5
v1 v2 r3 r4 r5
x1 x2    r4 r5

is it posible (and how) to convert this data to structure like:

r1 r2 r3
r1 r2 r4
r1 r2 r5
v1 v2 r3
v1 v2 r4
v1 v2 r5
x1 x2 r4
x1 x2 r5

thanks in advance

How to&Answers:

Is this what you are trying?

Sub Sample()
    Dim wsI As Worksheet, wsO As Worksheet
    Dim wsIlRow As Long, wsOlRow As Long, i As Long, j As Long

    Set wsI = Sheets("Sheet1")
    Set wsO = Sheets("Sheet2")

    wsIlRow = wsI.Range("A" & wsI.Rows.Count).End(xlUp).Row

    wsOlRow = 1

    For i = 1 To wsIlRow
        For j = 3 To 5
            If Len(Trim(wsI.Cells(i, j).Value)) <> 0 Then
                wsO.Range("A" & wsOlRow).Value = wsI.Range("A" & i).Value
                wsO.Range("B" & wsOlRow).Value = wsI.Range("B" & i).Value
                wsO.Range("C" & wsOlRow).Value = wsI.Cells(i, j).Value
                wsOlRow = wsOlRow + 1
            End If
        Next j
    Next i
End Sub

SNAPSHOT

enter image description here

Answer:

This method uses arrays to avoid range loops. It dumps a range from column A:E to F:H

enter image description here

Sub MoveEM()
    Dim rng1 As Range
    Dim X
    Dim Y
    Dim lngRow As Long
    Dim lngCol As Long
    Dim lngCnt As Long
    Set rng1 = Range([a1], Cells(Rows.Count, "E").End(xlUp))
    X = rng1.Value2

    ReDim Y(1 To 3 * UBound(X, 1), 1 To 3)
    For lngRow = 1 To UBound(X, 1)
        For lngCol = 1 To 3
            lngCnt = lngCnt + 1
            Y(lngCnt, 1) = X(lngRow, 1)
            Y(lngCnt, 2) = X(lngRow, 2)
            Y(lngCnt, 3) = X(lngRow, 2 + lngCol)
        Next
    Next
   [f1].Resize(UBound(Y, 1), UBound(Y, 2)) = Y

   End Sub