使用VBA的迭代SUMIF函数

时间:2014-06-09 01:34:59

标签: excel-vba vba excel

考虑下表:

enter image description here

我希望能够做的就是在右侧创建类似的东西。这基本上要求告诉Excel将单元格为零的所有值求和,直到遇到1,此时它应该再次开始计数。我想这可以使用VBA完成,所以我只需要确定如何实际设置该代码。我想构建块应该是这样的:

Dim row As Long

Dim sum As List

row = Excel row definition

While ColB <> ""

  If ColB.value = 0 
  Append ColC.value to Sum
  Else Do Nothing

row = row + 1

Loop

非常感谢任何有关代码结构和语法的帮助。

1 个答案:

答案 0 :(得分:1)

试试这个:

Sub test()
    Dim cel As Range, sRng As Range, oRng As Range, Rng As Range
    Dim i As Long: i = 1

    On Error GoTo halt
    With Sheet1
        .AutoFilterMode = False
        Set Rng = .Range("B1", .Range("B" & .Rows.Count).End(xlUp))
        Rng.AutoFilter 1, 0
        Set sRng = Rng.Offset(1, -1).Resize(Rng.Rows.Count - 1) _
            .SpecialCells(xlCellTypeVisible)
        Rng.AutoFilter 1, 1
        Set oRng = Rng.Offset(1, 0).SpecialCells(xlCellTypeVisible)
        .AutoFilterMode = False
    End With

    If sRng.Areas.Count >= oRng.Areas.Count Then i = 2
    For Each cel In oRng.Areas
        If i > sRng.Areas.Count Then Exit For
        If cel.Cells.Count = 1 Then
            cel.Offset(0, 1).Formula = _
                "=SUM(" & sRng.Areas(i).Address(True, True) & ")"
        Else
            cel.Cells(cel.Cells.Count).Offset(0, 1).Formula = _
                "=SUM(" & sRng.Areas(i).Address(True, True) & ")"
        End If
        i = i + 1
    Next
Exit Sub
halt:
    Sheet1.AutoFilterMode = False
End Sub

<强> EDIT1:
无论您在B列中有多少零或一个,上述情况均有效。
如果发生错误,它将退出。我将编码留给你想要处理错误的方式。