每行Sumifs vba循环

时间:2019-03-07 09:54:26

标签: excel vba

我正在尝试做一个宏,该宏基于一个条件(该条件由每行的第一个单元格的值设置)来进行求和。表2是我想要的结果。在Excel = Sumifs(Sales; Store; nStore; Retailer; nRetailer)中看起来是什么

enter image description here

2 个答案:

答案 0 :(得分:0)

字典会构建一个快速的SUMIF并在此过程中构建唯一的零售商列表。

Sub mySumIf()

    Dim i As Long, arr As Variant, retailer As string, dict As Object

    Set dict = CreateObject("scripting.dictionary")
    dict.comparemode = vbTextCompare

    With Worksheets("tab 1")
        'collect source values into array
        arr = .Range(.Cells(2, "A"), .Cells(.Rows.Count, "C").End(xlUp)).Value2
    End With

    retailer = UCase(Worksheets("tab 2").Cells(4, "F").Value2)

    'build a dictionary with Stores as keys and Sales as Items
    For i = LBound(arr, 1) To UBound(arr, 1)
        If UCase(arr(i, 2)) = retailer Then
            dict.iktem(arr(i, 1)) = dict.iktem(arr(i, 1)) + arr(i, 3)
        End If
    Next i

    With Worksheets("tab 2")
        'put Stores and Summed Sales onto target worksheet
        .Cells(6, "E").Resize(dict.Count, 1) = Application.Transpose(dict.keys)
        .Cells(6, "F").Resize(dict.Count, 1) = Application.Transpose(dict.items)
    End With

End Sub

答案 1 :(得分:0)

您可以尝试合并方法:

步骤:

  1. 选择要插入总计的单元格(在我的方案中为D1单元格)
  2. 转到数据-数据工具-合并
  3. 参考
  4. 中选择整个数据范围( A1:B9
  5. 添加
  6. 确定

结果:

enter image description here