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

  • 本文关键字:VBA Excel 于另一 excel vba
  • 更新时间 :
  • 英文 :


在excel中使用vba,我试图在A列中的特定文本之后添加新的行,然后总结B。

中的成本。

此新行应为指定的文本" Apple",并在A列中添加总数。在B列中,它应该简单地总结所有" Apple"s。

A列A随机数量有3种类型的水果(苹果,橙子和香蕉(。

B列的每个苹果,橙色和香蕉的成本。

它应该看起来像这样

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

您可能需要更改循环的界限(我只能通过第20行(。当值也以货币为单位时,这将起作用。

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

最新更新