0

我正在寻找一种在 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 €

根据BillNrVBA 代码中的数字,应将所有值相加Value并显示Number在被调用的单元格中sum。实际上,列表是关于15000行长的,所以我想它需要被包裹在循环中?

4

1 回答 1

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

截屏

在此处输入图像描述

非 VBA(使用 Pivot 和 Vlookup)

创建 Pivot 后,我Vlookup​​在 Col D 中使用。您可以设置Autofilter进行Col C过滤sum,然后将公式放入相关单元格中Col C

在此处输入图像描述

于 2013-01-18T11:18:06.733 回答