vba, 多列多行, 每隔6行插入新的一行,该新行对上面的6行数据按列进行求和
时间: 2024-02-22 21:00:57 浏览: 216
您可以使用 VBA 中的 for 循环和 if 语句来实现该功能。下面是一个简单的示例代码:
```
Sub InsertRowAndSum()
Dim currentRow As Long
Dim lastRow As Long
Dim sumRange As Range
currentRow = 1
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Do While currentRow <= lastRow
If (currentRow - 1) Mod 6 = 0 And currentRow > 1 Then
' Insert a new row
Rows(currentRow).Insert Shift:=xlShiftDown
' Sum the values in the previous 6 rows by column
For i = 1 To 10 ' 假设有10列需要求和
Set sumRange = Range(Cells(currentRow - 7, i), Cells(currentRow - 2, i))
Cells(currentRow - 6, i).Value = WorksheetFunction.Sum(sumRange)
Next i
currentRow = currentRow + 1
lastRow = lastRow + 1
End If
currentRow = currentRow + 1
Loop
End Sub
```
在上面的代码中,我们使用了 Do While 循环来遍历每一行数据。当循环到每隔6行时,插入新的一行,并对上面的6行数据按列进行求和,然后继续往下遍历。请注意,我们使用 `currentRow - 1` 来判断是否为每隔6行,因为我们从第1行开始循环,而不是从第0行开始。
另外,代码中的 `10` 表示需要求和的列数,您可以根据实际情况进行修改。
阅读全文
相关推荐







