列表中的EXCEL VBA计算总和取决于其他单元格值

时间:2013-01-18 10:46:02

标签: excel vba excel-vba

我正在VBA中寻找一种方法来根据另一个Cell的值

来总结值

示例源表:

 BillNr   Pos   Value

  200        0  sum
  200        1  10,00 €
  200        2  15,00 €
  200        3  31,00 €
  200        4  21,00 €
  200        5  19,00 €
  200        6  81,00 €
  201        0  sum
  201        1  14,00 €
  201        2  18,00 €
  212        0  sum
  212        1  31,00 €
  212        2  19,00 €
  212        3  78,00 €

根据BillNr中的数字,VBA代码应对Value中的所有值求和,并在名为Number的单元格中显示sum。实际上List是关于15000行的长度,所以我想它需要被包裹在循环中?

1 个答案:

答案 0 :(得分:0)

选择:)

<强> VBA

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim aCell As Range, bCell As Range
    Dim ExitLoop As Boolean

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Find "sum" in Col C
        Set aCell = .Columns(3).Find(What:="sum", LookIn:=xlValues, _
                    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                    MatchCase:=False, SearchFormat:=False)
        If Not aCell Is Nothing Then
            Set bCell = aCell

            '~~> If found Calculate the sum
            aCell.Value = Application.Evaluate("=SUMIF(A:A,A" & aCell.Row & ",C:C)")

            '~~> Find the next "Sum"
            Do While ExitLoop = False
               Set aCell = .Columns(3).FindNext(After:=aCell)

               If Not aCell Is Nothing Then
                   If aCell.Address = bCell.Address Then Exit Do
                   aCell.Value = Application.Evaluate("=SUMIF(A:A,A" & aCell.Row & ",C:C)")
               Else
                   ExitLoop = True
               End If
            Loop
        End If
    End With
End Sub

<强> 截图

enter image description here

非VBA(使用Pivot和Vlookup)

创建Pivot后,我在Col D中使用Vlookup。您可以在Autofilter中设置Col C以过滤sum,然后将公式放入Col C

中的相关单元格中

enter image description here