excel - 不同工作表(同一单元格)中的值求和

标签 excel vba sum

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

我有一个带有完全相同表格的摘要选项卡,我只需要在那里总结所有内容,该表格至少有 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

关于excel - 不同工作表(同一单元格)中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68713777/

相关文章:

excel - LOOKUP 函数未给出预期结果

javascript - nodejs - 帮助 "promisifying"使用嵌套 promise 读取文件

vba - 一年中的天数 Excel VBA

sql - SELECT SUM 在没有记录时返回一行

mysql - 连接 2 表 Mysql 的查询中的计算

excel - 登录后如何网页抓取 Steam?

excel - 删除工作表中的所有空格

excel - 当我从 Excel 发送电子邮件时,为什么 Attachments.Add 不起作用?

excel - 突出显示选定的行和列

java - Java 中的高尔夫得分数组