帮我写一段Vba将每个工作表对应单元格相加
时间: 2023-12-14 12:35:59 浏览: 140
以下是一段VBA代码,可以将每个工作表对应单元格相加并在新工作表中显示结果:
```VBA
Sub SumWorksheets()
Dim ws As Worksheet
Dim totalSum As Double
Dim newWS As Worksheet
'Create new worksheet for results
Set newWS = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
newWS.Name = "Total"
'Iterate through each worksheet and sum corresponding cells
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> newWS.Name Then 'Exclude new worksheet from calculation
totalSum = Application.WorksheetFunction.Sum(ws.Range("A1:B2")) 'Change range as needed
newWS.Cells(ws.Index, 1).Value = ws.Name
newWS.Cells(ws.Index, 2).Value = totalSum
End If
Next ws
End Sub
```
该代码将创建一个名为“Total”的新工作表,并在其中列出每个工作表的名称和对应单元格的总和。您需要根据实际情况更改代码中的范围。
阅读全文