vba - Excel VBA - 两个值之间的总和

标签 vba excel

我有一个报告,我正在尝试获取动态行数的总和以生成小计。

If Cells(s, 1).Value = "start" Then
   If Cells(r, 1).Value = "subtotal" Then
    'Set the Monthly Subtotal Formulas
     Cells(r, 44) = "=SUM(AR" & Trim(Str(s)) & ":AR" & Trim(Str(r - 1)) & ")"
     Cells(r, 46) = "=SUM(AT" & Trim(Str(s)) & ":AT" & Trim(Str(r - 1)) & ")"
    'Set the Weekly Subtotal Formulas
     Cells(r, 48) = "=SUM(AV" & Trim(Str(s)) & ":AV" & Trim(Str(r - 1)) & ")"
     Cells(r, 52) = "=SUM(AZ" & Trim(Str(s)) & ":AZ" & Trim(Str(r - 1)) & ")"
     'Set the Daily Subtotal Formulas
     Cells(r, 54) = "=SUM(BB" & Trim(Str(s)) & ":BB" & Trim(Str(r - 1)) & ")"
     Cells(r, 56) = "=SUM(BD" & Trim(Str(s)) & ":BD" & Trim(Str(r - 1)) & ")"
     'Set the Hourly Formulas
     Cells(r, 60) = "=SUM(BH" & Trim(Str(s)) & ":BH" & Trim(Str(r - 1)) & ")"
     Cells(r, 62) = "=SUM(BJ" & Trim(Str(s)) & ":BJ" & Trim(Str(r - 1)) & ")"
     Cells(r, 1) = ""
    End If
    Cells(s, 1) = ""
End If

基本上,每个工作组都位于单元格值“开始”和“小计”内。 如何找到“s”或行号并在公式中使用它?

最佳答案

大多数时候, built-in subtotals feature of Excel 应该足够了

<小时/>

如果您确实需要使用 VBA 解决方案并且不知道如何迭代数据中已存在的所有“小计”标签,请将代码放入如下循环中:

header_column = Intersect(ActiveSheet.Range("A:A"), ActiveSheet.UsedRange).Value2
s = 1
For r = 1 To UBound(header_column)
    If header_column(r, 1) = "start" Then
        s = r
    End If
    If header_column(r, 1) = "subtotal" Then
        ' ... do your stuff here ... '
        ' s = r ' if the next "start" tag always follows a subtotal tag, no need for the "start" tags at all, just uncomment this line just before End If
    End If
Next

P.S.:不需要"string"& Trim(Str(integer)),使用"string"& integer代替

关于vba - Excel VBA - 两个值之间的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11103822/

相关文章:

excel - 雅虎财经历史股价幂查询返回301响应

excel - VBA 从监 window 口打开 Outlook

excel - 在VBA中粘贴特殊值

C# 互操作 - 迭代行并删除

vba - 如果我在整个文件上运行子例程,Excel 会崩溃,但在分段中运行正常

vba - 如何在VBA中给单元格填充颜色?

excel - 复制多个工作表列中的纯值单元格并粘贴到一列中

excel:如何将概率与 "or"结合起来?

vba - 平均公式 Excel VBA

php - 将excel数据映射到mysql数据库