简体   繁体   English

VBA-条件求和B列,直到A列中的值更改

[英]VBA - conditional Sum column B until change of value in column A

Basic explanation. 基本说明。 I am collecting all my multiple invoice data in one spreadsheet. 我正在一个电子表格中收集所有所有发票数据。 Lets say I have only two columns that seperate each of the different invoice: 可以说,我只有两列分别分隔每个不同的发票:

Serial ID.    Value

ABC001        $5.00
ABC001        $5.00
ABC001        $5.00
CBA100        $6.00
CBA100        $4.00
CBA100        $5.00

I want a VBA solution that would loop through columns, sum values in columnB UNTIL there is a change in columnA and THEN would put that sum value on columnC LAST ROW BEFORE THE CHANGE in columnA. 我想要一个VBA解决方案,该解决方案将遍历各列,直到B列中的值求和,然后再将B列中的值求和,然后再将C列中的求和值放在C列中的最后一行。 The outpoot would look like this: 任务看起来像这样:

Serial ID.    Value   Total

ABC001        $5.00   
ABC001        $5.00
ABC001        $5.00   $15.00
CBA100        $6.00
CBA100        $4.00
CBA100        $5.00   $15.00

So far the closest thing I found was the solution by D Mason 到目前为止,我发现最接近的是D Mason的解决方案

But the problem with his code that the sum of the values in columnB adress is in EXACT row number WHERE THE CHANGE HAPPENS (not BEFORE), and it would run like this: 但是他的代码存在问题,即columnB地址中的值之和在确切的行号中发生了变化(不是之前),并且它将像这样运行:

Serial ID.    Value   Total

ABC001        $5.00   $15.00   
ABC001        $5.00
ABC001        $5.00
CBA100        $6.00   $15.00
CBA100        $4.00
CBA100        $5.00

I am sure, that I made my problem clear. 我敢肯定,我已经明确了我的问题。 But just in case, the Serial Id will always stay in the same column, so will values. 但以防万一,串行ID始终会保留在同一列中,值也会保留在同一列中。 No sort will be performed. 不会执行任何排序。 Sum if of whole range also is not good for me, becouse there may be duplicate invoices, and if function would take range (A:A) to lookup a conditional serial number, it would produce a false result. 如果整个范围的总和对我也不好,因为可能有重复的发票,并且如果函数使用范围(A:A)查找条件序列号,则会产生错误的结果。 Thank you in advance, if there is some ways I could improve my question (if I get a correct answer and want it to be easier to find for others with the same problem), write a suggestion. 在此先感谢您,如果有一些方法可以改善我的问题(如果我得到了正确的答案,并希望更容易找到其他遇到相同问题的人),请提出建议。

Please give this a try... 请尝试一下...

Sub GetTotal()
Dim rng As Range, cell As Range
Dim lr As Long
Dim Total As Double

Application.ScreenUpdating = False
lr = Cells(Rows.Count, 1).End(xlUp).Row
Set rng = Range("A2:A" & lr)
For Each cell In rng
    If cell = cell.Offset(1) Then
        Total = Total + cell.Offset(0, 1)
    Else
        Total = Total + cell.Offset(0, 1)
        cell.Offset(0, 2) = Total
        Total = 0
    End If
Next cell
Columns("C").NumberFormat = "$#,##0.00"
Application.ScreenUpdating = True
End Sub

Can you try following formula. 您可以尝试以下公式吗?

=IF(A2<>A1,SUMIF(A:A,A2,B:B),"")

Put the formula C2 cell as shown in screenshot. 如屏幕快照所示,放入公式C2单元格。

屏幕截图

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

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