如果重复,则计算重复项,匹配列并计算总和

时间:2015-09-01 14:06:35

标签: excel vba excel-vba

样本数据:

Column A       Column B       Column C        Column D
Example 1      5              Example 1       13
Example 1      2              Example 2       8
Example 1      4
Example 1      2
Example 2      2
Example 2      4
Example 3      2

bad pseudo:

  • 通过A列循环检查重复项
  • 如果发现重复,请增加重复计数器并存储在数组中?
  • 然后写下#'示例#'到C栏
  • 使用计数器在B列中的行之间跳转,并在D列中总结值和输出

英语:

  • 为每个'示例#'
  • 添加所有值
  • 输出'示例#'到指定的列/行
  • 将值和值输出到指定的列/行

有更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

由VBA创建的数据透视表(通过记录宏):

Sub MacroPT()
    Application.CutCopyMode = False
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Sheet1!R1C1:R1048576C2", Version:=xlPivotTableVersion15).CreatePivotTable _
        TableDestination:="Sheet1!R1C3", TableName:="PivotTable1", DefaultVersion _
        :=xlPivotTableVersion15
    Sheets("Sheet1").Select
    Cells(1, 3).Select
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Column A")
        .Orientation = xlRowField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Column B")
        .Orientation = xlColumnField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Column B"), "Count of Column B", xlCount
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Count of Column B")
        .Caption = "Sum of Column B"
        .Function = xlSum
    End With
    ActiveSheet.PivotTables("PivotTable1").CompactLayoutRowHeader = "Column C"
    Range("D1").Select
    ActiveSheet.PivotTables("PivotTable1").DataPivotField.PivotItems( _
        "Sum of Column B").Caption = "Column D"
    Range("C3").Select
    With ActiveSheet.PivotTables("PivotTable1")
        .ColumnGrand = False
        .RowGrand = False
    End With
End Sub  

Example 2导致6,而不是8