简体   繁体   English

基于另一列Excel VBA中特定值的总计

[英]Sum totals based on specific value in another column excel VBA

Using VBA within excel, I am trying to add a new row after specific text in column a, then sum the costs that are in column b. 我在excel中使用VBA,我试图在a列中的特定文本之后添加一个新行,然后对b列中的成本求和。

This new row should take the specified text "apple" and add the word total to it in column a. 此新行应使用指定的文本“ apple”,并在a列中添加单词total。 in column b, it should simply sum all the "apple"s. 在b列中,它应该简单地将所有“苹果”加起来。

Column A has a random amount of 3 types of fruits (apples, oranges, and bananas). A列随机包含3种水果(苹果,橙子和香蕉)。

Column B has the cost of each apple, orange, and banana. B列包含每种苹果,橙和香蕉的成本。

It should look something like this 它应该看起来像这样

Apple $12    
Apple $12    
Apple $12    
orange $13    
orange $13    
Banana $7    
Banana $7

to

Apple $12    
Apple $12    
Apple $12    
Apple Total $36    
orange $13    
orange $13    
orange Total $26    
Banana $7    
Banana $7    
Banana Total $14

You may want to change the bounds for the loop (I only made it go through row 20). 您可能想更改循环的边界(我只使它通过了第20行)。 This will work when the values are in currency as well. 当值也以货币表示时,这将起作用。

Dim i As Integer
Dim j As Integer
Dim frt As String

j = 1

For i = 2 To 20
    If Cells(i, 1).Value <> Cells(i - 1, 1).Value Then
        Range("A" & i).EntireRow.Insert
        frt = Cells(i - 1, 1).Value & " Total"
        Cells(i, 1).Value = frt
        Cells(i, 2).Value = Application.WorksheetFunction.Sum(Range("B" & j, "B" & i - 1))
        j = i + 1
        i = i + 1
    End If
Next i

End Sub

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

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