有没有一种方法可以使用VBA在Excel中堆叠数据

时间:2020-03-06 00:20:56

标签: excel vba

我有一个120列的Excel文件。部分数据如下:

Exce

两个重要列是M列(组)和N列(类)。我想从列组中获取M 1和M2。接下来,我过滤Class以获得M1和M2。接下来,在将从Group获得的数据的末尾,复制从Class获得的复制粘贴M1和M2,然后将它们重命名为M1和M2。因此输出为:

enter image description here 因此,组只有M1和M2。谢谢您的帮助

1 个答案:

答案 0 :(得分:0)

请参见Range对象的Copy方法


Option Explicit
Sub stack()

    Const START_ROW = 2 ' row below header

    Dim wb As Workbook, ws As Worksheet, count As Integer
    Dim iRow As Long, iLastRow As Long, iTargetRow As Long, s As String

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")

    ' find last row existing data
    iLastRow = ws.Range("M" & Rows.count).End(xlUp).Row
    iTargetRow = iLastRow + 1

    ' scan col M
    For iRow = START_ROW To iLastRow
       s = ws.Cells(iRow, 13).Value ' M
       If s = "M1" Or s = "M2" Then
           ws.Rows(iRow).EntireRow.Copy ws.Cells(iTargetRow, 1)
           iTargetRow = iTargetRow + 1
           count = count + 1
       End If
    Next

    ' scan col N
    For iRow = START_ROW To iLastRow
       s = ws.Cells(iRow, 14).Value ' N
       If s = "M1" Or s = "M2" Then
           ws.Rows(iRow).EntireRow.Copy ws.Cells(iTargetRow, 1)
           ws.Cells(iTargetRow, 13) = s ' copy from N to M
           iTargetRow = iTargetRow + 1
           count = count + 1
       End If
    Next

    MsgBox count & " rows copied.", vbInformation
End Sub