Approach via transposed datafield array
Get data via a transposed datafield array (rows and columns changed), rearrange the array structure once after a reverse loop (within the same array) and write the array back to a target sheet:
Code example
This code example assumes you have a header line in row 1:1
in your data sheet:
Option Explicit ' declaration head of your code module
Sub Iterate()
Dim i As Long, j As Long, n As Long
Dim nCol As Long, sCol As String
Dim v ' short for Dim v As Variant
Dim ws As Worksheet, ws2 As Worksheet
Set ws = ThisWorkbook.Worksheets("MyData") ' << change to data sheet name
Set ws2 = ThisWorkbook.Worksheets("MyTarget") ' << change to target sheet name
' [1] get last row in column A containing data
n = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
' [2] count header columns A:G (=7) and add one column to receive free line
nCol = 7 + 1 ' nCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column + 1
' [3] get column letter after multiplication of rows with nCol
sCol = Split(Cells(1, (n - 1) * nCol).Address, "$")(1)
' [4] get values to transposed one based 2dim array
v = Application.Transpose(ws.Range("A1:" & sCol & n).Value)
' [5] rearrange data by reverse loop
For i = n To 2 Step -1
For j = 1 To nCol
' assign header (col 1) and data (col 2) to array items
v((i - 2) * nCol + j, 1) = v(j, 1) ' header
v((i - 2) * nCol + j, 2) = v(j, i) ' data
Next j
Next i
' [6] write back to target sheet
ws2.Range("A:B") = "" ' clear columns A:B in target sheet
ReDim Preserve v(1 To UBound(v), 2) ' redim array to 2 columns
ws2.Range("A1").Resize(UBound(v), 2) = v ' write back
End Sub
Notes
Usually the (not yet transposed) datafield array would contain n
data rows and nCol
columns.
As this example tries to reuse the original array, the data range gets greater to include all items multiplied by 8 (i.e. 7 columns plus an empty one).
- As the data range will be transposed, columns change to rows.
- As the total lines have to contain the product rows (n-1, i.e. without header line) * 8, it's necessary to define a greater column range to receive a greater array for later rearrangement - see section [3] with definition of a column letter.
- The array item
v((i - 2) * nCol + j,
2)
rearranges the data items only in column 2 to write them back later to target sheet column B
. The new row index ((i
- 2) * nCol + j
has to calculate i-2
considering the header line (-1) as well as a start from zero (-1), multiplied by nCol
plus column j
.