SUMPRODUCT公式,工作表数量不断变化

时间:2017-09-11 09:06:53

标签: excel

我有一个包含多个工作表的Excel工作簿,我想使用SUMPRODUCT公式对所有工作表中的值进行求和,其名称为 Page 1,Page 1(2),Page 1(3),Page 1(4) 等:

=SUMPRODUCT(SUMIF(INDIRECT("'"&D2:D4&"'!B11:B100"),$B3,INDIRECT("'"&D2:D4&"'!E11:E100")))

问题是 Page 1 工作表的数量每次都不同,我需要每次手动更新&D2:D4&。有什么方法可以让它自动化,所以我不需要手动更改范围吗?

1 个答案:

答案 0 :(得分:0)

请将以下代码粘贴到您拥有SUMPRODUCT公式的工作簿的ThisWorkbook代码表中。然后调整代码以符合我添加到其中的注释(特别是关于您具有范围D2的工作表的名称:D4。

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    SetPageRange
End Sub

Private Sub SetPageRange()

    ' this procedure creates a named range "Pages" which you can
    ' use in your formula instead of "D2:D4"
    ' =SUMPRODUCT(SUMIF(INDIRECT("'"& Pages &"'!B11:B100"),$B3,INDIRECT("'"& Pages &"'!E11:E100")))


    Const WsName As String = "Page"             'Page, Page (1), Page(x)
                                                ' change to "Page 1" if that is what you need

    Dim Wb As Workbook
    Dim MasterWs As Worksheet
    Dim Arr() As String
    Dim i As Integer
    Dim Ws As Worksheet

    ' the Active workbook is not necessarily the workbook containing this code !!
    Set Wb = ActiveWorkbook
    ReDim Arr(1 To 20)                          ' maximum number of sheets you expect
                                                ' this number of rows must be available
                                                ' below D2 in the sheet where your
                                                ' formula resides

    For Each Ws In Wb.Worksheets
        ' this collects all sheets whose name starts with "Page"
        If InStr(1, Ws.Name, WsName, vbTextCompare) = 1 Then
            i = i + 1
            Arr(i) = Ws.Name
        End If
    Next Ws

    ' Change the name "Sheet5" to the name of the sheet where your
    ' SUMPRODUCT formula resides and where you currently have D2:D4
    ' if it isn't in the ActiveWorkbook, then where is it?
    Set MasterWs = Wb.Worksheets("Sheet5")
    With MasterWs.Cells(2, "D")             ' this is where the names will be written
                                            ' from D2 down (20 rows, as set above)
        .Resize(UBound(Arr)).Value = Application.Transpose(Arr)
        Wb.Names.Add Name:="Pages", RefersTo:="=" & .Resize(i).Address(True, True, xlA1, True)
    End With
End Sub

将工作簿保存为启用宏(xlsm格式)现在,此代码将在您保存工作簿时自动运行。我想你会打开它,导入一些“第1页”表,然后想要总计。所以,现在你必须先保存它。范围D2:D4(我的代码中为D2:D20)将自动调整。

如果您不喜欢自动化,请完全删除Workbook_BeforeSave程序(或在每行的开头放置一个撇号)。您可以通过将光标放在其中的任何位置并按F5来手动运行SetPageRange过程。通过将属性Private更改为Public,您可以从Excel的工作表界面中运行它。

代码将创建一个名为“Pages”的命名范围,您需要将公式更改为指向命名范围(代码操作的大小和内容),而不是当前的“D2:D4”。修订后的公式包含在上面的代码评论中。