不同工作表(同一单元格)中的总和值

Sum Values in different worksheets (same cell)

我有一个包含多张工作表的工作簿,每个项目的工作簿数量可能会发生变化,但它们都以 PAF 结尾。 table 在所有工作表和单元格中都相同。

我有一个与 table 完全相同的摘要选项卡,我只需要在那里汇总所有内容,table 至少有 6 列和 20 行,因此每个单元格都需要相同的公式(基本上)所以我想出了以下但我收到错误。有什么建议吗?

Sub SumPAF
Dim ws as Worksheet
Sheets("Summary PAF").Activate

For Each ws In ActiveWorkbook.Worksheets
If ws.Name Like "PAF" Then

Range("E10") = WorksheetFunction.Sum(Range("E10"))

End If
Next
End Sub

它卡在“For Each”中说需要一个对象...

我已经对代码进行了注释,因此您理解它应该没有问题。

Option Explicit

Sub SumPAF()
    Dim ws As Worksheet
    
    '~~> This will store the cell addresses
    Dim sumFormula As String
    
    '~~> Loop though each worksheet and check if it ends with PAF
    '~~> and also to ingore summary worksheet
    For Each ws In ActiveWorkbook.Worksheets
        If UCase(ws.Name) Like "*PAF" And _
        InStr(1, ws.Name, "Summary", vbTextCompare) = 0 Then _
        sumFormula = sumFormula & "," & "'" & ws.Name & "'!E10"
        '~~> or simply 
        'sumFormula = sumFormula & ",'" & ws.Name & "'!E10"
    Next
    
    '~~> Remove the intital ","
    sumFormula = Mid(sumFormula, 2)
    
    '~~> Insert the sum formula
    If sumFormula <> "" Then _
    Sheets("Summary PAF").Range("E10").Formula = "=SUM(" & sumFormula & ")"
End Sub

这里有一个非常简单易懂的程序来说明 VBA 如何用于范围内的循环。如果您有任何问题,请随时提问:

Sub SumPAF()
    'Save a reference to the Summary Sheet
    Dim SummarySheet As Worksheet
    Set SummarySheet = Sheets("Summary PAF")
    
    'Save a reference to the Summary Table and decide the table dimensions
    Dim SummaryTable As Range
    Set SummaryTable = SummarySheet.Range("A1:F20")
    
    'Create an array to save the sum values
    Dim SumValues() As Double
    ReDim SumValues(1 To SummaryTable.Rows.Count, 1 To SummaryTable.Columns.Count)
    
    'Loop through the workbook sheets
    Dim ws As Worksheet, TableRange As Range
    For Each ws In ActiveWorkbook.Worksheets
        'Find sheets ending in PAF other than the summary PAF
        If ws.Name Like "*PAF" And Not ws.Name = SummarySheet.Name Then
            'create a reference to a range on the sheet in the same place and dimensions as the summary table
            Set TableRange = ws.Range(SummaryTable.Address)
            
            'loop through the range, cell by cell
            Dim i As Long, j As Long
            For i = 1 To TableRange.Rows.Count
                For j = 1 To TableRange.Columns.Count
                    'Sum each cell value into the array, where its cell address is the array coordinates.
                    SumValues(i, j) = SumValues(i, j) + TableRange.Cells(i, j).Value
                Next j
            Next i
        End If
    Next
    
    'Output the array into the summary table
    SummaryTable.Value = SumValues
End Sub