Excel VBA - 两个数值之间求和

3
我有一个报表,我正在尝试获取动态行数的总和以生成小计。
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”的行号并在公式中使用它呢?


1
你只是想在每个工作表中找到“Start”和“Subtotal”的每个实例,并处理每个块的公式吗?如果是这样,请参阅.Find和.FindNext方法。 - Scott Holtzman
你能展示一下你的数据快照吗?也许有更简单的方法? - Siddharth Rout
1
内置小计有什么问题? - Aprillion
这需要是报告生成人员不必自己完成的内容,因为报告可能包含大量需要总计的数据。 - PlatiNUM
@PlatiNUM,如果我的回答符合您的需求,请查看它 - 如果不是,请重新表达您的问题。 - Aprillion
显示剩余3条评论
1个回答

2
大多数情况下,Excel的内置小计功能应该足够使用。
如果您确实需要使用VBA解决方案,并且不知道如何在数据中迭代所有已存在的“subtotal”标记,请将您的代码放置在类似以下的循环内部:
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

附言:不需要使用"string"和Trim(Str(integer)),可以直接使用"string"和integer。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接