【问题标题】:VBA SUM Variable RangeVBA SUM 变量范围
【发布时间】:2015-06-18 14:07:11
【问题描述】:

如果满足特定条件,我想要一个代码来汇总变量行。 例如如果 A12 为数字且 B12 为空,则在单元格 C12 中插入一个公式以求和 C3:C11。 然后在 C22 和 C30 执行相同的操作。 我的问题是不知道如何定义起始行。

Sub Test()
Dim y As Variant
Dim r As Variant
Dim StartRow As Variant

   LastRow = Range("C" & Rows.Count).End(xlUp).Row
        For y = 3 To 500
            For r = 1 To LastRow

            If InStr(1, Cells(r, 1), "Amount") Then
                StartRow = r

            If IsNumeric(Cells(y, 1)) And IsEmpty(Cells(y, 2)) Then
            Cells(y, 3).Formula = "=SUM(C" & StartRow + 1 & ":C" & y - 1 & ")"
            End If
         End If
      Next r
  Next y

End Sub

【问题讨论】:

  • 你可以只用一个额外的列而不需要 VBA...
  • @LS_dev 因为这只是我整个代码的一部分,所以我想要 VBA 代码来执行这个,你能帮忙吗? ^ ^

标签: excel vba variables sum range


【解决方案1】:
Sub Test()
Dim y As Variant
Dim firstRow As Variant
Dim lastRow As Variant
lastRow = Range("C" & Rows.Count).End(xlUp).Row
firstRow = Cells(lastRow, 3).End(xlUp).Row
If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then
    Cells(lastRow + 1, 3).Formula = "=SUM(C" & firstRow & ":C" & lastRow & ")"
End If
For y = firstRow To 3 Step -1
    lastRow = Cells(y, 3).End(xlUp).Row
    firstRow = Cells(lastRow, 3).End(xlUp).Row
    If firstRow < 3 Then firstRow = 3
    If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then
        Cells(lastRow + 1, 3).Formula = "=SUM(C" & firstRow & ":C" & lastRow & ")"
    End If
    y = firstRow
    If firstRow = 3 Then Exit Sub
  Next y
End Sub

【讨论】:

  • 嗨,Abe,太棒了!有用!但是我可以知道如何插入这个条件吗? If IsNumeric(Cells(y, 1)) And IsEmpty(Cells(y, 2)) Then
  • 编辑了答案以包含它。让我知道它是否不起作用。我没有测试它。
  • 嗨,Abe,这非常有效!但是...还是一个问题,C12 中的公式变成了 SUM(C1:C11),我想要的是 C3:C11。我应该修改哪一部分?
  • 哈哈,我之前也把For y = firstRow To 3 Step -1从1改成了3,但是不行,所以才要问你。
  • 还有其他一些变化。用这个替换你的代码,看看它是否有效。
猜你喜欢
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多