2017-04-16 80 views
0

我想寫一個VBA代碼,只要值爲「1」就對行的值進行求和,然後總計行的值,只要該值爲「 - 」 1「,然後循環直到該行爲空。VBA:根據重複條件分別合計行值

見所附截屏

enter image description here

請注意,標準不重複5次,而是經常變化。

+1

你嘗試過這麼遠嗎?分享你的代碼嘗試。 –

+0

請閱讀:https://stackoverflow.com/help/how-to-ask –

+0

嗨,嗨,我真的還沒有試圖拿出代碼呢。我瀏覽過去,看看過去有沒有相關的帖子可以適應我的需求。 – jason

回答

0

我寫了下面的代碼,這似乎工作。它期望您選擇要加總的值的列(最後不要有空格),並根據右邊的列將相關總計添加到第三列。

Sub MyProc() 

Dim inputRange As Range 
Set inputRange = Selection 

Dim Cell As Range 
Dim RunningTotal As Integer 
Dim VerticalOffset As Integer 

Dim PreviousCellFlag As Integer 
PreviousCellFlag = 0 

For Each Cell In inputRange 

    If Cell.Offset(0, 1) <> PreviousCellFlag Then 

     PreviousCellFlag = Cell.Offset(0, 1) 
     RunningTotal = 0 
     VerticalOffset = 0 

     While Cell.Offset(0, 1) = Cell.Offset(VerticalOffset, 1) 
      RunningTotal = RunningTotal + Cell.Offset(VerticalOffset, 0).Value 
      VerticalOffset = VerticalOffset + 1 
     Wend 

     Cell.Offset(0, 2) = RunningTotal 
    Else 
     Cell.Offset(0, 2) = "" 
    End If 

Next Cell 

End Sub 
2

如果你的數據在A2開始,用這個公式在C2然後複製/粘貼在C列:

=IF(B2=B1,"",SUMPRODUCT(OFFSET(A2,,,MATCH(TRUE,B3:B$1000<>B2,0))))