enter code here
子逆透视()尺寸lastRow为长尺寸lastCol为长尺寸i为长尺寸j为长尺寸k为长尺寸data()为变量尺寸ws为工作表
Set ws = Worksheets("Table")
'Get the range of data
lastRow = Range("A" & Rows.Count).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
data = Range(Cells(1, 1), Cells(lastRow, lastCol)).Value
'Create new headers for the unpivoted data
ws.Range("A1").CurrentRegion.ClearContents
ws.Range("B3:E3").Value = Array("Line", "LOB", "Date", "Value")
'Loop through the data and unpivot
k = 1
For i = 2 To lastRow
For j = 3 To lastCol
If j <> 2 And j <> 1 Then 'skip columns A and B
If IsDate(data(1, j)) Then 'check if column header is a date
ws.Range("B4").Offset(k, 0).Resize(1, 4).Value = _
Array(data(i, 1), data(i, 2), data(1, j), data(i, j))
Else
ws.Range("B4").Offset(k, 0).Resize(1, 4).Value = _
Array(data(i, 1), data(i, 2), data(1, j), data(i, j))
End If
k = k + 1
End If
Next j
Next i
末端子组件
i有一个表中所示的列b到O,我需要一个vba代码,可以将其转换为表中所示的样本从范围R,S,T,u
尝试了此代码,但它不执行所需的操作。Sub TransformTable()
' Define variables
Dim i As Long, j As Long
Dim lastRow As Long, lastCol As Long
Dim data As Variant, newData As Variant
Dim ws As Worksheet
' Set initial values
Set ws = ThisWorkbook.Sheets("Table") ' Change the sheet name to your desired sheet name
lastRow = Cells(Rows.Count, "B").End(xlUp).Row ' Find last row with data in column B
lastCol = Cells(6, Columns.Count).End(xlToLeft).Column ' Find last column with data in row 6
data = Range("B6", Cells(lastRow, lastCol)).Value ' Get data from table
' Resize new data array
ReDim newData(1 To UBound(data, 1) * (UBound(data, 2) - 3), 1 To 4)
' Loop through data and transform
For i = 1 To UBound(data, 1)
For j = 4 To UBound(data, 2)
newData(((i - 1) * (UBound(data, 2) - 3)) + (j - 3), 1) = data(i, 1) ' Line
newData(((i - 1) * (UBound(data, 2) - 3)) + (j - 3), 2) = data(i, 2) ' LOB
newData(((i - 1) * (UBound(data, 2) - 3)) + (j - 3), 3) = data(5, j) ' Date
newData(((i - 1) * (UBound(data, 2) - 3)) + (j - 3), 4) = data(i, j) ' Value
Next j
Next i
' Clear old table and paste new data
ws.Range("A1:D1").Value = Array("Line", "LOB", "Date", "Value") ' Add headers
ws.Range("A2").Resize(UBound(newData, 1), UBound(newData, 2)).Value = newData ' Paste new data
End Sub
1条答案
按热度按时间xsuvu9jc1#
转换数据:取消旋转RCV(VBA)