SarahDetroja
New Member
- Joined
- May 13, 2020
- Messages
- 18
- Office Version
- 2013
- Platform
- Windows
Sub Rearrange()
Dim a As Variant, b As Variant
Dim i As Long, k As Long
a = Range("A2", Range("D" & Rows.Count).End(xlUp)).Value
ReDim b(1 To UBound(a) / 3, 1 To 5)
For i = 1 To UBound(a) Step 3
k = k + 1
b(k, 1) = a(i, 1): b(k, 2) = a(i, 2): b(k, 3) = a(i, 4): b(k, 4) = a(i + 1, 4): b(k, 5) = a(i + 2, 4)
Next i
With Range("F2:J2").Resize(k)
.Value = b
.Rows(0).Value = Array("First Name", "Last Name", "Color", "Country", "City")
.EntireColumn.AutoFit
End With
End Sub
Hi Peter,Try this with a copy of your workbook. I have assumed that your actual data starts in row 2 with headers in row 1.
VBA Code:Sub Rearrange() Dim a As Variant, b As Variant Dim i As Long, k As Long a = Range("A2", Range("D" & Rows.Count).End(xlUp)).Value ReDim b(1 To UBound(a) / 3, 1 To 5) For i = 1 To UBound(a) Step 3 k = k + 1 b(k, 1) = a(i, 1): b(k, 2) = a(i, 2): b(k, 3) = a(i, 4): b(k, 4) = a(i + 1, 4): b(k, 5) = a(i + 2, 4) Next i With Range("F2:J2").Resize(k) .Value = b .Rows(0).Value = Array("First Name", "Last Name", "Color", "Country", "City") .EntireColumn.AutoFit End With End Sub
You are most welcome.You're welcome. Thanks for the follow-up.
Pretty hard to give you a fixed rule as to what to do since even your fixed columns are not all at the left side etc, but see if this helps. You will have to fixe the headers section of the results yourself.in future if I have more questions and more columns (like Name, Age) what do I need to do?
Sub Rearrange_v2()
Dim a As Variant, b As Variant, FCols As Variant
Dim i As Long, j As Long, k As Long
Const NumQns As Long = 10
Const FixedCols As String = "1 2 5 6" 'Columns A, B, E F
Const AnswerCol As Long = 4 'Column D
Const NumCols As Long = 6 'Total number of columns
a = Range("A2", Range("A" & Rows.Count).End(xlUp)).Resize(, NumCols).Value
FCols = Split(FixedCols)
ReDim b(1 To UBound(a) / NumQns, 0 To UBound(Split(FixedCols)) + NumQns)
For i = 1 To UBound(a) Step NumQns
k = k + 1
For j = 0 To UBound(FCols)
b(k, j) = a(i, FCols(j))
Next j
For j = UBound(FCols) + 1 To UBound(FCols) + NumQns
b(k, j) = a(i + j - UBound(FCols) - 1, AnswerCol)
Next j
Next i
With Range("Z2").Resize(k, NumQns + UBound(FCols) + 1)
.Value = b
' .Rows(0).Value = Array("First Name", "Last Name", .....) 'Add other headers here
.EntireColumn.AutoFit
End With
End Sub