在每个组下插入总计行

时间:2009-11-14 09:01:26

标签: excel vba excel-vba

我需要在每个组下插入一个包含总计和分页符的行。

我尝试了以下插入行,但是当我只想要一行时,它插入了多行。

Sub macro()
Dim sh1 As Worksheet
Dim i As Long, lastrow1 As Long

Set sh1 = Worksheets("Sheet1")     
lastrow1 = sh1.Cells.SpecialCells(xlCellTypeLastCell).Row

For i = 1 To lastrow1

   If sh1.Cells(i, "A").Value = "sell" Then
      sh1.Cells(i, "A").EntireRow.Insert
   End If
Next i
End Sub

3 个答案:

答案 0 :(得分:3)

我不是VBA的专家,但看起来你的代码每次发现“卖”时会插入一行,因此会插入多行。

尝试在插入行后添加中断以使您退出for循环。

希望这会有所帮助 AH注意,在VBA中Exit For用于中断for循环  所以你的代码将是

Set sh1 = Worksheets("Sheet1")     
lastrow1 = sh1.Cells.SpecialCells(xlCellTypeLastCell).Row

For i = 1 To lastrow1
    If sh1.Cells(i, "A").Value = "sell" Then
       sh1.Cells(i, "A").EntireRow.Insert
       Exit For
    End If
Next i
End Sub

答案 1 :(得分:1)

这将适用于A列中的两个以上不同的字符串

Sub InsertTotals()

    Dim i As Long
    Dim lLastRow As Long
    Dim sh1 As Worksheet

    Set sh1 = ActiveWorkbook.Worksheets("Sheet1")

    lLastRow = sh1.Cells(sh1.Rows.Count, 1).End(xlUp).Row

    For i = lLastRow + 1 To 2 Step -1
        If sh1.Cells(i, 1).Value <> sh1.Cells(i - 1, 1).Value Then
            sh1.Cells(i, 1).EntireRow.Insert
        End If
    Next i

End Sub

答案 2 :(得分:1)

这是使用Excel内置小计的另一种方法。它不是用于插入行本身,但如果您的最终目标是小计B列,则可能更合适。

Sub InsertSubtotals()

    Dim rTransactions As Range
    Dim sh1 As Worksheet

    Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
    sh1.Range("A1").EntireRow.Insert
    sh1.Range("A1:B1").Value = Array("Type", "Amount")

    Set rTransactions = sh1.Range("A1", sh1.Cells(sh1.Rows.Count, 1).End(xlUp))

    rTransactions.Resize(, 2).Subtotal 1, xlSum, Array(2)

End Sub