总和两个特殊标记之间的小范围

问题描述 投票:0回答:2

样本数据:

Column A       Column B

63843       
60208        
57606   
130717           1    
190407   
186980           1    
167839   
180043   
174384           1   
170289           1  
107142   
87628      
41637  
48807            1    
57602   
51537   

A列是浓度,B列是标记。

我想将一个标记后的浓度与下一个标记相加到一个新列(C列),“1”以外的浓度是一个总和的最后一个元素。例如:sum(63843:130717),sum(190407:186980),sum(167839:174384)等。

如果标记相互粘连,如174384与170289之间,则总和为170289。

我希望我能清楚地表达出来。我知道我应该在这部分写一些代码,但我完全不知道。我想我应该使用类似的东西:

范围(“C1:C”和lastrow).Formula =“= IF(B1 = 1,TEXT(SUM(...........),”“.......... ......... “”), “”, “”)”

非常感谢。

vba
2个回答
1
投票
Dim Lastrow As Long
With ActiveSheet
    Lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
    .Range("C1").Formula = "=IF(B1=1,A1,"""")"
    .Range("C2:C" & Lastrow).Formula = "=IF(B2=1,SUM($A$1:A2)-SUM($C$1:C1),"""")"
End With

enter image description here


1
投票

VBA解决方案:

编辑:已经实现我在我的例子中错过了1,所以它与你的不匹配,但你得到了我想的要点。

Option Explicit
Sub SumBetweenMarks()
Dim sht As Worksheet, lastrow As Long, myvalue As Long, i as long

Set sht = ActiveSheet
lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

myvalue = 0
For i = 1 To lastrow
    If Range("B" & i).Value <> 1 Then
        myvalue = myvalue + Range("A" & i).Value
    Else
        myvalue = myvalue + Range("A" & i).Value
        Range("C" & i).Value = myvalue
        myvalue = 0
    End If
Next i
End Sub

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.