繁体   English   中英

汇总与另一列相关的唯一值的宏

[英]Macros to sum unique values related to another column

我需要创建宏以填充“指标计算器”选项卡,即每个“研究”(D 列)的“测试步骤数”(G 列)的总和。 总和应仅考虑唯一值。 请看下表:桌子

在这项研究中,没有“1111”,总步数/患者没有“20”重复 3 次,“15”重复 4 次,“30”重复 3 次 - 我需要宏来获取唯一值并添加,即仅 20+ 15+30=65。

在指标计算器选项卡中”-它应该带有输出

研究编号 步骤总数 1111 65

因此,如果我理解了这个问题,您想对 B 列中的唯一值求和。以下内容可以解决问题。

请注意,您需要根据需要调整范围。 现在范围设置为 B2:B20,如您的示例表中所示。

Sub unique()
    Dim arr() As Variant
    Dim arrElem As Variant
    Dim Rng As Range
    Dim elem As Range
    Dim i As Long
    Dim stepSum As Long
    Dim match As Boolean

    Set Rng = Range("B2:B20") 'Edit this so that it fits your array

    'this sets up an array to store unique variables
    ReDim Preserve arr(1 To 1) As Variant
    arr(1) = 0

    'this loops through each number in the identified range
    For Each elem In Rng

      'this is a boolean, false means the current number is unique (so far) true means the number has been seen previously.
      match = False

      'this checks the current number against all the unique values stored in the array
      For Each arrElem In arr
          'If it finds a match, it changes the boolean to true
          If arrElem = elem Then match = True
      Next arrElem

      'If not match was found, we store the current number as a new unique value in the array
      If match = False Then
        'this adds another row to the array
        ReDim Preserve arr(1 To UBound(arr) + 1) As Variant
        'this adds the unique value
        arr(UBound(arr)) = elem.Value
      End If

    Next elem

    'this sums the unique numbers we stored in the array
    For i = 1 To UBound(arr)
        stepSum = stepSum + arr(i)
    Next i

    'this reports the sum of unique elements
    MsgBox stepSum

End Sub

查看此示例:

在此处输入图片说明

在我们的示例中,“B 列”中的单元格(供应商名称)被列为“K 列”中的唯一值:

Columns("B:B").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Columns( _
        "B:B"), CopyToRange:=Range("'Sheet1'!K1"), Unique:=True

后来,为了对“L”列中的这些项目(I 列中的金额)求和,我们使用循环将 SUMIF 公式输入到 L 列中的单元格:

For i = 2 To Cells(Rows.Count, 11).End(xlUp).Row
       Cells(i, "L").FormulaR1C1 = "=SUMIF(C[-10],RC[-1],C[-3])"
Next i

来源: Excel vba sum 唯一项

暂无
暂无

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

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