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

时间:2018-05-30 10:32:53

标签: excel-vba excel-formula vba excel

我需要创建宏来填充"度量计算器"选项卡,每个"研究""测试步骤的数量和#34;(G列)的总和(D栏)。总和应仅考虑唯一值。请参阅下表: Table

在本研究中,没有' 1111',总步骤否/患者没有' 20'重复3次,' 15'重复4次,' 30' 3次 - 我需要宏来获取唯一值并添加,即只需20 + 15 + 30 = 65。

在度量计算器选项卡" - 它应该带有输出

研究没有步骤总数 1111 65

2 个答案:

答案 0 :(得分:0)

因此,如果我理解了这个问题,您需要对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

答案 1 :(得分:0)

回顾这个例子:

enter image description here

在我们的示例中,“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 unique items