excel - 不同表的动态范围总和

标签 excel vba dynamic sum

我想知道您是否可以帮我找到一种方法来编写对不同表中的动态范围求和的 vba 代码。

我正在尝试对不同表中的值进行求和(其行数会发生变化)。

这些表格都在同一张纸上,如下所示:

enter image description here

我尝试通过宏记录器编写代码(请参见下文),但是,我正在努力寻找如何使其动态化。

Range("B3").Select
ActiveCell.FormulaR1C1 = "=SUM(R[6]C:R[9]C)"
Range("B4").Select
ActiveCell.FormulaR1C1 = "=SUM(R[12]C:R[14]C)"
Range("B5").Select
ActiveCell.FormulaR1C1 = "=SUM(R[17]C:R[19]C)"

感谢您的帮助!

最佳答案

范围求和

Option Explicit

Sub SumUpWeeks()
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim dlCell As Range: Set dlCell = ws.Cells(ws.Rows.Count, "B").End(xlUp)
    Dim srg As Range: Set srg = ws.Range("A7", ws.Cells(dlCell.Row, "A"))
    
    Dim drg As Range: Set drg = ws.Range("A3:B5")
    
    Dim drrg As Range
    Dim fCell As Range
    Dim lCell As Range
    Dim sString As String
    Dim sIndex As Variant
    
    For Each drrg In drg.Rows
        sString = CStr(drrg.Cells(1).Value)
        ' Get week index.
        sIndex = Application.Match(sString, srg, 0)
        If IsNumeric(sIndex) Then ' week found
            ' In column 'B' skip 'Money Spent'.
            Set fCell = srg.Cells(sIndex).Offset(2, 1)
            Set lCell = ws.Range(fCell, dlCell) _
                .Find("", dlCell, xlValues, xlWhole)
            If lCell Is Nothing Then ' last week
                If dlCell.Row = fCell.Row Then ' one entry
                    drrg.Cells(2).Formula = "=" & fCell.Address
                Else ' multiple entries
                    drrg.Cells(2).Formula = "=SUM(" & fCell.Address _
                        & ":" & dlCell.Address & ")"
                End If
            Else ' not last week
                If lCell.Row = fCell.Row Then ' one entry
                    drrg.Cells(2).Formula = "=" & fCell.Address
                Else ' multiple entries
                    drrg.Cells(2).Formula = "=SUM(" & fCell.Address _
                        & ":" & lCell.Offset(-1).Address & ")"
                End If
            End If
        Else ' week not found
            drrg.Cells(2).Value = vbNullString
        End If
    Next drrg
    
    MsgBox "Weeks summed up.", vbInformation
    
End Sub

关于excel - 不同表的动态范围总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71764480/

相关文章:

vba - 公共(public)变量超出范围

excel - 在 Excel 中定义单元格位置变量

delphi - 在 Delphi 中将静态数组作为动态数组的参数传递

python - 将 pandas Excel Dataframe 复制到没有索引标题的剪贴板

excel - 循环遍历已过滤的枢轴项目

vba - 如何以编程方式在 Word 中调出文档属性窗口并转到“摘要”选项卡?

动态大小的多维数组的 C++ 解决方法

java - 在 Apache POI 3.9 中使用 autosizeColumn 出现在同一列上的图像被拉伸(stretch)

excel - 如何在django中用空格指定列名

php - 动态预处理语句不好吗? (使用 php + mysqli)