答案 0 :(得分:3)
如下所示,使用双For循环遍历行然后列,并以所需格式将数据传输到Sheet2(这不会将标题添加到Sheet2,但它会给你一些关于如何去做的指导):
Sub Summarize()
Dim ws As Worksheet: Set ws = Sheets("Sheet1") 'Sheet with data
Dim ws2 As Worksheet: Set ws2 = Sheets("Sheet2") 'Summarised Sheet
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
LastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
'optimize code:
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
For i = 2 To LastRow 'loop through rows
For col = 6 To 14 Step 4 'loop through columns
'replace 14 with (LastCol - 4) if you wish to do all the months instead of just the first 3
FreeRow = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row + 1 'get the next free row to transfer data to
ws2.Cells(FreeRow, 1).Value = ws.Cells(i, 1).Value
ws2.Cells(FreeRow, 2).Value = ws.Cells(i, 2).Value
ws2.Cells(FreeRow, 3).Value = ws.Cells(i, 3).Value
ws2.Cells(FreeRow, 4).Value = ws.Cells(i, 4).Value
ws2.Cells(FreeRow, 5).Value = "20" & Mid(ws.Cells(1, col).Value, 5, 2) 'get the year from the header
ws2.Cells(FreeRow, 6).Value = Left(ws.Cells(1, col).Value, 3) ' get the month name from header
ws2.Cells(FreeRow, 7).Value = ws.Cells(i, col).Value 'transfer values
ws2.Cells(FreeRow, 8).Value = ws.Cells(i, col + 1).Value
ws2.Cells(FreeRow, 9).Value = ws.Cells(i, col + 2).Value
ws2.Cells(FreeRow, 10).Value = ws.Cells(i, col + 3).Value
Next col
Next i
'return to normal Excel status after macro has finished
Application.EnableEvents = True
Application.DisplayStatusBar = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
<强>更新强>
我在代码中添加了几行以尝试优化它的速度,同时删除了Copy&amp;粘贴并更改它以传递值而不复制任何内容,请看下面的内容:
{{1}}