我试图创建一个Excel宏来搜索Sheets("Data").Range("B:" & lastRow)
的值" 0"。
如果找到一个值为" 0"在B列中,我需要将它与SUM合并,并将该行与其上方的行合并。
我有以下代码,但我收到错误,而我无法弄清楚我做错了什么:
Sub sumZeroRows()
Dim ws As Worksheet
Dim lastrow As Long
Dim i As Long
Set ws = Sheets("Data")
With ws
lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
For i = lastrow To 11 Step -1
If .Cells(i, "B").Value = "0" Then
.Cells(i - 1, "C").Value = .Cells(i - 1, "C").Value2 + .Cells(i, "C").Value2
.Cells(i - 1, "D").Value = .Cells(i - 1, "D").Value2 + .Cells(i, "D").Value2
.Cells(i - 1, "E").Value = .Cells(i - 1, "E").Value2 + .Cells(i, "E").Value2
.Cells(i - 1, "F").Value = .Cells(i - 1, "F").Value2 + .Cells(i, "F").Value2
.Cells(i - 1, "G").Value = .Cells(i - 1, "G").Value2 + .Cells(i, "G").Value2
.Cells(i - 1, "H").Value = .Cells(i - 1, "H").Value2 + .Cells(i, "H").Value2
.Cells(i - 1, "I").Value = .Cells(i - 1, "I").Value2 + .Cells(i, "I").Value2
.Cells(i - 1, "J").Value = .Cells(i - 1, "J").Value2 + .Cells(i, "J").Value2
.Cells(i - 1, "K").Value = .Cells(i - 1, "K").Value2 + .Cells(i, "K").Value2
.Cells(i - 1, "L").Value = .Cells(i - 1, "L").Value2 + .Cells(i, "L").Value2
.Cells(i - 1, "M").Value = .Cells(i - 1, "M").Value2 + .Cells(i, "M").Value2
.Cells(i - 1, "N").Value = .Cells(i - 1, "N").Value2 + .Cells(i, "N").Value2
.Cells(i - 1, "O").Value = .Cells(i - 1, "O").Value2 + .Cells(i, "O").Value2
.Cells(i - 1, "P").Value = .Cells(i - 1, "P").Value2 + .Cells(i, "P").Value2
.Cells(i - 1, "Q").Value = .Cells(i - 1, "Q").Value2 + .Cells(i, "Q").Value2
.Cells(i - 1, "R").Value = .Cells(i - 1, "R").Value2 + .Cells(i, "R").Value2
.Rows(i).Delete
End If
Next i
End With
End Sub
我的单元格看起来像。
答案 0 :(得分:2)
这样做你想要的:
Sub sumZeroRows()
Dim ws As Worksheet
Dim lastrow As Long
Dim i As Long
Set ws = Sheets("Data")
With ws
lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
For i = lastrow To 11 Step -1
If .Cells(i, "B").Value = "0" Then
.Cells(i - 1, "C").Value = .Cells(i - 1, "C").Value2 + .Cells(i, "C").Value2
.Cells(i - 1, "D").Value = .Cells(i - 1, "D").Value2 + .Cells(i, "D").Value2
.Rows(i).Delete
End If
Next i
End With
End Sub
删除行时需要向后循环。并分别对每一列进行总结。