我一直在使用此语法将总行添加到一个工作表
With ActiveSheet
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
LastRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
LastRow = 1
End If
End With
Range("C" & LastRow + 1).FormulaR1C1 = "=SUM(R[-" & LastRow & "]C:R[-1]C)"
Range("C" & LastRow + 1 & ":L" & LastRow + 1).FillRight
我想将它添加到工作簿中的所有工作表中,我只需要像这样添加一个foreach循环
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
'code above
Next
但这不符合法案,因为我使用With ActiveSheet
它只会增加多个&#34; Total&#34;行到选定的工作表。
如何在工作簿中的每个工作表中添加总行?
答案 0 :(得分:0)
试试这个。我没有测试过它。你测试代码,让我知道如果有错误,我会继续处理 -
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
LastRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
LastRow = 1
End If
End With
ws.Range("C" & LastRow + 1).FormulaR1C1 = "=SUM(R[-" & LastRow & "]C:R[-1]C)"
ws.Range("C" & LastRow + 1 & ":L" & LastRow + 1).FillRight
Next
答案 1 :(得分:0)
您只需要确保激活每个工作表:
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.activate
'code above
Next
应该这样做。