繁体   English   中英

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

[英]EXCEL VBA calc sum in list depending on other cell value

我正在VBA中寻找一种方法来基于另一个单元格的值求和

源表示例:

 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 实际上,该列表大约有15000行,所以我想它需要循环包装吗?

随便挑:)

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

屏幕截图

在此处输入图片说明

非VBA(使用数据透视和Vlookup)

创建数据透视后,我在D Vlookup中使用了Vlookup 您可以在Col C设置Autofilter过滤器以对sum进行过滤,然后将公式放入Col C中的相关单元格中

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM